gws

GBD WebSuite: basic types and interfaces.

The gws package holds the types that all parts of GBD WebSuite share: the basic data containers, enums and type aliases, the error classes, the object tree interfaces, the base Config and Props classes, and the interfaces of all configurable objects (gws.Layer, gws.Map, gws.Model, gws.Grabber, gws.Project, gws.Application and many more). Every GWS module imports it with import gws.

gws/__init__.py is generated by app/_make_init.py from this file (__init__.pyinc). Each # @include line is replaced with the contents of a *.pyinc fragment, so the types defined in core/*.pyinc and in the types.pyinc files of the other packages all end up in the gws namespace. The package also re-exports these modules of gws.core under short names:

  • gws.u: general utilities (gws.core.util),

  • gws.c: constants (gws.core.const),

  • gws.log: logging,

  • gws.debug: debugging helpers,

  • gws.env: environment variables,

and gws.ext, the decorators that register extension classes and command methods.

Code base layout

  • gws.core: the lowest layer: basic types, the object tree, logging, constants and general utilities.

  • gws.lib: general purpose libraries (CRS, images, XML, networking, SVG, styles and so on), independent of the GWS object tree.

  • gws.gis: GIS functionality built on lib: map rendering, zoom levels, source layers and tile caches.

  • gws.base: the base classes and managers of the configurable objects (application, projects, maps, layers, models, actions, auth and others).

  • gws.plugin: concrete implementations of the base classes (layer types, auth providers, OWS services, templates, model fields and so on), each registered with a gws.ext decorator.

  • gws.config: configuration parsing and loading, which builds the object tree from the configuration.

  • gws.spec: the spec generator and runtime: type metadata used to read configuration and requests and to find extension classes and commands.

  • gws.server: configuration and control of the embedded servers (uWSGI, NGINX, the spool server and the monitor).

  • gws.ext: the extension decorators (gws.ext.object.*, gws.ext.config.*, gws.ext.props.*, gws.ext.command.*). gws/ext/__init__.py is generated as well.

  • gws.test: the test framework.

The intended import hierarchy is core < lib < gis < base < plugin: each layer imports only from the layers below it. config, spec and server import lib and each other, and base imports them. Nothing outside gws.plugin imports plugins; plugin classes are found through the specs and loaded on demand.

Example:

import gws
import gws.base.layer

d = gws.Data(name='roads', crs='EPSG:3857')
d.name                                 # 'roads'
d.title                                # None, missing attributes are None
gws.u.get({'a': {'b': 1}}, 'a.b')      # 1

@gws.ext.config.layer('my')
class Config(gws.base.layer.Config):
    pass

@gws.ext.object.layer('my')
class Object(gws.base.layer.Object):
    def configure(self):
        gws.log.info(f'configuring {self.uid}')

Source code: gws

Subpackages

Package Contents

class gws.Access

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

Comma-separated rules allow <role> or deny <role>.

class gws.Action

Bases: Node

Server action.

An action is a configurable object that provides server commands.

class gws.ActionManager

Bases: Node

Action manager.

Locates actions in projects and the application and prepares command calls.

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

Get the actions a user can use in a project.

Includes the project actions and the application actions, one action per type. A project action takes precedence over an application action of the same type.

Parameters:
  • project – The project.

  • user – The user.

Returns:

A list of actions.

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

Find an action by its type.

Searches the project actions first, if a project is given, then the application actions.

Parameters:
  • project – The project, or None to search the application actions only.

  • ext_type – Action type, for example map.

  • user – The user who wants to use the action.

Returns:

The action object, or None if not found.

Raises:

ForbiddenError – If the action is found but the user may not use it.

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

Prepare a command call.

Parses the parameters into the command’s request type, finds the action that owns the command (in the requested project, then in the application) and checks the user’s access.

Parameters:
  • command_category – Command category.

  • command_name – Command name, for example mapDescribeLayer.

  • params – Raw request parameters.

  • path – Request path; for raw commands, the project uid can be given as a /projectUid/<uid> segment.

  • user – The user who runs the command.

  • read_options – Options for the spec reader.

Returns:

A tuple of the bound command method and the parsed request object.

Raises:
gws.activate_root(root: Root) → Root

Activate the root object and make it the current root.

Parameters:

root – The root object.

Returns:

The root object.

class gws.Application

Bases: Node

Application object.

The top-level node of the configuration tree. It holds the managers, the global objects and the projects, and is available as root.app.

actionMgr: ActionManager

Action manager.

actions: list[Action]

Actions available in all projects.

authMgr: AuthManager

Authorization manager.

client: Client

Default client, used by projects without their own client configuration.

databaseMgr: DatabaseManager

Database manager.

defaultPrinter: Printer

Default printer, used when no printer is configured.

exporterMgr: ExporterManager

Exporter manager.

exporters: list[Exporter]

Global exporters.

finders: list[Finder]

Finders available in all projects.

jobMgr: JobManager

Job manager.

localeUids: list[str]

Default locale uids for all projects.

metadata: Metadata

Application metadata.

middlewareMgr: MiddlewareManager

Middleware manager.

modelMgr: ModelManager

Model manager.

models: list[Model]

Global models.

monitor: ServerMonitor

Server monitor, watches configuration files and runs periodic tasks.

owsServices: list[OwsService]

OWS services provided by the server.

printerMgr: PrinterManager

Printer manager.

printers: list[Printer]

Global printers.

projects: list[Project]

Configured projects.

searchMgr: SearchManager

Search manager.

serverMgr: ServerManager

Server manager.

storageMgr: StorageManager

Storage manager.

templateMgr: TemplateManager

Template manager.

templateOptions: TemplateOptions

Options for the built-in home page templates.

templates: list[Template]

Global templates, including the built-in ones.

title: str

Application title.

vars: dict

Custom variables from the configuration.

version: str

Application version, for example 8.5.3.

versionString: str

Version string for display, with the revision if known.

webMgr: WebManager

Web manager.

developer_option(key: str)

Return the value of a developer option.

Developer options are configured in the developer property of the application config and are meant for development and debugging only.

Parameters:

key – Option name, for example template.always_reload.

Returns:

The option value, or None if it is not set.

helper(ext_type: str) → Node | None

Return a helper object by its type.

A helper that is not configured is created with default options on the first call.

Parameters:

ext_type – Helper type, for example upload.

Returns:

The helper object.

Raises:

Error – If the helper type does not exist.

project(uid: str) → Project | None

Find a project by its uid.

Parameters:

uid – Project uid.

Returns:

The project, or None if not found.

register_supported_crs(crs: Crs)

Register an additional supported CRS.

Must be called during configuration.

Parameters:

crs – The CRS object.

supported_crs() → list[Crs]

Return all CRS supported by the application.

These are the CRS of all maps and the CRS supported by OWS services, plus the registered ones. The list is computed on the first call.

Returns:

A list of CRS objects, sorted by srid.

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

Bases: Data

Application manifest, read from a MANIFEST.json file.

The manifest is JSON; lines starting with // or # are ignored.

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

Custom plugin entry in the application manifest.

name: str = ''

Plugin name. When omitted, the directory name is used.

path: DirPath

Path to the plugin directory; relative paths are resolved against the manifest location.

class gws.AttributeType

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.

exception gws.AuthenticationError

Bases: ForbiddenError

Credentials are missing, wrong or expired.

class gws.AuthManager

Bases: Node

Authorization manager.

Holds the authentication methods, providers, multi-factor adapters and the session manager, authenticates users and opens a session for every web request.

guestSession: AuthSession

Session of the guest user, used for requests without a session.

guestUser: User

The guest user.

methods: list[AuthMethod]

Authentication methods.

mfAdapters: list[AuthMultiFactorAdapter]

Multi-factor adapters.

providers: list[AuthProvider]

Authentication providers.

sessionMgr: AuthSessionManager

Session manager.

systemUser: User

The system user, allowed everything.

add_method(method: AuthMethod)

Add an authentication method.

Parameters:

method – The method.

add_multi_factor_adapter(adapter: AuthMultiFactorAdapter)

Add a multi-factor adapter.

Parameters:

adapter – The adapter.

add_provider(provider: AuthProvider)

Add an authentication provider.

Parameters:

provider – The provider.

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

Authenticate a user with the providers that allow the method.

Parameters:
  • method – The authentication method.

  • credentials – The credentials, for example username and password.

  • req – The web request.

Returns:

The user, or None if no provider accepts the credentials.

Raises:
can_use_method(req: WebRequester, method: AuthMethod) → bool

Check if a method may be used for a request.

A secure method can only be used on secure requests, or from the addresses listed in its allowInsecureFrom.

Parameters:
  • req – The web request.

  • method – The method.

Returns:

True if the method may be used.

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

Create a session that lives only for the duration of the request.

The session is not stored in the session manager.

Parameters:
  • method – The method that creates the session.

  • user – The session user.

  • data – Session data.

Returns:

A new session.

get_method(uid: str) → AuthMethod | None

Get an authentication method by its uid.

Parameters:

uid – Method uid.

Returns:

The method, or None if not found.

get_multi_factor_adapter(uid: str) → AuthMultiFactorAdapter | None

Get a multi-factor adapter by its uid.

Parameters:

uid – Adapter uid.

Returns:

The adapter, or None if not found.

get_provider(uid: str) → AuthProvider | None

Get an authentication provider by its uid.

Parameters:

uid – Provider uid.

Returns:

The provider, or None if not found.

get_user(user_uid: str) → User | None

Get a user by its global uid.

Parameters:

user_uid – Global user uid.

Returns:

The user, or None if the provider is not found or does not return the user.

is_public_object(obj: Object, *context) → bool

Check if the guest user can read an object.

Parameters:
  • obj – The object.

  • *context – Further objects to check, before the parents.

Returns:

True if the object is public.

serialize_user(user: User) → str

Serialize a user to a string, together with its provider uid.

Parameters:

user – The user.

Returns:

A JSON string.

unserialize_user(ser: str) → User | None

Restore a user serialized by serialize_user.

Parameters:

ser – The serialized user.

Returns:

The user, or None if the provider is not found.

class gws.AuthMethod

Bases: Node

Authentication method.

Defines how credentials and sessions are passed between the client and the server, for example as a login form and a session cookie.

allowInsecureFrom: list[str]

IP addresses from which the method may be used without HTTPS.

secure: bool

The method may only be used on secure (HTTPS) requests.

close_session(req: WebRequester, res: WebResponder) → None

Close the session of a request.

Called at the end of every web request whose session was opened by this method, for example to set or delete the session cookie.

Parameters:
  • req – The web request.

  • res – The web response.

open_session(req: WebRequester) → AuthSession | None

Try to open a session for a request.

Called at the start of every web request.

Parameters:

req – The web request.

Returns:

A session, or None if the request has no session for this method.

class gws.AuthMultiFactorAdapter

Bases: Node

Multi-factor authentication adapter.

Provides the second verification step of a login, for example a code sent by email or generated by an authenticator app.

lifeTime: int

Time in seconds allowed to complete the verification.

maxRestarts: int

How often a transaction can be restarted.

maxVerifyAttempts: int

Number of verification attempts allowed.

message: str

Message shown to the user during the verification step.

check_restart(mfa: AuthMultiFactorTransaction) → bool

Check if a transaction can be restarted.

Parameters:

mfa – The transaction.

Returns:

True if a restart is allowed.

check_state(mfa: AuthMultiFactorTransaction) → bool

Check if a transaction is still valid, and mark it failed if not.

Parameters:

mfa – The transaction.

Returns:

True if the transaction is valid.

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

Generate a key URI for authenticator apps.

Parameters:
  • secret – The user’s secret.

  • issuer_name – Issuer name shown in the app.

  • account_name – Account name shown in the app.

Returns:

An otpauth:// URI, or None if the adapter does not support it.

restart(mfa: AuthMultiFactorTransaction) → AuthMultiFactorTransaction | None

Restart a transaction, for example by sending a new code.

Parameters:

mfa – The transaction.

Returns:

A new transaction, or None if a restart is not possible.

start(user: User) → AuthMultiFactorTransaction | None

Start a transaction for a user.

Parameters:

user – The user who logs in.

Returns:

A new transaction, or None if the adapter cannot be used for this user, for example because a required user attribute is missing.

verify(mfa: AuthMultiFactorTransaction, payload: dict) → AuthMultiFactorTransaction

Verify a payload submitted by the user.

Parameters:
  • mfa – The transaction.

  • payload – The payload, for example {'code': '123456'}.

Returns:

The transaction with an updated state.

class gws.AuthMultiFactorState

Bases: Enum

State of a multi-factor authentication transaction.

failed = 'failed'

The transaction failed.

ok = 'ok'

The verification was successful.

open = 'open'

The transaction is started and waits for verification.

retry = 'retry'

The verification failed and can be retried.

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

Bases: Data

Multi-factor authentication transaction.

Kept in the user’s session from the login until the verification succeeds, fails or expires.

adapter: AuthMultiFactorAdapter

The adapter handling the transaction.

generateTime: int

Time when the code was last generated, as a Unix timestamp.

message: str

Message shown to the user.

restartCount: int

Number of restarts.

secret: str

Secret for code generation.

startTime: int

Start time, as a Unix timestamp.

state: AuthMultiFactorState

Current state.

user: User

The user who logs in.

verifyCount: int

Number of verification attempts.

class gws.AuthProvider

Bases: Node

Authentication provider.

A source of users, for example a file, an LDAP directory or a database table, which verifies credentials.

allowedMethods: list[str]

Method types this provider accepts, all methods if empty.

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

Authenticate a user.

Parameters:
  • method – The authentication method.

  • credentials – The credentials, for example username and password.

Returns:

The user, or None if the provider does not know the user.

Raises:

AuthenticationError – If the credentials are wrong or match more than one user.

get_user(local_uid: str) → User | None

Get a user by its local uid.

Parameters:

local_uid – User uid within the provider.

Returns:

The user, or None if not found.

serialize_user(user: User) → str

Serialize a user to a string.

Parameters:

user – The user.

Returns:

The serialized user.

unserialize_user(ser: str) → User | None

Restore a user serialized by serialize_user.

Parameters:

ser – The serialized user.

Returns:

The user, or None if it cannot be restored.

class gws.AuthSession

Authentication session.

Holds the user and arbitrary data between requests.

created: datetime.datetime

Creation time.

data: dict

Session data.

isChanged: bool

The session data has changed since the session was loaded.

isTransient: bool

The session lives only for the duration of the request and is not stored.

method: AuthMethod | None

The method that created the session, None for the guest session.

uid: str

Session uid.

updated: datetime.datetime

Last update time.

user: User

The session user.

get(key: str, default=None)

Get a session data value.

Parameters:
  • key – Value name.

  • default – Default value.

Returns:

The value, or the default if it is not set.

set(key: str, value)

Set a session data value and mark the session as changed.

Parameters:
  • key – Value name.

  • value – The value.

class gws.AuthSessionManager

Bases: Node

Authentication session manager.

Stores sessions persistently. A session is valid until lifeTime has passed since its last update, or maxLifeTime since its creation.

lifeTime: int

Session life time in seconds, counted from the last update.

maxLifeTime: int

Absolute session life time in seconds, counted from the creation, or 0 if not limited.

cleanup()

Remove expired sessions from the storage.

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

Create and store a new session.

Parameters:
  • method – The method that creates the session.

  • user – The session user.

  • data – Session data.

Returns:

The new session.

delete(sess: AuthSession)

Delete a session.

Parameters:

sess – The session.

delete_all()

Delete all sessions.

get(uid: str) → AuthSession | None

Get a valid session by its uid.

Parameters:

uid – Session uid.

Returns:

The session, or None if it does not exist or has expired.

list_all() → list[AuthSession]

Get all stored sessions.

Returns:

A list of sessions.

save(sess: AuthSession)

Save the session data.

Parameters:

sess – The session.

touch(sess: AuthSession)

Update the last activity time of a session.

Parameters:

sess – The session.

class gws.Axis

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: an extent together with its CRS.

crs: Crs

Coordinate reference system of the extent.

extent: Extent

Extent in the coordinates of crs.

type gws.ClassRef = type | str

a type, an ext class or name like gws.ext.object.layer, or a full class name.

Type:

Class reference

class gws.Client

Bases: Node

Settings for the browser client: UI elements and client options.

elements: list

Client UI elements.

options: dict

Client options.

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

Bases: Data

Parameters of a command line command.

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

Bases: Enum

Command category.

api = 'api'

API command.

cli = 'cli'

CLI command.

get = 'get'

Web GET command.

post = 'post'

Web POST command.

raw = 'raw'

Raw Web command without preprocessing.

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

Bases: Data

Object configuration.

uid: str = ''

Unique ID.

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

Bases: Data

Shared state for parsing and validating a configuration.

errors: list[ConfigErrorInfo]

Errors collected so far.

paths: set[str]

Paths of all configuration files that were read, including included files.

readOptions: set[SpecReadOption]

Options passed to the spec reader.

specs: SpecRuntime

Specs used to validate the configuration.

warnings: list[ConfigErrorInfo]

Warnings collected so far.

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

Bases: Data

Full information about a configuration error.

cause: str

Representation of the exception that caused the error.

contextLines: list[str]

Source lines around the error, with line numbers, the error line is marked with >>>.

line: int

Line number where the error occurred.

message: str

Error message.

path: str

Path to the configuration file.

stack: list[ConfigLocation]

Locations of the objects being configured when the error occurred, innermost first.

value: str

Value that caused the error.

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

Bases: Data

Location in the configuration tree.

objectName: str

Name of the object.

objectType: str

Type of the object.

objectUid: str

UID of the object.

propName: str

Property of the parent this object is located at.

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

Bases: Data

Result of a configuration run.

config: Config | None

Parsed application configuration.

errors: list[ConfigErrorInfo]

Configuration errors.

info: str

Summary with the number of objects, time and memory used.

root: Root | None

Configured root object, or None if configuration failed or was not requested.

warnings: list[ConfigErrorInfo]

Configuration warnings.

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 rules per operation.

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

Bases: Response

Web response with literal content.

content: bytes | str

Response content.

contentFilename: str

File name for the attachment. If provided, the content is served as an attachment.

contentPath: str

Local path with the content.

headers: dict

Additional headers.

mimeType: str

Response mime type.

gws.create_root(specs: SpecRuntime) → Root

Create a new root object.

Parameters:

specs – Specs runtime.

Returns:

The root object.

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.

wgsMaxExtent: Extent

Maximal extent that makes sense for this CRS, in the WGS projection.

wkt: str

WKT definition.

axis_for_format(fmt: CrsFormat) → Axis

Get the axis orientation implied by a CRS name format.

For CRSs with a lat/lon axis, the orientation depends on how the CRS is named. We adhere to the GeoServer convention: the srid, epsg, url and uri formats imply XY, the urn and urnx formats imply YX (see https://docs.geoserver.org/latest/en/user/services/wfs/axis_order.html). For XY CRSs, the own axis is always returned.

Parameters:

fmt – CRS name format.

Returns:

The axis orientation.

clip_wgs_extent(wgs_extent: Extent) → Extent | None

Clip a WGS extent to the maximal extent of this CRS.

Parameters:

wgs_extent – Extent in the WGS projection.

Returns:

The clipped extent in the WGS projection, or None if there is no intersection.

extent_size_in_meters(extent: Extent) → Size

Calculate the width and height of an extent in meters.

For projected CRSs, the extent size is returned as is. For geographic CRSs, geodesic distances on the WGS84 ellipsoid are measured along the middle latitude and the middle longitude of the extent.

Parameters:

extent – Extent in this CRS.

Returns:

A (width, height) tuple in meters.

Raises:

gws.lib.crs.Error – If this is a projected CRS with units other than meters.

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

Calculate a point at a given distance and direction from another point.

Parameters:
  • xy – Point in this CRS.

  • dist – Distance in meters.

  • az – Azimuth in degrees (0 = North, 90 = East, etc.).

Returns:

The offset point in this CRS.

Raises:

gws.lib.crs.Error – If this is a projected CRS with units other than meters.

to_geojson() → dict

Return a GeoJSON representation of the CRS.

The CRS is represented as a “named CRS” with its urn name, as per the 2008 GeoJSON specification (https://geojson.org/geojson-spec#named-crs).

Returns:

A GeoJSON crs dict.

to_string(fmt: CrsFormat | None = None) → str

Return the name of the CRS in a given format.

Parameters:

fmt – Format to use, CrsFormat.epsg by default.

Returns:

The CRS name, like EPSG:3857.

transform_extent(extent: Extent, crs_to: Crs) → Extent

Transform an Extent from this CRS to another.

The transformation goes through WGS84. If the extent is very large (almost the whole world) and the target CRS has a limited area of use, the result is computed by sampling points, so that it stays finite.

Parameters:
  • extent – Extent in this CRS.

  • crs_to – Target CRS.

Returns:

The transformed Extent, with min and max values in order.

transform_resolution(extent: Extent, res: float, crs_to: Crs) → float

Transform a resolution over an extent from this CRS to another.

The returned resolution is the finest one found at a set of sample points of the extent, so that the target resolution is never coarser than the source resolution anywhere in the extent.

Parameters:
  • extent – Extent in this CRS.

  • res – Resolution in units of this CRS per pixel.

  • crs_to – Target CRS.

Returns:

The resolution in units of the target CRS per pixel, or 0.0 if the transformation fails.

transformer(crs_to: Crs) → Callable

Create a transformer function to another CRS.

The function always uses the XY (easting/longitude first) axis order.

Parameters:

crs_to – Target CRS.

Returns:

A function that takes x, y and returns a transformed (x, y) tuple.

class gws.CrsFormat

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 more dict or Data arguments and/or keyword args. All 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.

Example:

d = gws.Data({'a': 1}, b=2)
d.a     # 1
d['b']  # 2
d.c     # None
get(key, default=None)

Get an attribute value.

Parameters:
  • key – Attribute name.

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

Returns:

The attribute value or the default.

set(key, val)

Set an attribute value.

Parameters:
  • key – Attribute name.

  • val – Attribute value.

setdefault(key, val)

Set an attribute value if it is not already set.

Parameters:
  • key – Attribute name.

  • val – Attribute value.

Returns:

The current attribute value, existing or new.

update(*args, **kwargs)

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

Later values override earlier ones, keywords override args.

Parameters:
  • *args – Dicts, Mappings or Data objects. Other values are ignored.

  • **kwargs – Keyword args.

class gws.DatabaseConnection

Database connection.

Wraps an SQLAlchemy Connection and provides some convenience methods. Returned by DatabaseProvider.begin. The connection does not control the transaction: it is committed or rolled back by begin.

Statements can be SQLAlchemy objects or SQL strings with :name bind parameters.

saConn: sqlalchemy.Connection

The underlying SQLAlchemy connection.

execute(stmt: DatabaseStmt, params=None, execution_options: dict = None) → sqlalchemy.CursorResult

Execute a statement.

Parameters:
  • stmt – Statement or SQL string.

  • params – Bind parameters, a dict or a list of dicts.

  • execution_options – SQLAlchemy execution options.

Returns:

The result.

fetch_all(stmt: DatabaseStmt, **params) → list[dict]

Execute a statement and return all rows.

Parameters:
  • stmt – Statement or SQL string.

  • **params – Bind parameters.

Returns:

A list of rows as dicts.

fetch_first(stmt: DatabaseStmt, **params) → dict | None

Execute a statement and return the first row.

Parameters:
  • stmt – Statement or SQL string.

  • **params – Bind parameters.

Returns:

The first row as a dict, or None if there are no rows.

fetch_int(stmt: DatabaseStmt, **params) → int | None

Execute a statement and return the first column of the first row as an integer.

Parameters:
  • stmt – Statement or SQL string.

  • **params – Bind parameters.

Returns:

The integer, or None if there are no rows or the value is NULL.

Raises:

ValueError – If the value is not an integer.

fetch_ints(stmt: DatabaseStmt, **params) → list[int]

Execute a statement and return the first column of all rows as integers.

Parameters:
  • stmt – Statement or SQL string.

  • **params – Bind parameters.

Returns:

A list of integers.

Raises:

ValueError – If a value is not an integer.

fetch_scalar(stmt: DatabaseStmt, **params) → Any

Execute a statement and return the first column of the first row.

Parameters:
  • stmt – Statement or SQL string.

  • **params – Bind parameters.

Returns:

The value, or None if there are no rows.

fetch_scalars(stmt: DatabaseStmt, **params) → list

Execute a statement and return the first column of all rows.

Parameters:
  • stmt – Statement or SQL string.

  • **params – Bind parameters.

Returns:

A list of values.

fetch_string(stmt: DatabaseStmt, **params) → str | None

Execute a statement and return the first column of the first row as a string.

Parameters:
  • stmt – Statement or SQL string.

  • **params – Bind parameters.

Returns:

The string, or None if there are no rows or the value is NULL.

fetch_strings(stmt: DatabaseStmt, **params) → list[str]

Execute a statement and return the first column of all rows as strings.

Parameters:
  • stmt – Statement or SQL string.

  • **params – Bind parameters.

Returns:

A list of strings, with NULL values as empty strings.

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

Bases: Data

Options for database inspection.

cacheLifeTime: int = 0

Schema cache lifetime in seconds.

refresh: bool = False

Whether to force inspection even if cached information is available.

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 a database provider and add it to providers.

The provider is created as a shared object. A provider with the same uid that is already in providers is replaced.

Parameters:
  • cfg – Provider configuration.

  • **kwargs – Extra configuration values.

Returns:

The provider.

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

Find a database provider by uid or type.

With uid, returns the provider with this uid (and of type ext_type, if given). With ext_type only, returns the first provider of this type. Without arguments, returns the first provider.

Parameters:
  • uid – Provider uid.

  • ext_type – Provider type, e.g. postgres.

Returns:

The provider, or None if none matches.

class gws.DatabaseModel

Bases: Model

Data model for a database table.

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 SELECT statement for a search.

Combines the search query in mc.search, the columns and conditions collected by the fields in mc.dbSelect and sqlFilter.

Parameters:

mc – Model context with search and dbSelect set.

Returns:

The SELECT statement, or None if the search cannot match anything.

column(column_name: str) → sqlalchemy.Column

Return the SQLAlchemy Column object of a column in the model table.

Parameters:

column_name – Column name.

Returns:

The column object.

Raises:

sqlalchemy.exc.SQLAlchemyError – If the table or the column does not exist.

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

Run a SELECT statement and create a feature for each row.

The row values become the attributes of the feature record.

Parameters:

select – SELECT statement.

Returns:

A list of features.

table() → sqlalchemy.Table

Return the SQLAlchemy Table object of the model table.

Returns:

The table object.

Raises:

sqlalchemy.exc.SQLAlchemyError – If the table does not exist.

uid_column() → sqlalchemy.Column

Return the SQLAlchemy Column object of the primary key column.

Returns:

The column object for uidName.

Raises:

gws.Error – If the model has no primary key or the key column does not exist.

uid_equals(uid: FeatureUid | Iterable[FeatureUid]) → sqlalchemy.ColumnElement[bool]

Return a condition that matches features by uid.

The values are bound with the type of the primary key column, so that string uids can be compared with columns of other types.

Parameters:

uid – A feature uid, or an iterable of uids.

Returns:

An = condition for a single uid, an IN condition for an iterable.

Raises:

gws.Error – If the model has no primary key or the key column does not exist.

class gws.DatabaseProvider

Bases: Node

Database provider.

Wraps an SQLAlchemy Engine and hands out connections. Also reflects table structures and describes tables and columns.

autocommit_connection() → ContextManager[DatabaseConnection]

Open a separate connection in autocommit mode, to be used as a context manager.

For statements that cannot run inside a transaction, like VACUUM. The connection is not shared with begin.

Returns:

A context manager that yields the connection.

Raises:

gws.Error – If a transaction of this provider is open in the current thread.

begin(nested: bool = False) → ContextManager[DatabaseConnection]

Begin a transaction, to be used as a context manager.

The outermost call opens a connection and begins a transaction, which is committed on normal exit and rolled back on an exception. Inner calls in the same thread join the open transaction, or create a savepoint if nested is set:

with db.begin() as conn:
    conn.execute('INSERT ...')
    with db.begin() as conn2:  # same connection and transaction
        rows = conn2.fetch_all('SELECT ...')
    with db.begin(nested=True) as conn3:  # savepoint
        conn3.execute('UPDATE ...')
# committed, connection closed

Unlike SQLAlchemy Engine.begin, an inner call does not open a new connection. Each provider keeps its own connection per thread.

Parameters:

nested – Create a savepoint when joining an open transaction. An exception inside the block then rolls back to the savepoint only. Has no effect on the outermost call.

Returns:

A context manager that yields the connection.

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

Return the SQLAlchemy Column object for a column.

Parameters:
  • table – Table object or table name.

  • column_name – Column name.

Returns:

The column object.

Raises:

sqlalchemy.exc.SQLAlchemyError – If the table or the column does not exist.

connect() → ContextManager[DatabaseConnection]

Deprecated, same as begin.

count(table: DatabaseTableAlike) → int

Return the number of rows in a table.

Parameters:

table – Table object or table name.

Returns:

The row count, or 0 if the table does not exist.

create_engine(**kwargs) → sqlalchemy.Engine

Create a new SQLAlchemy Engine object for this provider.

Parameters:

**kwargs – Engine options, see engine_options.

Returns:

The engine.

describe(table: DatabaseTableAlike) → DataSetDescription

Describe a table.

Parameters:

table – Table object or table name.

Returns:

The table description. The first geometry column becomes the primary geometry.

Raises:

sqlalchemy.exc.SQLAlchemyError – If the table does not exist.

describe_column(table: DatabaseTableAlike, column_name: str) → ColumnDescription

Describe a column in a table.

Parameters:
  • table – Table object or table name.

  • column_name – Column name.

Returns:

The column description.

Raises:

sqlalchemy.exc.SQLAlchemyError – If the table or the column does not exist.

engine() → sqlalchemy.Engine

Return the SQLAlchemy Engine object for this provider, creating it if needed.

Returns:

The engine.

engine_options(**kwargs)

Add defaults to the SQLAlchemy engine options.

Parameters:

**kwargs – Engine options. Options passed here take precedence over the defaults.

Returns:

The options dict.

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

Execute a textual statement in a transaction, see begin.

Parameters:
  • sql – SQL statement with :name bind parameters.

  • **kwargs – Bind parameters.

Returns:

The result.

Raises:

sqlalchemy.exc.SQLAlchemyError – On database errors.

has_column(table: DatabaseTableAlike, column_name: str) → bool

Check if a column exists.

Parameters:
  • table – Table object or table name.

  • column_name – Column name.

Returns:

True if the table and the column exist.

has_schema(schema_name: str) → bool

Check if a schema exists.

Parameters:

schema_name – Schema name.

Returns:

True if the schema exists.

has_table(table_name: str) → bool

Check if a table exists.

Parameters:

table_name – Table name, optionally schema-qualified.

Returns:

True if the table exists.

inspect_schema(schema: str, options: DatabaseInspectOptions | None = None)

Reflect the tables of a schema and keep the result.

A schema that has already been reflected is not reflected again, unless options.refresh is set. The reflected metadata is cached for the configured schema cache lifetime. If options are given, their cacheLifeTime is used instead; 0 means no caching.

Parameters:
  • schema – Schema name.

  • options – Inspection options.

join_table_name(schema: str, name: str) → str

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

Parameters:
  • schema – Schema name. If empty, the default schema is used.

  • name – Table name.

Returns:

The schema-qualified table name.

schema_names() → list[str]

Return the names of the schemas in the database.

Returns:

A list of schema names.

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

Execute a textual SELECT statement.

Parameters:
  • sql – SQL statement with :name bind parameters.

  • **kwargs – Bind parameters.

Returns:

A list of rows as dicts.

Raises:

sqlalchemy.exc.SQLAlchemyError – On database errors.

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

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

Parameters:

table_name – Table name, optionally schema-qualified.

Returns:

A tuple of the schema name (the default schema if none is given) and the table name.

table(table: DatabaseTableAlike, **kwargs) → sqlalchemy.Table

Return the SQLAlchemy Table object for a table.

Parameters:
  • table – Table object or table name.

  • **kwargs – Not used by the base provider.

Returns:

The table object.

Raises:

sqlalchemy.exc.SQLAlchemyError – If the table does not exist.

table_bounds(table: DatabaseTableAlike) → Bounds | None

Compute the bounding box of the primary geometry of a table.

Parameters:

table – Table object or table name.

Returns:

The bounds, or None if the table has no geometry or no data.

url() → str

Return the connection URL.

Returns:

An SQLAlchemy 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

Format a date.

Parameters:
  • fmt – Format type, or a babel (CLDR) date pattern like dd.MM.yyyy.

  • date – Date or date string, the current date by default.

Returns:

The formatted date.

Raises:

Error – If the date cannot be parsed.

iso(date=None) → str

Format a date in the ISO 8601 format, e.g. 2013-12-11.

Parameters:

date – Date or date string, the current date by default.

Returns:

The formatted date.

long(date=None) → str

Format a date in the long format of the locale, e.g. 11. Dezember 2013.

Parameters:

date – Date or date string, the current date by default.

Returns:

The formatted date.

medium(date=None) → str

Format a date in the medium format of the locale, e.g. 11.12.2013.

Parameters:

date – Date or date string, the current date by default.

Returns:

The formatted date.

short(date=None) → str

Format a date in the short format of the locale, e.g. 11.12.13.

Parameters:

date – Date or date string, the current date by default.

Returns:

The formatted date.

type gws.DateStr = str

ISO date string like 2019-01-30.

class gws.DateTimeFormat

Bases: Enum

Date or 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.

gws.deactivate_root()

Remove the current root.

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

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.

Its repr is the first line of log.exception_backtrace: the class name, the message and the location.

gws.ErrorValue

Special value for invalid fields.

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

Bases: Data

Arguments passed to Exporter.run.

exporter: Exporter

The exporter.

features: list[Feature] | None

Features to export.

maxErrors: int = 100

Maximum number of errors collected in the result.

notify: Callable

Progress callback, called with an event name.

project: Project

Project of the export request.

shape: Shape | None

Shape from the export request.

user: User

User the export runs for.

class gws.Exporter

Bases: Node

Exporter.

Writes features to files in a specific format.

options: dict

Format-specific options, passed to the GDAL driver.

supportedAttributeTypes: list[AttributeType] | None

Attribute types the exporter can write. If empty, the types supported by GDAL are used.

supportsMultiLayer: bool

The format can hold several layers in one file.

supportsRaster: bool

The exporter can export raster data.

supportsVector: bool

The exporter can export vector features.

title: str

Exporter title, shown in the client.

withMixedCrs: bool

Allow different CRS in one layer instead of skipping features.

withMixedGeometry: bool

Allow different geometry types in one layer instead of skipping features.

withMultiLayer: bool

Write all layers to one file.

withNoGeometry: bool

Export features without geometry instead of skipping them.

run(ea: ExportArgs, er: ExportResult)

Export the features.

Writes the result file and sets its path, the mime type, the counts and errors in the export result.

Parameters:
  • ea – Export arguments.

  • er – Export result, filled by the exporter.

class gws.ExporterManager

Bases: Node

Exporter manager.

exec_export(request: ExportRequest, out_path: str)

Run an export directly, as the system user, and copy the result file.

Parameters:
  • request – Export request.

  • out_path – Path to copy the result file to.

Returns:

The export result.

Raises:

gws.Error – If no features were exported.

get_exporter(where: list[Node], uid: str, user: User) → Exporter | None

Find an exporter by uid among the exporters the user can use.

Parameters:
  • where – Objects with an exporters list, e.g. a project and the application.

  • uid – Exporter uid.

  • user – User.

Returns:

The exporter, or None if it is not found.

list_exporters(where: list[Node], user: User) → list[Exporter]

List the exporters of the given objects that the user can use.

Of several exporters with the same title, only the first one is listed.

Parameters:
  • where – Objects with an exporters list, e.g. a project and the application. None entries are ignored.

  • user – User.

Returns:

A list of exporters.

start_export_job(request: ExportRequest, user: User) → JobStatusResponse

Create and schedule a background export job.

Parameters:
  • request – Export request.

  • user – User the export runs for.

Returns:

The status of the new job.

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

Bases: Request

Export request from the client.

exporterUid: str

Uid of the exporter.

features: list[FeatureProps] | None

Features to export.

shape: ShapeProps | None

Shape passed to the exporter.

type: ExportRequestType

Kind of data to export.

class gws.ExportRequestType

Bases: Enum

Kind of data to export.

raster = 'raster'

Raster data.

vector = 'vector'

Vector features.

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

Bases: Response

Export response with the content of the result file.

content: str | bytes

File content.

contentFilename: str

File name.

mimeType: str

Mime type.

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

Bases: Data

Export result.

errors: list[str]

Error messages for features that were not exported.

mimeType: str

Mime type of the result file.

numFeaturesExported: int

Number of exported features.

numFeaturesTotal: int

Number of requested features.

numFiles: int

Number of files written.

path: str

Path of the result file, empty if nothing was exported.

class gws.ExportTarget

Bases: Enum

Export target.

download = 'download'

Return the export result for download.

file = 'file'

Save the export result to a file on the server.

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

Bases: Data

Command descriptor, describes the action method that handles a command.

extCommandCategory: CommandCategory

Command category.

extName: str

Full command name like gws.ext.command.api.mapGetBox.

extType: str

Command name like mapGetBox.

methodName: str

Name of the action method that handles the command.

methodPtr: Callable

Command method. Not set by SpecRuntime.command_descriptor.

owner: ExtObjectDescriptor

Object descriptor of the action class that owns the command.

request: Request

Request sent to the command. Not set by SpecRuntime.command_descriptor.

tArg: str

Type uid of the command argument (the request).

tOwner: str

Type uid of the action class that owns the command.

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

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

exception gws.ExternalServiceError

Bases: Error

Generic error when an external service fails.

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.

A set of named attributes that belongs to a model. The model defines the uid attribute (uidName) and the geometry attribute (geometryName).

attributes: dict

Attribute values as python values.

category: str

Category for grouping features in the client, e.g. the source layer name.

createWithFeatures: list[Feature]

Related features a new feature is created with.

cssSelector: str

CSS selector for the feature style in the client.

errors: list[ModelValidationError]

Validation errors.

insertedPrimaryKey: int | str | None

Primary key of the row inserted when the feature was created.

isNew: bool

The feature is new and not yet saved.

model: Model

Model the feature belongs to.

props: FeatureProps

Data from or for the client.

record: FeatureRecord

Raw data from or for the source.

views: dict

Rendered views, keyed by view name, e.g. title or label.

get(name: str, default=None) → Any

Get an attribute value.

Parameters:
  • name – Attribute name.

  • default – Value to return if the attribute does not exist.

Returns:

The attribute value, or default.

has(name: str) → bool

Check if an attribute exists.

Parameters:

name – Attribute name.

Returns:

True if the attribute exists.

raw(name: str) → Any

Get a raw attribute value from the record.

Parameters:

name – Attribute name.

Returns:

The value, or None if the record has no such attribute.

render_views(templates: list[Template], **kwargs) → Feature

Render feature views and store them in views.

Each template renders the view named after the last part of its subject, e.g. feature.title renders title. The templates receive the feature attributes, feature and the extra arguments.

Parameters:
  • templates – Feature templates.

  • **kwargs – Extra template arguments.

Returns:

The feature itself.

set(name: str, value: Any) → Feature

Set an attribute value.

Parameters:
  • name – Attribute name.

  • value – Attribute value.

Returns:

The feature itself.

shape() → Shape | None

Get the feature geometry.

Returns:

The geometry, or None if the model has no geometry or the feature has no value.

to_geojson(keep_crs=False) → dict

Convert the feature to a GeoJSON feature.

The geometry is converted to WGS84 unless keep_crs is set. The uid is added as the id property.

Parameters:

keep_crs – Keep the geometry coordinates in the feature CRS.

Returns:

A GeoJSON feature dict.

to_svg(view: MapView, label: str | None = None, style: Style | None = None) → list[XmlElement]

Render the feature geometry as SVG fragments for a map view.

Parameters:
  • view – Map view. The geometry is transformed to its CRS.

  • label – Label text.

  • style – Style.

Returns:

A list of SVG elements, empty if the feature has no geometry.

transform_to(crs: Crs) → Feature

Transform the feature geometry to another CRS, in place.

Parameters:

crs – Target CRS.

Returns:

The feature itself.

uid() → FeatureUid

Get the unique id of the feature.

Returns:

The value of the uid attribute as a string, an empty string if the model has no uid attribute, or None if the feature has no value.

class gws.FeatureExportStrategy

Bases: Enum

How exported features are obtained.

client = 'client'

Export features using properties as received from the client.

load = 'load'

Load features by ids from the source model.

class gws.FeatureLoadingStrategy

Bases: Enum

When the client loads a layer’s features.

all = 'all'

Load all features once, on first display.

bbox = 'bbox'

Reload features for the current map extent whenever it changes.

lazy = 'lazy'

Load features only when a search text is entered.

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

Attribute values as read from the source or as written to it.

ewkt: str

Geometry as EWKT, provided by some sources.

meta: dict

Extra source information, e.g. layerName for features from OWS responses.

shape: Shape | None

Geometry provided by the source.

uid: str | None

Feature id provided by the source.

type gws.FeatureUid = str

Unique Feature id.

type gws.FilePath = str

File path on the server.

class gws.Finder

Bases: Node

Search provider, finds features for search queries.

category: str

Category assigned to the results.

models: list[Model]

Models used to read the features.

sourceLayers: list[SourceLayer]

Source layers to search in, for finders of OWS and QGIS sources.

supportsFilterSearch: bool = False

The finder supports filter searches.

supportsGeometrySearch: bool = False

The finder supports geometry searches.

supportsKeywordSearch: bool = False

The finder supports keyword searches.

templates: list[Template]

Templates to format the found features.

title: str

Finder title.

tolerance: UomValue

Tolerance for geometry searches.

withFilter: bool

Filter searches are enabled.

withGeometry: bool

Geometry searches are enabled.

withKeyword: bool

Keyword searches are enabled.

can_run(search: SearchQuery, user: User) → bool

Check if the finder can run a search query.

Parameters:
  • search – Search query.

  • user – User running the search.

Returns:

True if the finder can run the query.

run(search: SearchQuery, user: User, layer: Layer | None = None) → list[Feature]

Run a search query.

Parameters:
  • search – Search query.

  • user – User running the search.

  • layer – Layer the finder belongs to, if any.

Returns:

Found features.

exception gws.ForbiddenError

Bases: Error

Generic ‘forbidden’ error.

type gws.FormatStr = str

Format string as used in Python.

class gws.GeometryType

Bases: Enum

Feature geometry type.

OGC and SQL/MM geometry types.

References

circularstring = 'circularstring'

Circular arc string.

compoundcurve = 'compoundcurve'

Curve composed of line strings and circular strings.

curve = 'curve'

Curve.

curvepolygon = 'curvepolygon'

Polygon with curved rings.

geometry = 'geometry'

Any geometry.

geometrycollection = 'geometrycollection'

Collection of geometries.

line = 'line'

Line.

linearring = 'linearring'

Linear ring.

linestring = 'linestring'

Line string.

multicurve = 'multicurve'

Collection of curves.

multilinestring = 'multilinestring'

Collection of line strings.

multipoint = 'multipoint'

Collection of points.

multipolygon = 'multipolygon'

Collection of polygons.

multisurface = 'multisurface'

Collection of surfaces.

point = 'point'

Point.

polygon = 'polygon'

Polygon.

polyhedralsurface = 'polyhedralsurface'

Polyhedral surface.

surface = 'surface'

Surface.

tin = 'tin'

Triangulated irregular network.

triangle = 'triangle'

Triangle.

gws.get_root() → Root

Return the current root object.

Returns:

The root object set by activate_root or load_root.

Raises:

Error – If there is no current root.

class gws.Grabber

Raster grabber.

Provides raster images for a layer: fetches them from a source, aligns them to a tile grid, stores and reads them back.

cache: MapCache

Cache settings; the name (<layer cache name>_<srid>) keys the tile store.

extent: Extent

Extent covered by this grabber, in the target CRS.

grid: MapGrid

The fixed target grid for the CRS.

imageFormat: ImageFormat

Format tiles are stored and returned in.

sourceCrs: Crs

Source CRS; defines the original CRS of the raster data.

store: TileStore

Persistent tile store.

targetCrs: Crs

Target CRS; one grabber serves exactly one CRS.

get_box_as_bytes(extent: Extent, w: int, h: int, params: dict | None = None) → bytes

Return an encoded image for arbitrary extent and pixel size.

A box overlapping no data is a transparent image.

Parameters:
  • extent – Extent in the target CRS.

  • w – Width in pixels.

  • h – Height in pixels.

  • params – Dynamic request parameters. With params, the persistent store is bypassed.

Returns:

The encoded image.

Raises:

Exception – Errors of the source request are passed through.

get_box_as_image(extent: Extent, w: int, h: int, params: dict | None = None) → Image

Return an image for arbitrary extent and pixel size.

Same contract as get_box_as_bytes, decoded pixels instead of bytes.

Parameters:
  • extent – Extent in the target CRS.

  • w – Width in pixels.

  • h – Height in pixels.

  • params – Dynamic request parameters. With params, the persistent store is bypassed.

Returns:

The image.

Raises:

Exception – Errors of the source request are passed through.

get_tile_as_bytes(mt: MapTile, params: dict | None = None) → bytes

Return a single tile as an encoded image, composing and storing it if needed.

A tile outside the layer’s range is a transparent image.

Parameters:
  • mt – Tile.

  • params – Dynamic request parameters. With params, the persistent store is bypassed.

Returns:

The encoded tile.

Raises:

Exception – Errors of the source request are passed through.

get_tile_as_image(mt: MapTile, params: dict | None = None) → Image

Return a single tile as an image, composing and storing it if needed.

Same contract as get_tile_as_bytes, decoded pixels instead of bytes.

Parameters:
  • mt – Tile.

  • params – Dynamic request parameters. With params, the persistent store is bypassed.

Returns:

The tile image.

Raises:

Exception – Errors of the source request are passed through.

get_tiles_as_bytes_dict(mtr: MapTileRange, params: dict | None = None) → dict[MapTile, bytes]

Return a rectangular block of tiles as encoded images.

Parameters:
  • mtr – Tile range.

  • params – Dynamic request parameters. With params, the persistent store is bypassed.

Returns:

contains entries only for tiles present in the grid.

Return type:

Encoded tiles, keyed by tile. Sparse

Raises:

Exception – Errors of the source request are passed through.

get_tiles_as_image_dict(mtr: MapTileRange, params: dict | None = None) → dict[MapTile, Image]

Return a rectangular block of tiles as images.

Same contract as get_tiles_as_bytes_dict, decoded pixels instead of bytes.

Parameters:
  • mtr – Tile range.

  • params – Dynamic request parameters. With params, the persistent store is bypassed.

Returns:

Tile images, keyed by tile.

Raises:

Exception – Errors of the source request are passed through.

levels() → list[int]

Return the levels this grabber supports.

Returns:

A list of levels.

tile_range_for_level(z: int) → MapTileRange

Return the tile range covered by the grabber’s extent at a level.

Parameters:

z – Level.

Returns:

The tile range in the grabber’s grid.

class gws.Image

Raster image.

Manipulation methods change the image in place and return the image itself, so that calls can be chained.

add_box(color=None) → Image

Draw a 1 pixel wide frame along the image edges.

The image is converted to RGBA.

Parameters:

color – Line color, black by default.

Returns:

The image.

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

Draw text on the image with the default font.

The image is converted to RGBA.

Parameters:
  • text – Text, can contain multiple lines.

  • x – X coordinate of the top left corner of the text.

  • y – Y coordinate of the top left corner of the text.

  • color – Text color, black by default.

Returns:

The image.

compare_to(other: Image) → float

Compare this image to another one.

Computes the mean squared difference of the RGBA channels over all pixels, normalized to the range 0 to 1. Both images must be RGBA and have the same size.

Parameters:

other – Image to compare to.

Returns:

0 if the images are equal, larger values for larger differences.

compose(other: Image, opacity=1) → Image

Place another image on top of this one, using alpha composition.

The other image is resized to the size of this one if needed.

Parameters:
  • other – Image to place on top.

  • opacity – Opacity of the other image, from 0 to 1.

Returns:

The image.

convert(mode: str) → Image

Convert the image to a mode.

Parameters:

mode – PIL image mode.

Returns:

The image.

crop(box) → Image

Crop the image.

Parameters:

box – Crop rectangle (left, upper, right, lower) in pixels.

Returns:

The image.

mode() → str

Get the image mode.

Returns:

PIL image mode, e.g. RGBA.

paste(other: Image, where=None) → Image

Paste another image into this one.

Parameters:
  • other – Image to paste.

  • where – Position (x, y) of the upper left corner, or a box (left, upper, right, lower). By default, the image is pasted at (0, 0).

Returns:

The image.

resize(size: Size, **kwargs) → Image

Resize the image to a size, without keeping the aspect ratio.

Parameters:
  • size – New size (width, height).

  • **kwargs – Options for PIL.Image.resize. The default resampling is bicubic.

Returns:

The image.

resize_to(width: int = 0, height: int = 0, **kwargs) → Image

Resize the image to a width, a height or both.

If only one dimension is given, the other is computed to keep the aspect ratio. If none is given, the image is not changed.

Parameters:
  • width – New width.

  • height – New height.

  • **kwargs – Options for PIL.Image.resize.

Returns:

The image.

rotate(angle: int, **kwargs) → Image

Rotate the image counter-clockwise.

Parameters:
  • angle – Angle in degrees.

  • **kwargs – Options for PIL.Image.rotate. The default resampling is bicubic.

Returns:

The image.

size() → Size

Get the image size.

Returns:

A tuple (width, height) in pixels.

to_array() → numpy.typing.NDArray

Convert the image to a numpy array.

Returns:

An array of shape (height, width) or (height, width, channels).

to_base64(mime_type: str | None = None, options: dict | None = None) → str

Encode the image as a base64 string.

Parameters:
  • mime_type – MIME type of the output, PNG by default.

  • options – Encoding options, as in to_bytes.

Returns:

The base64 encoded image.

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

Encode the image.

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, with an adaptive palette.

An additional option background sets the color to replace the alpha channel with when an RGBA image is saved as JPEG (default is white).

Parameters:
  • mime_type – MIME type of the output, PNG by default.

  • options – Encoding options.

Returns:

The encoded image.

to_data_url(mime_type: str | None = None, options: dict | None = None) → str

Encode the image as a base64 data URL.

Parameters:
  • mime_type – MIME type of the output, PNG by default.

  • options – Encoding options, as in to_bytes.

Returns:

A data: URL.

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

Encode the image and save it to a file.

Parameters:
  • path – File path.

  • mime_type – MIME type of the output, PNG by default.

  • options – Encoding options, as in to_bytes.

Returns:

The file path.

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

Bases: Data

Image format: MIME types and encoding options.

mimeTypes: list[str]

MIME types for this format.

name: str

Name of the format.

options: dict

Encoding options, as accepted by Image.to_bytes.

gws.is_data_object(x)

Check if the argument is a Data object.

Parameters:

x – A value.

Returns:

True if the value is a Data object.

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

Bases: Data

Background job data.

error: str

Error message, if the job failed.

numSteps: int

Total number of steps, for progress reporting.

payload: dict

Input data for the worker.

result: dict

Result data from the worker.

state: JobState

Job state.

step: int

Current step.

stepName: str

Name of the current step.

timeCreated: datetime.datetime

Creation time.

timeUpdated: datetime.datetime

Time of the last update.

uid: str

Job uid.

user: User

User who created the job.

worker: str

Worker class, as <module path>:<class name>.

class gws.JobManager

Bases: Node

Job manager.

cancel_job(job: Job) → Job | None

Set a job to the cancel state.

The worker notices the change on its next job update and stops.

Parameters:

job – The job.

Returns:

The updated job, or None if the job does not exist.

create_job(worker: type, user: User, payload: dict | Data = None) → Job

Create a job in the open state.

Parameters:
  • worker – Worker class. It must have a run(root, job) class method.

  • user – User the job runs for.

  • payload – Input data for the worker, must be JSON-serializable.

Returns:

The new job.

get_job(job_uid: str, user: User = None, state: JobState = None) → Job | None

Read a job.

Parameters:
  • job_uid – Job uid.

  • user – If given, the job must belong to this user.

  • state – If given, the job must be in this state.

Returns:

The job, or None if it does not exist or does not match. The reason is logged.

handle_cancel_request(req: WebRequester, p: JobRequest) → JobStatusResponse

Cancel a job of the requesting user.

Parameters:
  • req – Web request.

  • p – Job request.

Returns:

The job status after cancelling.

Raises:

gws.NotFoundError – If the job does not exist or belongs to another user.

handle_status_request(req: WebRequester, p: JobRequest) → JobStatusResponse

Return the status of a job of the requesting user.

Parameters:
  • req – Web request.

  • p – Job request.

Returns:

The job status.

Raises:

gws.NotFoundError – If the job does not exist or belongs to another user.

job_status_response(job: Job, **kwargs) → JobStatusResponse

Create a status response for a job.

Parameters:
  • job – The job.

  • **kwargs – Extra or overriding response fields.

Returns:

The status response.

remove_job(job: Job)

Delete a job record.

Parameters:

job – The job.

require_job(req: WebRequester, p: JobRequest) → Job

Return the job of a request, if it belongs to the requesting user.

Parameters:
  • req – Web request.

  • p – Job request.

Returns:

The job.

Raises:

gws.NotFoundError – If the job does not exist or belongs to another user.

require_result(req: WebRequester, p: JobRequest) → dict

Return the result of a completed job of the requesting user.

Parameters:
  • req – Web request.

  • p – Job request.

Returns:

The job result.

Raises:

gws.NotFoundError – If the job does not exist, belongs to another user, is not complete or has no result.

run_job(job: Job) → Job | None

Run an open job in the current process.

Marks the job as running, so that it runs only once, and calls the run method of its worker. If the worker raises an exception, the job goes into the error state.

Parameters:

job – The job.

Returns:

The job after the run.

Raises:

gws.Error – If the job is not open or is already taken by another process.

schedule_job(job: Job) → Job

Start an open job.

The job is passed to the uWSGI spooler if it is available, otherwise it runs at once in the current process.

Parameters:

job – The job.

Returns:

The job.

Raises:

gws.Error – If the job is not open.

update_job(job: Job, **kwargs) → Job | None

Update fields of a job.

Parameters:
  • job – The job.

  • **kwargs – Job fields to update.

Returns:

The updated job, or None if the job does not exist.

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

Bases: Request

Request that refers to a job.

jobUid: str

Job uid.

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

Bases: Response

Job status.

jobUid: str

Job uid.

output: dict

Job-specific output, e.g. a download URL when the job is complete.

progress: int

Progress in percent.

state: JobState

Job state.

stepName: str

Name of the current step.

exception gws.JobTerminated

Bases: Exception

Raised in a worker when its job is no longer running, e.g. because it was cancelled.

class gws.Layer

Bases: Node

Layer object.

bounds: Bounds

the WGS extent clipped to the parent extent and to the CRS.

Type:

Bounds in the map CRS

canRenderBox: bool

The layer can render a single image for an arbitrary extent.

canRenderInClient: bool

The layer can be drawn by the client directly from its source (display: client).

canRenderSvg: bool

The layer can render its features as SVG.

canRenderTile: bool

The layer can render tiles in a fixed grid.

cssSelector: str

CSS selector for feature styling.

displayMode: LayerDisplayMode

How the client displays the layer.

finders: list[Finder]

Search providers.

grabbers: dict[int, Grabber]

Grabbers by CRS code, one for each CRS the application supports.

hasLegend: bool

The layer has a legend.

imageFormat: ImageFormat

Image format for box and tile rendering.

isEnabledForOws: bool

The layer can be used by OWS services.

isGroup: bool

The layer is a group of other layers.

isSearchable: bool

The layer has at least one search provider.

layers: list[Layer]

Child layers.

legend: Legend | None

Legend object.

loadingStrategy: FeatureLoadingStrategy

How the client loads features.

mapCrs: Crs

CRS of the map this layer belongs to.

metadata: Metadata

Layer metadata.

models: list[Model]

Data models.

opacity: float

Layer opacity, 0 to 1.

ows: LayerOwsBinding

Binding to OWS services.

resolutions: list[float]

Resolutions the layer is visible at, in map units per pixel.

sourceLayers: list[SourceLayer]

Source layers this layer is built from.

templates: list[Template]

Layer templates.

title: str

Layer title.

wgsExtent: Extent

Layer extent in WGS84.

zoomBounds: Bounds

Bounds the client zooms to for this layer; defaults to bounds.

find_features(search: SearchQuery, user: User) → list[Feature]

Find features in the layer.

Vector layers search in the first model the user can read; other layers return an empty list.

Parameters:
  • search – Search query.

  • user – The user who searches.

Returns:

Found features.

render(lri: LayerRenderInput) → LayerRenderOutput | None

Render a box, a tile or an SVG fragment, depending on the input type.

Parameters:

lri – Render input.

Returns:

Render output with image content or SVG tags, or None if the layer has nothing to render.

render_legend(args: dict | Data | None = None) → LegendRenderOutput | None

Render the layer legend.

Without args the output is cached for the server lifetime.

Parameters:

args – Arguments passed to the legend renderer.

Returns:

Legend output, or None if the layer has no legend.

url_path_for(kind: str) → str

Return the URL path for requests to this layer.

Parameters:

kind – box, tile, legend or features. The tile path contains {z}, {x} and {y} placeholders.

Returns:

URL path.

Raises:

gws.Error – If kind is not recognized.

class gws.LayerDisplayMode

Bases: Enum

How a layer is rendered.

box = 'box'

Render the map view as a single image.

client = 'client'

Let the client render the layer from its source.

tile = 'tile'

Render the layer as tiles of a grid.

class gws.LayerOwsBinding

Bases: Node

Binding of a layer to OWS services: access, names and models.

allowedServiceUids: list[str]

UIDs of services which can use this layer; empty means any.

deniedServiceUids: list[str]

UIDs of services which can not use this layer.

featureName: str

Name for features in this layer.

geometryName: str

Name for geometries in this layer.

layerName: str

Name for this layer in OWS services.

models: list[Model]

OWS-specific models.

xmlNamespace: XmlNamespace | None

XML namespace for feature and layer names.

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

Bases: Data

Input of a layer render request.

extraParams: dict

Additional request parameters, e.g. compositeLayerUids.

project: Project

Project of the request.

renderParams: dict

Parameters set by the layer for its grabber. Non-empty params mark a dynamic, uncached request.

style: Style

Style for the svg type.

targetCrs: Crs

CRS of the output.

type: LayerRenderInputType

Request type.

user: User

User who requests the rendering.

view: MapView

Map view, for the box and svg types.

x: int

Tile column, for the tile type.

y: int

Tile row, for the tile type.

z: int

Zoom level, for the tile type.

class gws.LayerRenderInputType

Bases: Enum

Type of a layer render request.

box = 'box'

Render an image of the view extent.

svg = 'svg'

Render SVG elements for the view.

tile = 'tile'

Render a tile of the layer grid.

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

Bases: Data

Output of a layer render request.

content: bytes

Encoded image, for the box and tile types.

tags: list[XmlElement]

SVG elements, for the svg type.

class gws.Legend

Bases: Node

Legend object.

render(args: dict | Data | None = None) → LegendRenderOutput | None

Render the legend.

Parameters:

args – Arguments for the renderer, for example template arguments.

Returns:

Legend output, or None if there is nothing to show.

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

Bases: Data

Legend render output.

html: str

HTML representation of the legend; not set by the built-in legend types.

image: Image

Legend image.

size: Size

Size of the legend image in pixels.

gws.load_root(path: str = None) → Root

Load a pickled root object, activate it and make it the current root.

sys.path is restored first, so that plugin modules can be imported.

Parameters:

path – File path. Defaults to config.pickle in the config directory.

Returns:

The root object.

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

Bases: Data

Locale data: language, territory, date and number conventions.

dateFormatLong: str

Long date format pattern.

dateFormatMedium: str

Medium date format pattern.

dateFormatShort: str

Short date format pattern.

dateUnits: str

Narrow names of year, month and day, e.g. YMD for en, JMT for de.

dayNamesLong: list[str]

Full day names.

dayNamesNarrow: list[str]

Narrow day names.

dayNamesShort: list[str]

Abbreviated day names.

firstWeekDay: int

First day of the week, 0 is Monday.

language: str

de.

Type:

Language code

language3: str

deu.

Type:

ISO 639 alpha-3 language code

languageBib: str

ger.

Type:

ISO 639-2 bibliographic language code

languageName: str

Deutsch.

Type:

Native language name

languageNameEn: str

German.

Type:

English language name

monthNamesLong: list[str]

Full month names.

monthNamesNarrow: list[str]

Narrow month names.

monthNamesShort: list[str]

Abbreviated month names.

numberDecimal: str

Decimal separator.

numberGroup: str

Group (thousands) separator.

territory: str

DE.

Type:

Territory code

territoryName: str

Deutschland.

Type:

Native territory name

uid: str

Locale uid like de_DE. A locale without a territory has the territory ZZ.

type gws.LocaleUid = str

Locale UID like de_DE.

gws.LockBusyError

Raised when a server lock cannot be acquired within the timeout.

class gws.Map

Bases: Node

Map object.

bounds: Bounds

Map extent in the map CRS.

center: Point

Initial map center.

coordinatePrecision: int

Decimal places for coordinates.

initResolution: float

Initial resolution.

resolutions: list[float]

Resolutions the map can be displayed at, in map units per pixel.

rootLayer: Layer

Root group layer that holds the map layers.

title: str

Map title.

wgsExtent: Extent

Map extent in WGS84.

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

Bases: Data

Tile cache settings of a grabber.

maxAge: int

Max. age of cached tiles in seconds, 0 disables storing.

maxLevel: int

Finest zoom level to store.

name: str

Cache name, also the name of the cache directory.

requestBuffer: int

Pixel buffer around source requests.

requestTiles: int

Tiles per side of the block rendered in one source request.

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

Bases: Data

Fixed tile grid over a CRS, origin north-west.

Level z has the resolution baseResolution / 2**z. See gws.lib.grid.

baseResolution: float

Resolution at level 0, in CRS units per pixel.

crs: Crs

Grid CRS.

extent: Extent

Frame extent; the origin is its north-west corner.

tileSize: int

Tile width and height in pixels.

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

Bases: Data

Input of the map renderer.

backgroundColor: int

Background color of the first raster plane.

bbox: Extent

Bounding box of the map. If not set, center and scale are used.

center: Point

Center point of the map.

dpi: int

Resolution of raster planes, for maps sized in mm.

mapSize: UomSize

Map size in mm or pixels.

notify: Callable

Callback, called with an event name and the plane before and after each plane is rendered.

planes: list[MapRenderInputPlane]

Planes to render, top to bottom.

project: Project

Project of the map.

rotation: int

Rotation angle in degrees.

scale: int

Scale denominator, used with center.

targetCrs: Crs

CRS of the map.

user: User

User who requests the map.

visibleLayers: list[Layer] | None

Visible layers of the map.

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

Bases: Data

A plane of a map to render.

compositeLayerUids: list[str]

Child layers to render in one composite image, for the imageLayer type.

features: list[Feature]

Features, for the features type.

image: Image

Image, for the image type.

layer: Layer

Layer, for the imageLayer and svgLayer types.

opacity: float

Opacity from 0 to 1, defaults to the layer opacity or 1.

soupPoints: list[Point]

Points in map coordinates, for the svgSoup type.

soupTags: list[Any]

Tags that refer to the points, for the svgSoup type.

styles: list[Style]

Styles. For features, matched by CSS selector; for svgLayer, the first style is used.

type: MapRenderInputPlaneType

Plane type.

class gws.MapRenderInputPlaneType

Bases: Enum

Type of a map render input plane.

features = 'features'

A list of features, rendered as SVG.

image = 'image'

A raster image.

imageLayer = 'imageLayer'

A layer, rendered as an image.

svgLayer = 'svgLayer'

A layer, rendered as SVG.

svgSoup = 'svgSoup'

An SVG soup, a resolution-independent drawing, see gws.lib.svg.soup_to_fragment.

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

Bases: Data

Output of the map renderer.

planes: list[MapRenderOutputPlane]

Rendered planes, bottom to top.

view: MapView

Map view of the vector planes.

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

Bases: Data

A plane of a rendered map.

elements: list[XmlElement]

SVG elements, for the svg type.

image: Image

Image, for the image type.

path: str

Image file path, for the path type.

type: MapRenderOutputPlaneType

Plane type.

class gws.MapRenderOutputPlaneType

Bases: Enum

Type of a map render output plane.

image = 'image'

A raster image.

path = 'path'

A path to an image file.

svg = 'svg'

A list of SVG elements.

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

Bases: Data

Options for a MapServer-based layer.

connectionString: str

Connection string for the data source.

connectionType: str

Type of connection, only postgres is supported.

crs: Crs

Layer CRS.

dataString: str

Layer DATA option, overrides path.

path: str

Path to the data file, e.g. an image (layer DATA option).

processing: list[str]

Processing options for the layer.

sldName: str

Name of an SLD NamedLayer to apply.

sldPath: str

Path to SLD file for styling the layer.

style: StyleValues

Style for the layer; only a part of the style values is supported.

tileIndex: str

Path to the tile index SHP file.

transparentColor: str

Color to treat as transparent in the layer (OFFSITE).

type: MapServerLayerType

Layer type.

class gws.MapServerLayerType

Bases: Enum

MapServer layer type.

line = 'line'

Line layer.

point = 'point'

Point layer.

polygon = 'polygon'

Polygon layer.

raster = 'raster'

Raster layer.

type gws.MapTile = tuple[int, int, int]

(x, y, z).

Type:

Grid tile

type gws.MapTileRange = tuple[int, int, int, int, int]

(min_x, min_y, max_x, max_y, z).

Type:

Rectangle of tiles at one level

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

Bases: Data

Geometry of a rendered map.

bounds: Bounds

Bounds of the map, not rotated.

center: Point

Center point.

dpi: int

Resolution in dots per inch.

mmSize: Size

Map size in mm.

pxSize: Size

Map size in pixels.

rotation: int

Rotation angle in degrees.

scale: int

Scale denominator.

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

Bases: Data

Metadata of an object, used in the client, in OWS services and in catalog records.

abstract: str

Abstract, a brief description of the object.

accessConstraints: str

Access constraints.

accessConstraintsType: str

Type of the access constraints.

attribution: str

Attribution text.

attributionUrl: str

URL of the attribution.

authorityIdentifier: str

Identifier issued by the authority.

authorityName: str

Name of the authority that issues identifiers.

authorityUrl: str

URL of the authority that issues identifiers.

catalogCitationUid: str

Identifier of the resource in catalog records.

catalogUid: str

Identifier of the metadata record.

contactAddress: str

Street address of the contact.

contactAddressType: str

Type of the contact address.

contactArea: str

Administrative area, state or province of the contact address.

contactCity: str

Contact city.

contactCountry: str

Contact country.

contactEmail: str

Contact email address.

contactFax: str

Contact fax number.

contactOrganization: str

Contact organization.

contactPerson: str

Contact person name.

contactPhone: str

Contact phone number.

contactPosition: str

Contact position or job title.

contactProviderName: str

Name of the service provider.

contactProviderSite: str

Website of the service provider.

contactRole: str

Role of the contact, an ISO CI_RoleCode value.

contactUrl: str

Website of the contact.

contactZip: str

Contact postal code.

crs: Crs | None

Reference system of the data.

dateCreated: datetime.datetime | None

Creation date.

dateUpdated: datetime.datetime | None

Last update date.

fees: str

Fees for using the object.

image: str

Image URL or path associated with the object.

inspireDegreeOfConformity: str

Degree of conformity with the INSPIRE implementing rules.

inspireMandatoryKeyword: str

INSPIRE mandatory keyword (service type).

inspireResourceType: str

INSPIRE resource type.

inspireSpatialDataServiceType: str

INSPIRE spatial data service type.

inspireSpatialScope: str

INSPIRE spatial scope.

inspireSpatialScopeName: str

Display name of the INSPIRE spatial scope.

inspireTheme: str

INSPIRE data theme code.

inspireThemeNameEn: str

English name of the INSPIRE theme, derived from inspireTheme.

inspireThemeNameLocal: str

Name of the INSPIRE theme in the metadata language, derived from inspireTheme.

isoMaintenanceFrequencyCode: str

How often the data is updated.

isoQualityConformanceExplanation: str

Explanation of the conformance result.

isoQualityConformanceQualityPass: bool

The data passes the conformance test.

isoQualityConformanceSpecificationDate: str

Publication date of the conformance specification.

isoQualityConformanceSpecificationTitle: str

Title of the conformance specification.

isoQualityLineageSource: str

Description of the source data.

isoQualityLineageSourceScale: int

Scale denominator of the source data.

isoQualityLineageStatement: str

Statement on the lineage of the data.

isoRestrictionCode: str

Restrictions on access or use of the data.

isoScope: str

Scope of the metadata.

isoScopeName: str

Name of the scope.

isoServiceFunction: str

ISO service function.

isoSpatialRepresentationType: str

How the data is represented spatially.

isoSpatialResolution: int

Spatial resolution as a scale denominator.

isoTopicCategories: list[str]

ISO 19115 topic categories.

keywords: list[str]

Keywords, optionally prefixed with a vocabulary, e.g. gemet:river.

language: str

Language as an ISO 639-1 code.

language3: str

Language as an ISO 639-2 three-letter code, derived from language.

languageBib: str

Language as an ISO 639-2 bibliographic code, derived from language.

languageName: str

Name of the language.

license: str

License text.

licenseUrl: str

License URL.

Links to metadata documents.

name: str

Object name.

parentIdentifier: str

Identifier of the parent metadata record.

serviceMetadataURL: str

URL of the service metadata document.

temporalBegin: datetime.datetime | None

Start of the temporal extent.

temporalEnd: datetime.datetime | None

End of the temporal extent.

title: str

Object title.

wgsExtent: Extent | None

Geographic extent in WGS84.

Bases: Data

Link to a metadata document or another resource related to an object.

about: str

Aspect of the object the link describes.

description: str

Description of the linked resource.

format: str

Format of the linked resource.

formatVersion: str

Version of the format of the linked resource.

function: str

Function of the link.

mimeType: str

MIME type of the linked resource.

scheme: str

Link scheme or protocol.

title: str

Link title.

type: str

Link type.

url: str

Link URL.

class gws.MiddlewareManager

Bases: Node

Middleware manager.

Middleware objects process every web request: the web server calls enter_middleware on each of them in dependency order before the action, and exit_middleware in reverse order after it.

objects() → list[Node]

Return the registered middleware objects in dependency order.

Returns:

A list of middleware objects, dependencies first.

Raises:

Error – If the dependencies are cyclic or refer to an unknown name.

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

Register an object as a middleware.

Parameters:
  • obj – The middleware object.

  • name – Middleware name, for example db or auth.

  • depends_on – Names of middleware that must run before this one.

type gws.MimeType = str

A MIME type or a file extension.

class gws.Model

Bases: Node

Data model.

Reads features from a source, converts them to and from client props and, if editable, writes them back.

clientOptions: ModelClientOptions

Client options.

defaultSort: list[SearchSort]

Default sort order of features.

exportStrategy: FeatureExportStrategy

How features are obtained for export.

fields: list[ModelField]

Model fields.

geometryCrs: Crs | None

CRS of the geometry field.

geometryName: str

Name of the geometry field.

geometryType: GeometryType | None

Type of the geometry field.

isEditable: bool

Features of this model can be edited.

loadingStrategy: FeatureLoadingStrategy

How the client loads features.

title: str

Model title.

uidName: str

Name of the uid (primary key) field.

withTableView: bool

The table view of features is enabled in the client.

create_feature(feature: Feature, mc: ModelContext) → FeatureUid

Insert a new feature into the source.

Parameters:
  • feature – The feature.

  • mc – The model context.

Returns:

The primary key of the inserted feature.

Raises:

gws.ForbiddenError – If the user cannot create features of this model.

delete_feature(feature: Feature, mc: ModelContext) → FeatureUid

Delete a feature from the source.

Parameters:
  • feature – The feature.

  • mc – The model context.

Returns:

The uid of the feature.

Raises:

gws.ForbiddenError – If the user cannot delete features of this model.

describe() → DataSetDescription | None

Return the description of the model source.

Returns:

The dataset description, or None if the source cannot be described.

feature_from_props(props: FeatureProps, mc: ModelContext) → Feature

Create a feature from client props.

Parameters:
  • props – The feature props.

  • mc – The model context.

Returns:

A new feature.

feature_to_props(feature: Feature, mc: ModelContext) → FeatureProps

Convert a feature to client props and store them in feature.props.

Parameters:
  • feature – The feature.

  • mc – The model context.

Returns:

The feature props.

feature_to_view_props(feature: Feature, mc: ModelContext) → FeatureProps

Convert a feature to client props for viewing, with a reduced set of attributes.

Parameters:
  • feature – The feature.

  • mc – The model context.

Returns:

The feature props.

field(name: str) → ModelField | None

Return a field by name.

Parameters:

name – The field name.

Returns:

The field, or None if it is not found.

find_features(search: SearchQuery, mc: ModelContext) → list[Feature]

Find features matching a search query.

Parameters:
  • search – The search query.

  • mc – The model context.

Returns:

The features found.

get_feature(uid: str | int, mc: ModelContext) → Feature | None

Return a feature by uid.

Parameters:
  • uid – The feature uid.

  • mc – The model context.

Returns:

The feature, or None if it is not found.

get_features(uids: Iterable[str | int], mc: ModelContext) → list[Feature]

Return features by uid.

Parameters:
  • uids – Feature uids.

  • mc – The model context.

Returns:

The features found, empty if no uids are given.

init_feature(feature: Feature, mc: ModelContext)

Initialize a new feature with initial field values.

Parameters:
  • feature – The new feature.

  • mc – The model context.

Raises:

gws.ForbiddenError – If the user cannot create features of this model.

related_models() → list[Model]

Return the models related to the fields of this model.

Returns:

A list of models without duplicates.

update_feature(feature: Feature, mc: ModelContext) → FeatureUid

Update an existing feature in the source.

Parameters:
  • feature – The feature.

  • mc – The model context.

Returns:

The uid of the feature.

Raises:

gws.ForbiddenError – If the user cannot write to this model.

validate_feature(feature: Feature, mc: ModelContext) → bool

Validate a feature and store validation errors in feature.errors.

Parameters:
  • feature – The feature.

  • mc – The model context.

Returns:

True if the feature has no errors.

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

Bases: Data

Client options for a model.

keepFormOpen: bool | None

Keep the edit form open after saving.

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

Bases: Data

Context of a model operation.

dbSelect: ModelSelectBuild

The select statement being built, for database read operations.

maxDepth: int = 0

Maximum depth of related features to process.

op: ModelOperation

The operation.

project: Project | None

The current project.

relDepth: int = 0

Current depth of related features.

search: SearchQuery

The search query, for read operations.

target: ModelReadTarget

Where the features are to be displayed, for read operations.

user: User

The user performing the operation.

class gws.ModelField

Bases: Node

Model field.

Handles a subset of feature data. The model calls the field methods when it performs an operation; the methods read and write feature.attributes, feature.record and feature.props.

attributeType: AttributeType

Type of the field value.

isAuto: bool

The value is set by the database and never written.

isHidden: bool

The field is not automatically displayed in the client.

isPrimaryKey: bool

The field is a primary key.

isRequired: bool

The field must not be empty.

isUnique: bool

The field is unique.

model: Model

The model of the field.

name: str

Field name.

supportsFilterSearch: bool = False

The field supports filter search.

supportsGeometrySearch: bool = False

The field supports geometry search.

supportsKeywordSearch: bool = False

The field supports keyword search.

title: str

Field title.

validators: list[ModelValidator]

Validators.

values: list[ModelValue]

Value objects.

widget: ModelWidget | None = None

Widget for the client.

after_create(feature: Feature, mc: ModelContext)

Called after a feature is inserted.

Parameters:
  • feature – The feature.

  • mc – The model context.

Called after a feature of another model, created together with features of this model, is inserted.

Parameters:
  • dst_feature – The created feature.

  • mc – The model context.

after_delete(feature: Feature, mc: ModelContext)

Called after a feature is deleted.

Parameters:
  • feature – The feature.

  • mc – The model context.

after_select(features: list[Feature], mc: ModelContext)

Called after features are selected, sets the field value in the features.

Parameters:
  • features – The selected features.

  • mc – The model context.

after_update(feature: Feature, mc: ModelContext)

Called after a feature is updated.

Parameters:
  • feature – The feature.

  • mc – The model context.

before_create(feature: Feature, mc: ModelContext)

Called before a feature is inserted, writes the field value to feature.record.

Parameters:
  • feature – The feature.

  • mc – The model context.

Called before a feature of another model, created together with features of this model, is inserted.

Parameters:
  • dst_feature – The feature being created.

  • mc – The model context.

before_delete(feature: Feature, mc: ModelContext)

Called before a feature is deleted.

Parameters:
  • feature – The feature.

  • mc – The model context.

before_select(mc: ModelContext)

Called before features are selected, adds columns and conditions to mc.dbSelect.

Parameters:

mc – The model context.

before_update(feature: Feature, mc: ModelContext)

Called before a feature is updated, writes the field value to feature.record.

Parameters:
  • feature – The feature.

  • mc – The model context.

describe() → ColumnDescription | None

Return the description of the source column of this field.

Returns:

The column description, or None if the source has no such column.

do_init(feature: Feature, mc: ModelContext)

Set the initial field value of a new feature.

Parameters:
  • feature – The feature.

  • mc – The model context.

Initialize a new feature of another model that is created together with features of this model.

Parameters:
  • dst_feature – The new feature.

  • mc – The model context.

do_validate(feature: Feature, mc: ModelContext)

Validate the field value and append errors to feature.errors.

Parameters:
  • feature – The feature.

  • mc – The model context.

find_relatable_features(search: SearchQuery, mc: ModelContext) → list[Feature]

Find features that can be linked by this field.

Parameters:
  • search – The search query.

  • mc – The model context.

Returns:

The features found in the related models.

from_props(feature: Feature, mc: ModelContext)

Set the field value from feature.props.

Parameters:
  • feature – The feature.

  • mc – The model context.

from_record(feature: Feature, mc: ModelContext)

Set the field value from feature.record.

Parameters:
  • feature – The feature.

  • mc – The model context.

prop_to_python(feature: Feature, value, mc: ModelContext)

Convert a client props value to a python value.

Parameters:
  • feature – The feature.

  • value – The value to convert.

  • mc – The model context.

Returns:

The converted value.

python_to_prop(feature: Feature, value, mc: ModelContext)

Convert a python value to a client props value.

Parameters:
  • feature – The feature.

  • value – The value to convert.

  • mc – The model context.

Returns:

The converted value.

python_to_raw(feature: Feature, value, mc: ModelContext)

Convert a python value to a raw source value.

Parameters:
  • feature – The feature.

  • value – The value to convert.

  • mc – The model context.

Returns:

The converted value.

raw_to_python(feature: Feature, value, mc: ModelContext)

Convert a raw source value to a python value.

Parameters:
  • feature – The feature.

  • value – The value to convert.

  • mc – The model context.

Returns:

The converted value.

related_models() → list[Model]

Return the models related to this field.

Returns:

A list of models, empty for fields that are not related fields.

to_props(feature: Feature, mc: ModelContext)

Write the field value to feature.props.

Parameters:
  • feature – The feature.

  • mc – The model context.

to_record(feature: Feature, mc: ModelContext)

Write the field value to feature.record.

Parameters:
  • feature – The feature.

  • mc – The model context.

class gws.ModelManager

Bases: Node

Model manager.

Looks up models and provides the default model.

default_model() → Model

Return the shared default model.

Returns:

The default model.

editable_models(project: Project, user: User) → list[Model]

Return the models a user can edit in a project, together with their related models.

Parameters:
  • project – The project.

  • user – The user.

Returns:

The models, sorted by title.

find_model(*objects, user: User = None, access: Access = None) → Model | None

Return the first model of the given objects.

Looks in the models attribute of each object in turn.

Parameters:
  • *objects – Objects with models, e.g. layers. None values are skipped.

  • user – If given together with access, the user must have this access to the model.

  • access – The required access.

Returns:

The model, or None if none is found.

get_model(uid: str, user: User = None, access: Access = None) → Model | None

Return a model by uid.

Parameters:
  • uid – The model uid.

  • user – If given together with access, the user must have this access to the model.

  • access – The required access.

Returns:

The model, or None if it is not found or not accessible.

class gws.ModelOperation

Bases: Enum

Model operation.

create = 'create'

Create new features.

delete = 'delete'

Delete features.

export = 'export'

Export features.

read = 'read'

Read features.

update = 'update'

Update existing features.

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

Bases: Data

Parts of a database select statement, collected from the model fields.

columns: list[sqlalchemy.Column]

Columns to select.

geometryWhere: list

Conditions for the geometry search, combined with OR.

keywordWhere: list

Conditions for the keyword search, combined with OR.

order: list

Sort expressions.

where: list

Other conditions, combined with AND.

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

Bases: Data

Validation error of a feature field.

fieldName: str

Name of the field that failed validation.

message: str

Error message, or a message key for the client.

class gws.ModelValidator

Bases: Node

Model validator.

Checks the value of a field.

message: str

Error message, or a message key for the client.

ops: set[ModelOperation]

Operations the validator applies to.

validate(field: ModelField, feature: Feature, mc: ModelContext) → bool

Check the value of a field in a feature.

Parameters:
  • field – The field.

  • feature – The feature.

  • mc – The model context.

Returns:

True if the value is valid.

class gws.ModelValue

Bases: Node

Model value.

Computes a value for a field.

isDefault: bool

The value is used only when the source provides no value.

ops: set[ModelOperation]

Operations the value applies to.

compute(field: ModelField, feature: Feature, mc: ModelContext)

Compute the value of a field.

Parameters:
  • field – The field.

  • feature – The feature.

  • mc – The model context.

Returns:

The computed value.

class gws.ModelWidget

Bases: Node

Model widget.

Describes how the client displays and edits a field value.

supportsTableView: bool = True

The widget can be used in the table view.

class gws.Node

Bases: Object

GWS object tree node.

Nodes are created by the Root or by their parent node. Configuration hooks (pre_configure, configure, post_configure) are invoked for every class in the MRO that defines them, base classes first, so they do not need to call super().

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.

Called by Root.activate after the configuration has been loaded.

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.

Called when the node is initialized. Raising an exception here aborts the creation of the node.

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 to end the request processing, or None to continue.

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 direct children that match a specific class.

Parameters:

classref – Class reference. If omitted, all children are returned.

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. If omitted, all ancestors are returned.

Returns:

A list of objects, from the parent upwards.

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

Find the closest node ancestor that matches a specific class.

Parameters:

classref – Class reference. If omitted, the parent is returned.

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. If omitted, all descendants are returned.

Returns:

A list of objects in the depth-first order.

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

Find the first direct child that matches a specific class.

Parameters:

classref – Class reference. If omitted, the first child is returned.

Returns:

An object or None.

initialize(config)

Initialize the node.

Store the configuration, set up the permissions, then run pre_configure and configure.

Parameters:

config – Configuration.

is_a(classref: ClassRef) → bool

Check if the node matches the class reference.

Parameters:

classref – Class reference.

Returns:

True if the node matches.

periodic_task()

Periodic task hook.

Called by the server monitor for nodes registered with register_periodic_task.

post_configure()

Post-configuration hook.

Called after the whole object tree has been created.

pre_configure()

Pre-configuration hook.

Called before configure, when the node is initialized.

exception gws.NotFoundError

Bases: Error

Generic ‘object not found’ error.

class gws.NumberFormat

Bases: Enum

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

Format a number as a currency value.

Parameters:
  • n – Number.

  • currency – Currency code like EUR.

  • *args – Arguments for babel.numbers.format_currency.

  • **kwargs – Keyword arguments for babel.numbers.format_currency.

Returns:

The formatted value.

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

Format a number as a decimal without group separators.

Parameters:
  • n – Number.

  • *args – Arguments for babel.numbers.format_decimal.

  • **kwargs – Keyword arguments for babel.numbers.format_decimal.

Returns:

The formatted number.

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

Format a number.

Parameters:
  • fmt – Format type. For an unknown format, the number is converted with str.

  • n – Number.

  • *args – Arguments for the format method, e.g. the currency for currency.

  • **kwargs – Keyword arguments for the format method.

Returns:

The formatted number.

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

Format a number as a decimal with group separators.

Parameters:
  • n – Number.

  • *args – Arguments for babel.numbers.format_decimal.

  • **kwargs – Keyword arguments for babel.numbers.format_decimal.

Returns:

The formatted number.

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

Format a number as a percentage, 0.5 is 50 percent.

Parameters:
  • n – Number.

  • *args – Arguments for babel.numbers.format_percent.

  • **kwargs – Keyword arguments for babel.numbers.format_percent.

Returns:

The formatted value.

class gws.Object

Basic GWS object.

An object has permissions and can provide properties for the client.

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.

Do not call this method directly, use gws.props_of instead, which also checks permissions.

Parameters:

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

Returns:

A Props object or a dict. Nested objects are converted to props as well.

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

Credentials for accessing an OWS service.

password: str

Password.

type: str

Authorization type, only basic is supported.

username: str

User name.

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

Bases: Data

Parsed capabilities of a remote OWS service.

metadata: Metadata

Service metadata.

operations: list[OwsOperation]

Operations offered by the service.

sourceLayers: list[SourceLayer]

Layers or feature types of the service.

tileMatrixSets: list[TileMatrixSet]

Tile matrix sets (WMTS).

version: str

Service version.

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

Bases: Data

OWS operation, as offered by a remote service or by our own service.

allowedParameters: dict[str, list[str]]

Allowed values for parameters, keyed by the upper-cased parameter name.

constraints: dict[str, list[str]]

Operation constraints.

formats: list[str]

Supported output formats.

handlerName: str

Name of the service method that handles this operation (server side).

params: dict[str, str]

Extra parameters for GET requests (client side).

postUrl: Url

URL for POST requests.

preferredFormat: str

Output format to use in requests (client side).

url: Url

URL for GET requests.

verb: OwsVerb

Request type.

class gws.OwsProtocol

Bases: Enum

Supported OWS protocols.

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

Bases: Node

OWS service provided by GBD WebSuite.

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.

Errors are returned as OWS exception documents, not raised.

Parameters:

req – Web request.

Returns:

The service response.

layer_is_compatible(layer: Layer) → bool

Check if a layer can be used in this service.

Parameters:

layer – Layer object.

Returns:

True if the layer can be published by this service.

class gws.OwsServiceProvider

Bases: Node

Remote OWS service used as a data provider.

alwaysXY: bool

Force XY axis order for CRSs with lat/lon axis order.

authorization: OwsAuthorization | None

Credentials for the service.

bounds: Bounds | None

Service bounds, if known.

forceCrs: Crs

CRS to use for requests, if configured.

maxRequests: int

Max. number of concurrent requests to the service.

metadata: Metadata

Service metadata.

operations: list[OwsOperation]

Operations offered by the service.

protocol: OwsProtocol

Service protocol.

sourceLayers: list[SourceLayer]

Layers or feature types of the service.

url: Url

Service URL.

version: str

Service version.

wgsExtent: Extent | None

Service extent in WGS84, if known.

get_features(args: SearchQuery, source_layers: list[SourceLayer]) → list[FeatureRecord]

Search for features in the given source layers.

Parameters:
  • args – Search query.

  • source_layers – Source layers to search.

Returns:

Found feature records.

get_operation(verb: OwsVerb, method: RequestMethod | None = None) → OwsOperation | None

Find an operation by its verb.

Parameters:
  • verb – Request type.

  • method – Request method. For POST, the operation must have a POST URL, otherwise a GET URL.

Returns:

The operation, or None if the service does not support it.

class gws.OwsVerb

Bases: Enum

OWS request type.

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

Bases: Config

Access rules per operation.

all: AclStr | None

Rules for read, write, create and delete at once.

create: AclStr | None

Rules for creating new objects.

delete: AclStr | None

Rules for deleting objects.

edit: AclStr | None

Rules for write, create and delete at once.

read: AclStr | None

Rules for reading or using the object.

write: AclStr | None

Rules for changing existing objects.

type gws.Point = tuple[float, float]

Point coordinates [x, y].

class gws.Printer

Bases: Node

Printer, a print template offered to users.

models: list[Model]

Models whose fields are shown as input fields in the print dialog.

qualityLevels: list[TemplateQualityLevel]

Quality levels users can choose from.

template: Template

Template that renders the print output.

title: str

Printer title.

class gws.PrinterManager

Bases: Node

Print manager.

exec_print(request: PrintRequest, out_path: str)

Execute a print request synchronously, as the system user.

Parameters:
  • request – Print request.

  • out_path – Path to copy the output file to.

start_print_job(request: PrintRequest, user: User) → JobStatusResponse

Start a background print job.

Parameters:
  • request – Print request.

  • user – User who requested the print.

Returns:

The status of the new job.

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

Bases: Data

Map properties for printing.

backgroundColor: int | None

Background color.

bbox: Extent | None

Map extent.

center: Point | None

Map center.

planes: list[PrintPlane]

Map planes.

rotation: int | None

Map rotation in degrees.

scale: int

Map scale denominator.

styles: list[StyleProps] | None

Styles used by the planes.

visibleLayers: list[str] | None

Uids of the visible layers.

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

Bases: Data

Print plane, a single map layer in a print request.

bitmapData: bytes | None

Raw pixel data, for bitmap planes.

bitmapHeight: int | None

Bitmap height in pixels.

bitmapMode: str | None

Pixel mode of the bitmap, RGBA or RGB.

bitmapWidth: int | None

Bitmap width in pixels.

compositeLayerUids: list[str] | None

Uids of the sub-layers to render, for composite raster layers.

cssSelector: str | None

CSS selector of the style for vector layers and features.

features: list[FeatureProps] | None

Features, for features planes.

layerUid: str | None

Layer uid, for raster and vector planes.

opacity: float | None

Plane opacity, from 0 to 1.

soupPoints: list[Point] | None

Points, for soup planes.

soupTags: list[Any] | None

SVG tags, for soup planes.

type: PrintPlaneType

Plane type.

url: str | None

Data URL of the image, for url planes.

class gws.PrintPlaneType

Bases: Enum

Print plane type.

bitmap = 'bitmap'

Raw bitmap data.

features = 'features'

Features sent by the client.

raster = 'raster'

Raster layer.

soup = 'soup'

points and SVG tags.

Type:

SVG soup

url = 'url'

Image given as a data URL.

vector = 'vector'

Vector layer, rendered as SVG.

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

Bases: Request

Print request.

args: dict | None

Template arguments.

crs: CrsName | None

CRS of the maps, the project CRS by default.

dpi: int | None

Output resolution.

maps: list[PrintMap] | None

Maps to print.

outputFormat: str | None

Output format, pdf (default) or png, or the mime type.

outputSize: Size | None

Output size in screen pixels, for map requests.

printerUid: str | None

Printer uid, for template requests.

type: PrintRequestType

Request type.

class gws.PrintRequestType

Bases: Enum

Type of the print request.

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

Bases: Data

Print result.

mimeType: str

Mime type of the output file.

path: str

Path of the output file.

class gws.Project

Bases: Node

Project: a map application with its own map, actions, templates and services.

actions: list[Action]

Actions available only in this project.

assetsRoot: WebDocumentRoot | None

Project assets directory, checked before the global assets directory.

client: Client

Project client settings, replacing the application client.

exporters: list[Exporter]

Exporters of the project.

finders: list[Finder]

Search providers of the project.

localeUids: list[str]

Locales of the project.

map: Map

Main map of the project.

metadata: Metadata

Project metadata.

models: list[Model]

Data models of the project.

owsServices: list[OwsService]

OWS services published for the project.

printers: list[Printer]

Printers of the project.

templates: list[Template]

Templates of the project.

title: str

Project title.

vars: dict

Custom variables.

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

Bases: Data

Object properties.

uid: str = ''

Unique ID.

gws.props_of(obj: Object, user: User, *context) → Props | None

Generate props for an object, if the user is allowed to use it.

Nested objects the user cannot read are removed from the result.

Parameters:
  • obj – The object.

  • user – The user.

  • *context – Context objects for the permission check.

Returns:

A Props object, or None if the user cannot use the object.

Raises:

Error – If the object’s props returns an invalid type.

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

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]

Paths of the configuration files.

configStack: list[Node]

Nodes being configured, from the outermost to the current one.

configWarnings: list

List of configuration warnings.

nodes: list[Node]

All nodes in the tree, in the order of creation.

specs: SpecRuntime

Specs runtime.

uidCount: int

Counter for generated uids.

uidMap: dict[str, Node]

Mapping from uids to nodes.

activate()

Run activate on all nodes.

config_warning(message: str)

Register a configuration warning.

The warning is logged immediately and reported again after the configuration is complete. The object stack is only available when called from configure or post_configure.

Parameters:

message – Warning message.

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.

If the config has no uid, it is computed from the class reference and the configuration. If an object with this uid already exists, it is returned instead of creating a new one.

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

Initialize a node and record configuration errors.

Parameters:
  • obj – The node.

  • config – Configuration.

Returns:

True if the node was initialized, False if it failed.

object_count() → int

Return the number of objects in the tree.

Returns:

The number of objects.

post_initialize()

Run post_configure on all nodes, in the reverse order of creation.

Errors are logged and recorded in configErrors.

gws.save_root(root: Root, path: str = None) → str

Pickle the root object to a file.

sys.path is pickled next to it, to <path>.syspath, so that load_root can restore it.

Parameters:
  • root – The root object.

  • path – File path. Defaults to config.pickle in the config directory.

Returns:

The file path.

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

Bases: Data

Search filter, a tree of filter operators.

escapeChar: str

Escape character for PropertyIsLike.

matchAction: SearchFilterMatchAction

How to match multi-valued properties.

matchCase: bool

Compare strings case-sensitively.

operator: SearchFilterOperator

Filter operator.

property: str

Property name for comparison and spatial operators.

shape: Shape

Shape for spatial operators.

singleChar: str

Single character placeholder for PropertyIsLike.

subFilters: list[SearchFilter]

Operands of logical operators.

value: str

Value for comparison operators.

wildCard: str

Wildcard character for PropertyIsLike.

class gws.SearchFilterMatchAction

Bases: Enum

How a filter is applied to a multi-valued property.

All = 'All'

All values must match.

Any = 'Any'

At least one value must match.

One = 'One'

Exactly one value must match.

class gws.SearchFilterOperator

Bases: Enum

Search filter operator, as defined in OGC Filter Encoding 2.0.

And = 'And'

All sub-filters match.

BBOX = 'BBOX'

Geometry intersects the bounding box.

Beyond = 'Beyond'

Geometry is beyond a distance of the shape.

Contains = 'Contains'

Geometry contains the shape.

Crosses = 'Crosses'

Geometry crosses the shape.

Disjoint = 'Disjoint'

Geometry does not intersect the shape.

DWithin = 'DWithin'

Geometry is within a distance of the shape.

Equals = 'Equals'

Geometry is equal to the shape.

Intersects = 'Intersects'

Geometry intersects the shape.

Not = 'Not'

The sub-filter does not match.

Or = 'Or'

At least one sub-filter matches.

Overlaps = 'Overlaps'

Geometry overlaps the shape.

PropertyIsBetween = 'PropertyIsBetween'

Property is between two values.

PropertyIsEqualTo = 'PropertyIsEqualTo'

Property is equal to the value.

PropertyIsGreaterThan = 'PropertyIsGreaterThan'

Property is greater than the value.

PropertyIsGreaterThanOrEqualTo = 'PropertyIsGreaterThanOrEqualTo'

Property is greater than or equal to the value.

PropertyIsLessThan = 'PropertyIsLessThan'

Property is less than the value.

PropertyIsLessThanOrEqualTo = 'PropertyIsLessThanOrEqualTo'

Property is less than or equal to the value.

PropertyIsLike = 'PropertyIsLike'

Property matches a pattern.

PropertyIsNil = 'PropertyIsNil'

Property is nil.

PropertyIsNotEqualTo = 'PropertyIsNotEqualTo'

Property is not equal to the value.

PropertyIsNull = 'PropertyIsNull'

Property is null.

Touches = 'Touches'

Geometry touches the shape.

Within = 'Within'

Geometry is within the shape.

class gws.SearchManager

Bases: Node

Search manager, runs search queries through the finders.

Run a search query.

Runs the finders of the query layers, the project finders and the application finders the user may use and which can run the query.

Parameters:
  • search – Search query.

  • user – User running the search.

Returns:

Search results, at most search.limit if a limit is given.

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

Found feature.

finder: Finder

Finder that found the feature.

layer: Layer

Layer whose finder found the feature, or None for project and application finders.

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

Bases: Data

Search sort specification.

fieldName: str

Field name to sort by.

reverse: bool

Sort in descending order.

class gws.ServerManager

Bases: Node

Server configuration manager.

Holds the server configuration and creates the configuration files for the embedded servers and the server start script.

templates: list[Template]

Templates for the server configuration files and the start script.

create_server_configs(target_dir: str, script_path: str, pid_paths: dict)

Create the server configuration files and the start script.

Parameters:
  • target_dir – Directory for the configuration files.

  • script_path – Path of the start script.

  • pid_paths – Paths of the pid files, keyed by server name (web, spool, nginx).

class gws.ServerMonitor

Bases: Node

Server monitor.

Watches configuration files and directories and reconfigures the server when they change, and runs periodic tasks of registered objects.

register_periodic_task(obj: Node, frequency: int = 0)

Register an object as a periodic task handler.

Parameters:
  • obj – A node with a periodic_task method.

  • frequency – Interval between runs in seconds, the monitor default if 0.

Raises:

gws.Error – If the object has no periodic_task method.

schedule_reload(with_reconfigure: bool = False)

Schedule a reload of the web and spool backends.

The reload is performed by the monitor on its next tick.

Parameters:

with_reconfigure – Reconfigure the server before reloading.

start()

Start watching files and register the timer that drives the monitor.

Must be called in a uWSGI process.

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

Add a directory to watch.

Parameters:
  • path – Directory path.

  • pattern – Regex pattern for file names to watch.

  • recursive – Also 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

Compute the area of the geometry.

Returns:

The area in CRS units, 0 for geometries without an area.

bounds() → Bounds

Compute the bounds of this shape.

Returns:

A Bounds object in the CRS of this shape.

center() → tuple[float, float]

Compute the coordinates of the centroid.

Returns:

A tuple (x, y).

centroid() → Shape

Compute the centroid of this shape.

Returns:

A Point shape.

contains(other: Shape) → bool

Check if this shape contains the other.

Parameters:

other – Another shape.

Returns:

True if this shape contains the other.

covered_by(other: Shape) → bool

Check if this shape is covered by the other.

Parameters:

other – Another shape.

Returns:

True if this shape is covered by the other.

covers(other: Shape) → bool

Check if this shape covers the other.

Parameters:

other – Another shape.

Returns:

True if this shape covers the other.

crosses(other: Shape) → bool

Check if this shape crosses the other.

Parameters:

other – Another shape.

Returns:

True if this shape crosses the other.

disjoint(other: Shape) → bool

Check if this shape does not intersect the other.

Parameters:

other – Another shape.

Returns:

True if the shapes have no point in common.

equals(other: Shape) → bool

Check if this shape is spatially equal to the other.

The other shape is transformed to the CRS of this shape. The same applies to all binary predicates.

Parameters:

other – Another shape.

Returns:

True if the shapes are equal.

intersection(*others: Shape) → Shape

Compute the intersection of this shape and other shapes.

Parameters:

*others – Other shapes, transformed to the CRS of this shape.

Returns:

A new shape, or this shape if no others are given.

intersects(other: Shape) → bool

Check if this shape intersects the other.

Parameters:

other – Another shape.

Returns:

True if the shapes have at least one point in common.

is_empty() → bool

Check if this shape is empty.

Returns:

True if this shape is empty.

is_ring() → bool

Check if this shape is a closed and simple line.

Returns:

True if this shape is a ring.

is_simple() → bool

Check if this shape is simple, that is, has no self-intersections.

Returns:

True if this shape is simple.

is_valid() → bool

Check if this shape is valid.

Returns:

True if this shape is valid.

overlaps(other: Shape) → bool

Check if this shape overlaps the other.

Parameters:

other – Another shape.

Returns:

True if this shape overlaps the other.

to_2d() → Shape

Convert this shape to 2 dimensions.

Returns:

A 2D shape, or this shape if it is already 2D.

to_ewkb() → bytes

Convert this shape to EWKB, which includes the SRID.

Returns:

EWKB bytes.

to_ewkb_hex() → str

Convert this shape to hex-encoded EWKB, which includes the SRID.

Returns:

A hex string.

to_ewkt(trim=False, rounding_precision=-1, output_dimension=3) → str

Convert this shape to EWKT, which is WKT prefixed with SRID=<srid>;.

Parameters:
  • trim – Remove trailing zeros from the coordinates.

  • rounding_precision – Number of decimal places, -1 for full precision.

  • output_dimension – Max. number of dimensions to output.

Returns:

An EWKT string.

to_geojson(keep_crs=False) → dict

Convert this shape to a GeoJSON geometry dict.

Parameters:

keep_crs – Keep the CRS of this shape, otherwise transform the coordinates to WGS84.

Returns:

A GeoJSON geometry dict.

to_multi() → Shape

Convert a single geometry shape to a multi-geometry one.

Returns:

A multi-geometry shape for a point, a line string or a polygon, otherwise this shape.

to_precision(prec: int) → Shape

Create a copy of this shape with coordinates snapped to the given precision.

Parameters:

prec – Number of decimal places.

Returns:

A new shape.

to_props() → ShapeProps

Convert this shape to props, with the EPSG code and a GeoJSON geometry in the CRS of this shape.

Returns:

Shape props.

to_type(new_type: GeometryType) → Shape

Convert this shape to another geometry type.

Only the conversion from a single to the respective multi-geometry is supported.

Parameters:

new_type – Target geometry type. geometry and the current type return this shape.

Returns:

A converted shape.

Raises:

gws.Error – If the conversion is not supported.

to_wkb() → bytes

Convert this shape to WKB.

Returns:

WKB bytes.

to_wkb_hex() → str

Convert this shape to hex-encoded WKB.

Returns:

A hex string.

to_wkt(trim=False, rounding_precision=-1, output_dimension=3) → str

Convert this shape to WKT.

Whitespace around commas and parentheses is removed.

Parameters:
  • trim – Remove trailing zeros from the coordinates.

  • rounding_precision – Number of decimal places, -1 for full precision.

  • output_dimension – Max. number of dimensions to output.

Returns:

A WKT string.

tolerance_polygon(tolerance=None, quad_segs=None) → Shape

Build a buffer polygon around this shape.

Polygons without a tolerance are returned as is. Other shapes always get a buffer, with a small minimal radius if no tolerance is given. Shapes in a geographic CRS are buffered in Web Mercator.

Parameters:
  • tolerance – Buffer radius in CRS units, or in meters for geographic CRS.

  • quad_segs – Number of segments per quarter circle.

Returns:

A polygon shape.

touches(other: Shape) → bool

Check if this shape touches the other.

Parameters:

other – Another shape.

Returns:

True if this shape touches the other.

transformed_to(crs: Crs) → Shape

Transform this shape to another CRS.

Parameters:

crs – Target CRS.

Returns:

A transformed shape, or this shape if the CRS is the same.

union(others: list[Shape]) → Shape

Compute the union of this shape and other shapes.

Parameters:

others – Other shapes, transformed to the CRS of this shape.

Returns:

A new shape, or this shape if others is empty.

within(other: Shape) → bool

Check if this shape is within the other.

Parameters:

other – Another shape.

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 order for features.

fieldName: str

Field name to sort by.

reverse: bool = False

Sort in descending order.

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

Bases: Data

A layer of an external source, such as a WMS, WFS or WMTS service or a QGIS project.

Source layers are read from capabilities and form a tree. The a* properties are set by gws.gis.source.check_layers.

aLevel: int

Depth in the layer tree, 1 for top-level layers.

aPath: str

Path of uids from the top of the tree, e.g. /root/roads.

aUid: str

Uid derived from the name or title.

dataSource: dict

Parsed data source of a QGIS layer.

defaultStyle: SourceStyle | None

Default style.

imageFormat: str

Image format for WMTS requests.

isExpanded: bool

The layer is expanded in the source layer tree.

isGroup: bool

The layer is a group.

isImage: bool

The layer can be rendered as an image.

isQueryable: bool

The layer can be queried for features.

isVisible: bool

The layer is visible by default.

layers: list[SourceLayer]

Sub-layers.

legendUrl: Url

URL of the legend image.

metadata: Metadata

Layer metadata.

name: str

Layer name, used in requests to the source.

opacity: float

Layer opacity from 0 to 1.

properties: dict

Custom properties of a QGIS layer.

resourceUrls: dict

WMTS resource URL templates, keyed by resource type.

scaleRange: list[float]

Min. and max. scale denominators at which the layer is visible.

sourceId: str

Id of the layer in the source, e.g. the QGIS layer id.

styles: list[SourceStyle]

Available styles.

supportedCrs: list[Crs]

CRS supported by the source for this layer.

tileMatrixIds: list[str]

Ids of the WMTS tile matrix sets the layer links to.

tileMatrixSets: list[TileMatrixSet]

WMTS tile matrix sets of the layer.

title: str

Layer title.

wgsExtent: Extent

Layer extent in WGS84.

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

Bases: Data

A style of a source layer, as listed in the capabilities of a service.

isDefault: bool

The style is the default style of the layer.

legendUrl: Url

URL of the legend image.

metadata: Metadata

Style metadata.

name: str

Style name.

class gws.SpecReadOption

Bases: Enum

Options for reading values with SpecRuntime.read.

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'

Add the value and the location of an error to ReadError exceptions.

class gws.SpecRuntime

Spec runtime.

Provides access to the generated specs: reading and validating values, looking up extension objects and commands, and loading classes.

appBundlePaths: list[str]

Paths of the client bundles of all chunks.

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.

The module defining the class is imported on demand.

Parameters:
  • classref – Class reference: a class, a class name or an extension name.

  • ext_type – Extension type, used when classref is an extension category name. Defaults to default.

Returns:

A class or None if the reference is not found.

Raises:

gws.spec.core.LoadError – If the module cannot be imported.

get_config_types(lang: str) → list[dict]

Get the configuration types as dictionaries.

Docstrings, titles and enum docs are taken from the strings in the given language.

Parameters:

lang – Language code.

Returns:

A list of type dictionaries.

object_descriptor(type_name: str) → ExtObjectDescriptor | None

Get an object descriptor.

Parameters:

type_name – Type uid or extension 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), where only one element is set.

Raises:

gws.spec.core.Error – If the class reference is invalid.

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

Read and validate a raw value according to a spec type.

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

  • type_name – Type uid or extension name.

  • path – Path of the config file, used to resolve relative paths and in error messages.

  • options – Read options.

Returns:

The parsed value. Objects are returned as gws.Data.

Raises:

gws.spec.core.ReadError – If the value does not match the type.

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

Register an extension class at run time.

The class gets the extName and extType attributes.

Parameters:
  • ext_name – Extension category, like gws.ext.object.layer.

  • obj_type – Extension type, like wms.

  • cls – Class to register.

Raises:

gws.spec.core.Error – If the class reference is invalid.

class gws.StorageManager

Bases: Node

Storage manager, holds the storage providers.

providers: list[StorageProvider]

Configured storage providers.

create_provider(cfg: Config, **kwargs) → StorageProvider

Create a storage provider and add it to the manager.

A provider with the same uid replaces the existing one.

Parameters:
  • cfg – Provider configuration.

  • **kwargs – Extra configuration values.

Returns:

The new provider.

find_provider(uid: str | None = None) → StorageProvider | None

Find a storage provider.

Parameters:

uid – Provider uid. If not given, the first provider is returned.

Returns:

The provider, or None if not found.

class gws.StorageProvider

Bases: Node

Storage provider, stores named records grouped by category.

delete(category: str, name: str)

Delete a record.

Parameters:
  • category – Category name.

  • name – Record name.

list_names(category: str) → list[str]

List the record names in a category.

Parameters:

category – Category name.

Returns:

Record names.

read(category: str, name: str) → StorageRecord | None

Read a record.

Parameters:
  • category – Category name.

  • name – Record name.

Returns:

The record, or None if not found.

write(category: str, name: str, data: str, user_uid: str)

Create a record or update an existing one.

Parameters:
  • category – Category name.

  • name – Record name.

  • data – Serialized record data.

  • user_uid – Uid of the user who writes the record.

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

Bases: Data

Storage record.

created: datetime.datetime

Record create time.

data: str

Serialized record data.

name: str

Record name.

updated: datetime.datetime

Record update time.

userUid: str

Uid of the user who last wrote the record.

class gws.Style

Feature style.

cssSelector: str

CSS selector of the style.

text: str

Raw CSS text of the style.

values: StyleValues

Parsed style values.

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

Style values, as parsed by gws.lib.style.parser.

fill: Color

Fill color.

icon: str

Icon for point geometries. After parsing, a gws.lib.style.icon.ParsedIcon object.

label_align: Literal['left', 'right', 'center']

Horizontal text alignment of the label.

label_background: Color

Label background color.

label_fill: Color

Label text color.

label_font_family: str

Label font family.

label_font_size: int

Label font size in pixels.

label_font_style: Literal['normal', 'italic']

Label font style.

label_font_weight: Literal['normal', 'bold']

Label font weight.

label_line_height: int

Line spacing for multi-line labels.

label_max_scale: int

Maximal scale denominator at which the label is shown.

label_min_scale: int

Minimal scale denominator at which the label is shown.

label_offset_x: int

Horizontal label offset in pixels.

label_offset_y: int

Vertical label offset in pixels.

label_padding: list[int]

Label padding in pixels, as [top, right, bottom, left].

label_placement: Literal['start', 'end', 'middle']

the first point, the last point or the centroid.

Type:

Label position along the geometry

label_stroke: Color

Label text stroke color.

label_stroke_dasharray: list[int]

Label text dash pattern.

label_stroke_dashoffset: int

Offset of the label text dash pattern.

label_stroke_linecap: Literal['butt', 'round', 'square']

Shape of label text line ends.

label_stroke_linejoin: Literal['bevel', 'round', 'miter']

Shape of label text line corners.

label_stroke_miterlimit: int

Limit for label text miter joins.

label_stroke_width: int

Label text stroke width in pixels.

marker: Literal['circle', 'square', 'arrow', 'cross']

Marker symbol drawn at the vertices of a geometry.

marker_fill: Color

Marker fill color.

marker_size: int

Marker size in pixels.

marker_stroke: Color

Marker stroke color.

marker_stroke_dasharray: list[int]

Marker dash pattern.

marker_stroke_dashoffset: int

Offset of the marker dash pattern.

marker_stroke_linecap: Literal['butt', 'round', 'square']

Shape of marker line ends.

marker_stroke_linejoin: Literal['bevel', 'round', 'miter']

Shape of marker line corners.

marker_stroke_miterlimit: int

Limit for marker miter joins.

marker_stroke_width: int

Marker stroke width in pixels.

offset_x: int

Horizontal offset of the drawn geometry in pixels.

offset_y: int

Vertical offset of the drawn geometry in pixels.

point_size: int

Diameter of point geometries in pixels.

stroke: Color

Stroke (line) color.

stroke_dasharray: list[int]

Dash pattern, as a list of dash and gap lengths.

stroke_dashoffset: int

Offset of the dash pattern.

stroke_linecap: Literal['butt', 'round', 'square']

Shape of line ends.

stroke_linejoin: Literal['bevel', 'round', 'miter']

Shape of line corners.

stroke_miterlimit: int

Limit for miter joins.

stroke_width: int

Stroke width in pixels.

with_geometry: Literal['all', 'none']

Draw the geometry (all) or not (none).

with_label: Literal['all', 'none']

Draw the label (all) or not (none).

class gws.Template

Bases: Node

Template, generates content from data.

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, the purpose the template serves, like feature.description.

title: str

Template title.

render(tri: TemplateRenderInput) → ContentResponse

Render the template.

Parameters:

tri – Render input.

Returns:

A response with the generated content.

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

Bases: Data

Template arguments.

app: Application

Application object.

date: DateFormatter

Locale-aware date formatter.

locale: Locale

Current locale.

number: NumberFormatter

Locale-aware number formatter.

time: TimeFormatter

Locale-aware time formatter.

class gws.TemplateManager

Bases: Node

Template manager, finds templates by subject and creates them from files.

find_template(subject: str, where: list[Node], user: User = None, mime_type: str = None) → Template | None

Find a template for a subject.

The templates of the objects in where are searched in the given order, then the application templates. A template without mimeTypes matches any MIME type.

Parameters:
  • subject – Template subject.

  • where – Objects whose templates are searched, in this order.

  • user – If given, only templates this user can use.

  • mime_type – If given, only templates which can produce this MIME type.

Returns:

The first matching template, or None.

find_templates(subjects: list[str], where: list[Node], user: User = None, mime_type: str = None) → list[Template]

Find templates for several subjects.

Parameters:
  • subjects – Template subjects.

  • where – Objects whose templates are searched, in this order.

  • user – If given, only templates this user can use.

  • mime_type – If given, only templates which can produce this MIME type.

Returns:

Found templates, one per subject at most.

template_from_path(path: str) → Template | None

Create a template from a file.

The template type is derived from the file extension.

Parameters:

path – File path.

Returns:

A template, or None if the file is not a template.

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

Bases: Data

Options for the built-in application and project home pages.

footerText: str | None

HTML text for the home page footer.

homeResources: list[str] | None

Extra resource URLs for the home page.

projectResources: list[str] | None

Extra resource URLs for the project page.

withGws: bool = True

Show the GWS logo in the home page footer.

withLogin: bool = True

Show the login form on the home page.

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

Bases: Config

Print quality level users can choose.

dpi: int

Print resolution in dots per inch.

name: str

Quality level name shown to users.

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

Bases: Data

Template render input.

args: dict | Data

Template arguments.

crs: Crs

CRS for maps.

dpi: int

Output resolution in dots per inch.

locale: Locale

Locale for the output.

maps: list[MapRenderInput]

Maps to render, for print templates.

mimeOut: str

Requested output MIME type.

notify: Callable

Callback for progress messages.

project: Project

Current project.

user: User

Current user.

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

Bases: Data

How keywords are matched against a text field.

caseSensitive: bool = False

Use case-sensitive search.

minLength: int = 0

Min. keyword 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.TileMatrix(*args, **kwargs)

Bases: Data

Tile matrix, one level of a tile matrix set, as in WMTS.

extent: Extent

Matrix extent.

height: float

Matrix height in tiles.

identifier: str

Matrix identifier.

resolution: float

Resolution in CRS units per pixel.

scale: float

Scale denominator.

tileHeight: float

Tile height in pixels.

tileWidth: float

Tile width in pixels.

width: float

Matrix width in tiles.

x: float

X coordinate of the top left corner.

y: float

Y coordinate of the top left corner.

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

Bases: Data

Tile matrix set, a pyramid of tile matrices, as in WMTS.

crs: Crs

CRS of the matrices.

identifier: str

Matrix set identifier.

matrices: list[TileMatrix]

Matrices of the set.

class gws.TileStore

Storage for encoded map tiles of one grid.

Tiles are addressed by (x, y, z). A tile counts as stored only while it is younger than maxAge.

baseDir: str

Base directory of the store.

maxAge: int

Max. age of stored tiles in seconds.

drop()

Remove the whole store.

drop_level(z: int)

Remove all tiles of a level.

Parameters:

z – Zoom level.

drop_range(mtr: MapTileRange)

Remove the tiles of a range.

Parameters:

mtr – Tile range.

has(mt: MapTile) → bool

Check if a tile is stored.

Parameters:

mt – Tile.

Returns:

True if the tile is stored and younger than maxAge.

path(mt: MapTile) → str

Return the file path of a tile.

Parameters:

mt – Tile.

Returns:

The file path, whether the tile exists or not.

read(mt: MapTile) → bytes | None

Read a stored tile.

Parameters:

mt – Tile.

Returns:

The tile content, or None if the tile is missing, stale or unreadable.

stats() → TileStoreStats

Compute statistics for the whole store.

Returns:

Number and size of stored tiles. The tile range is not set.

stats_for_level(z: int) → TileStoreStats

Compute statistics for a level.

Parameters:

z – Zoom level.

Returns:

Number, size and bounding tile range of the stored tiles of the level.

write(mt: MapTile, blob: bytes)

Store a tile.

Parameters:
  • mt – Tile.

  • blob – Encoded tile content.

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

Bases: Data

Tile store statistics.

count: int

Number of stored tiles.

range: MapTileRange | None

Bounding tile range of the stored tiles, only for a single level.

size: int

Total size of stored tiles in bytes.

class gws.TimeFormatter

Locale-aware time formatter.

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

Format a time.

Parameters:
  • fmt – Format type, or a babel (CLDR) time pattern like HH:mm.

  • time – Time, datetime or time string, the current time by default.

Returns:

The formatted time.

Raises:

Error – If the time cannot be parsed.

iso(time=None) → str

Format a time in the ISO 8601 format, with the time zone offset, e.g. 11:22:33+0100.

Parameters:

time – Time, datetime or time string, the current time by default.

Returns:

The formatted time.

long(time=None) → str

Format a time in the long format of the locale, which usually includes the time zone.

Parameters:

time – Time, datetime or time string, the current time by default.

Returns:

The formatted time.

medium(time=None) → str

Format a time in the medium format of the locale, e.g. 11:22:33.

Parameters:

time – Time, datetime or time string, the current time by default.

Returns:

The formatted time.

short(time=None) → str

Format a time in the short format of the locale, e.g. 11:22.

Parameters:

time – Time, datetime or time string, the current time by default.

Returns:

The formatted time.

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 Data object, a Mapping or None.

Returns:

A Data object.

Raises:

ValueError – If the value cannot be converted.

exception gws.TooManyRequestsError

Bases: Error

Generic ‘too many requests’ error.

retryAfter: int = 0

Time in seconds after which the request can be repeated.

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'

Decimetre.

fath = 'fath'

Fathom (EPSG 9014).

ft = 'ft'

Foot (EPSG 9002).

grad = 'grad'

Grad (EPSG 9105).

inch = 'in'

Inch.

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'

Typographic point (1/72 inch).

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_mi = 'us-mi'

US survey mile (EPSG 9035).

us_yd = 'us-yd'

US survey yard.

yd = 'yd'

Yard (EPSG 9096).

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

An extent with a unit, like (0, 0, 10, 20, Uom.mm).

type gws.UomExtentStr = list[str]

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

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

A point with a unit, like (1, 2, Uom.mm).

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, like (10, 20, Uom.mm).

type gws.UomSizeStr = list[str]

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

type gws.UomValue = tuple[float, Uom]

A value with a unit, like (5, Uom.mm).

type gws.UomValueStr = str

A value with a unit like 5mm.

type gws.Url = str

URL.

class gws.User

Bases: Object

User.

A user has a set of roles, which are checked against the permissions of objects to decide access.

attributes: dict

Public user attributes, sent to the client.

authProvider: AuthProvider

The provider that created the user.

authToken: str

Token for the token authentication method.

data: dict

Private user data from the provider.

displayName: str

User display name.

email: str

User email.

isGuest: bool

The user is the guest user.

localUid: str

User uid within its provider.

loginName: str

User login name.

mfaSecret: str

Secret for the multi-factor adapter.

mfaUid: str

Uid of the multi-factor adapter for this user, empty if none.

roles: set[str]

User roles.

uid: str

Global user uid, made of the provider uid and the local uid.

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

Get the access decision for an object itself, without parents.

Parameters:
  • access – Access mode.

  • obj – The object.

Returns:

gws.c.ALLOW or gws.c.DENY if the object’s permissions decide for one of the user’s roles, None otherwise.

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

Get an object by uid, if the user can access it.

Parameters:
  • uid – Object uid.

  • classref – Class reference. If provided, the object must match it.

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

Returns:

The object, or None if it does not exist or the user may not access it.

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

Check if the user can access an object.

If the object’s permissions do not decide, the context objects are checked in turn, then the parents of the last checked object.

Parameters:
  • access – Access mode.

  • obj – The object.

  • *context – Further objects to check, before the parents.

Returns:

True if access is granted.

can_create(obj: Object, *context) → bool

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

Parameters:
  • obj – The object.

  • *context – Further objects to check, before the parents.

Returns:

True if access is granted.

can_delete(obj: Object, *context) → bool

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

Parameters:
  • obj – The object.

  • *context – Further objects to check, before the parents.

Returns:

True if access is granted.

can_edit(obj: Object, *context) → bool

Check if the user has any of the write, create or delete permissions on an object.

Parameters:
  • obj – The object.

  • *context – Further objects to check, before the parents.

Returns:

True if access is granted.

can_read(obj: Object, *context) → bool

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

Parameters:
  • obj – The object.

  • *context – Further objects to check, before the parents.

Returns:

True if access is granted.

can_use(obj: Object, *context) → bool

Check if the user can use an object, which requires the read permission.

Parameters:
  • obj – The object.

  • *context – Further objects to check, before the parents.

Returns:

True if access is granted.

can_write(obj: Object, *context) → bool

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

Parameters:
  • obj – The object.

  • *context – Further objects to check, before the parents.

Returns:

True if access is granted.

has_role(role: str) → bool

Check if the user has a role.

Parameters:

role – Role name.

Returns:

True if the user has the role.

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

Get an object by uid and fail if it is not found or not accessible.

Parameters:
  • uid – Object uid.

  • classref – Class reference. If provided, the object must match it.

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

Returns:

The object.

Raises:
require_layer(uid=None) → Layer

Get a layer the user can read.

Parameters:

uid – Layer uid.

Returns:

The layer.

Raises:
require_project(uid: str = None) → Project

Get a project the user can read.

Parameters:

uid – Project uid.

Returns:

The project.

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

Bases: Data

CORS options.

allowCredentials: bool

Allow credentials in cross-origin requests.

allowHeaders: str

Headers allowed in cross-origin requests.

allowMethods: str

Methods allowed in cross-origin requests.

allowOrigin: str

Origins allowed to make cross-origin requests.

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

Bases: Data

Directory served over the web.

allowMime: list[str]

Allowed mime types.

denyMime: list[str]

Restricted mime types.

dir: DirPath

Local directory.

class gws.WebManager

Bases: Node

Web manager, holds the web site.

site: WebSite

Configured web site.

class gws.WebRequester

Web requester, gives access to an incoming web request.

contentType: str

Request content type.

environ: dict

Request environment.

host: str

Request host name, without the port, empty if the host is invalid.

ip: str

Client address.

isApi: bool

The request provides json data in the POST body.

isForm: bool

The request provides form data in the POST body.

isGet: bool

The request is a GET request.

isPost: bool

The request is a POST request.

isSecure: bool

The request is made over https.

method: RequestMethod

Request method.

port: int

Request port, 0 if not given.

root: Root

Object tree root.

scheme: str

Request scheme, http or https.

session: AuthSession

Current session.

site: WebSite

Website the request is processed for.

user: User

Current user.

absolute_url_for(request_path: str, **params) → str

Create an absolute URL pointing to the requested host.

Parameters:
  • request_path – Request path.

  • **params – Additional GET parameters.

Returns:

A URL.

api_responder(response: Response) → WebResponder

Create a responder for an API (structured) response.

The response is encoded as JSON or MessagePack, depending on the request.

Parameters:

response – Response object.

Returns:

A responder.

canonical_url_for(request_path: str, **params) → str

Create an absolute URL pointing to the canonical host.

Parameters:
  • request_path – Request path.

  • **params – Additional GET parameters.

Returns:

A URL.

command() → str

Return the command name.

Returns:

The command from the path, or from the cmd parameter.

content_responder(response: ContentResponse) → WebResponder

Create a responder for a content response.

Parameters:

response – Response with literal content or a content path.

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

Return the raw POST data, unzipped if gzip-encoded.

Returns:

POST data, empty for non-POST requests.

Raises:

gws.base.web.error.HTTPException – If the content length is invalid or too large, or the data cannot be unzipped.

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

Get a WSGI environment variable.

Parameters:
  • key – Variable name.

  • default – Default value.

Returns:

A variable value.

error_responder(exc: Exception) → WebResponder

Create a responder for an exception.

Parameters:

exc – An exception; anything but an HTTP exception results in a 500 response.

Returns:

A responder.

form() → list[tuple[str, Any]]

Return the POST form data.

Returns:

A list of (key, value) tuples, including uploaded files; empty if the request is not a form.

Raises:

gws.base.web.error.HTTPException – If the form data cannot be decoded.

has_param(key: str) → bool

Check if a GET parameter exists, ignoring case.

Parameters:

key – Parameter name.

Returns:

True if the parameter exists.

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, ignoring case.

Parameters:
  • key – Parameter name.

  • default – Default value.

Returns:

A parameter value.

params() → dict

Return the GET parameters.

Returns:

Parameters from the query string and from the request path.

parse()

Parse the request path, the parameters and the structured payload.

Also determines the scheme, host, port and client address, taking proxy headers into account if the site has proxies.

Raises:

gws.base.web.error.HTTPException – If the request path, the host or the payload is invalid.

path() → str

Return the request path after the command.

Returns:

The rest of the path after /_/<command>/.

query_params() → dict

Return the GET parameters from the query string.

Returns:

Query string parameters.

redirect_responder(response: RedirectResponse) → WebResponder

Create a responder for a redirect response.

Parameters:

response – Redirect response.

Returns:

A responder.

relative_url_for(request_path: str, **params) → str

Create a host-relative URL.

Parameters:
  • request_path – Request path.

  • **params – Additional GET parameters.

Returns:

A URL.

set_session(session: AuthSession)

Attach a session to the requester and set the user from it.

Parameters:

session – A session object.

struct() → dict

Return the structured payload of an API request.

Returns:

The decoded JSON or MessagePack payload.

text() → str

Return the POST data decoded to text, with the charset of the request.

Returns:

POST data as text.

Raises:

gws.base.web.error.HTTPException – If the data cannot be decoded.

class gws.WebResponder

Web responder, builds and sends the response to a web request.

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.

Returns:

The WSGI response iterable.

set_body(body: str | bytes)

Set the response body.

Parameters:

body – New response body; strings are encoded as UTF-8.

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

URL rewrite rule.

options: dict

Extra options.

pattern: Regex

URL matching pattern.

reversed: bool

The rule rewrites URLs generated by the server, not incoming URLs.

target: str

Rule target, with $1, $2 etc. placeholders for the pattern groups.

class gws.WebSite

Bases: Node

Web site the server responds to.

assetsRoot: WebDocumentRoot | None

Root directory for assets.

canonicalHost: str

Host name for absolute canonical URLs.

corsOptions: WebCors

CORS options.

hostnames: list[str]

Host names this site responds to.

proxyCount: int

Number of proxies in front of the server.

rewriteRules: list[WebRewriteRule]

URL rewrite rules.

ssl: bool

The site is served over https.

staticRoot: WebDocumentRoot

Root directory for static files.

url_for(req: WebRequester, path: str, mode: str, **params) → str

Create a URL for a request path, applying the reversed rewrite rules.

If the path, or the rewritten path, is an absolute URL, only the parameters are added. In the absolute and canonical modes, the URL gets the scheme of the request. The host is the canonical host in the canonical mode, and the request host and port otherwise or if there is no canonical host.

Parameters:
  • req – Web requester.

  • path – Request path.

  • mode – absolute, relative or canonical.

  • **params – Extra GET parameters.

Returns:

A URL.

Raises:

gws.BadRequestError – If an absolute URL is requested and there is no host.

class gws.XmlElement

Bases: Iterable

XML Element.

Implements a subset of the ElementTree.Element API.

tag is either a local name (Point) or a Clark name ({http://www.opengis.net/gml/3.2}Point); name is always the local name. Prefixed names never occur in a tree: tag() resolves ID:name to a Clark name, the parser resolves prefixes against the document’s declarations. The element itself (constructor, add(), set()) takes names as they are; it has no namespace map to resolve against.

attrib: dict

Dictionary of element attributes.

name: str

Element name (tag without a namespace).

namespaces: list[XmlNamespace]

Namespaces declared on this element (prefix == '' for the default namespace).

tag: str

Tag name, local or Clark.

tail: str

Text after this element’s end tag.

text: str

Text before first subelement.

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

Create a new element and add it as a child.

Names are taken as they are (local or Clark); ID:name resolution is done by tag() only.

Parameters:
  • tag – Tag name, local or Clark.

  • attrib – Attributes.

  • **extra – Additional attributes.

Returns:

The new element.

append(subelement: XmlElement)

Add a child at the end of the list of children.

Parameters:

subelement – The element to add.

children() → list[XmlElement]

Get the children of this element.

Returns:

The list of children. This is the internal list, not a copy.

clear()

Remove the attributes, namespace declarations, children, text and tail of this element.

declare(*namespaces: XmlNamespace)

Add namespace declarations to this element.

The declarations are written as xmlns attributes on output. Namespaces already declared with the same prefix and URI are skipped.

Parameters:

*namespaces – Namespaces to declare.

extend(subelements: Iterable[XmlElement])

Add children at the end of the list of children.

Parameters:

subelements – The elements to add.

find(path: str) → XmlElement | None

Find the first matching subelement.

Parameters:

path – Tag name or path in ElementTree syntax, with local or Clark names.

Returns:

The element, or None if nothing matches.

findall(path: str) → list[XmlElement]

Find all matching subelements.

Parameters:

path – Tag name or path in ElementTree syntax, with local or Clark names.

Returns:

A list of elements in document order.

findfirst(*paths) → XmlElement | None

Find the first element that matches one of the given paths.

Parameters:

*paths – Tag names or paths in ElementTree syntax, tried in order.

Returns:

The first match, or None. Without paths, the first child, or None if there are no children.

findtext(path: str, default: str = '') → str

Find the text of the first matching subelement.

Parameters:
  • path – Tag name or path in ElementTree syntax, with local or Clark names.

  • default – Value to return if nothing matches.

Returns:

The text of the element, or default.

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

Get an attribute value.

Parameters:
  • key – Attribute name, local or Clark.

  • default – Value to return if the attribute does not exist.

Returns:

The attribute value, or default.

hasattr(key: str) → bool

Check if an attribute exists.

Parameters:

key – Attribute name, local or Clark.

Returns:

True if the attribute exists.

insert(index: int, subelement: XmlElement)

Insert a child at the given position.

Parameters:
  • index – Position in the list of children.

  • subelement – The element to insert.

isa(*names: str) → bool

Check if the local name of this element matches one of the given names, case-insensitively.

Parameters:

*names – Local names.

Returns:

True if the name matches.

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

Get the attributes.

Returns:

The attributes as (name, value) pairs.

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

Iterate over this element and all its descendants, depth-first.

Parameters:

tag – Only return elements with this tag; None or * returns all elements.

Returns:

An iterator of elements, starting with this element if it matches.

iterfind(path: str) → Iterable[XmlElement]

Iterate over all matching subelements.

Parameters:

path – Tag name or path in ElementTree syntax, with local or Clark names.

Returns:

An iterator of elements in document order.

itertext() → Iterable[str]

Iterate over the text content of this element and its descendants.

Returns:

An iterator of the non-empty texts and tails in document order, without the tail of this element.

keys() → Iterable[str]

Get the attribute names.

Returns:

The attribute names.

remove(other: XmlElement)

Remove a child.

Parameters:

other – The child to remove.

Raises:

ValueError – If the element is not a child of this element.

require(path: str) → XmlElement

Find the first matching subelement, which must exist.

Parameters:

path – Tag name or path in ElementTree syntax, with local or Clark names.

Returns:

The element.

Raises:

gws.lib.xmlx.Error – If nothing matches.

set(key: str, value: Any)

Set an attribute.

Parameters:
  • key – Attribute name, local or Clark.

  • value – Attribute value.

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

Collect texts from subelements, keyed by tag.

Texts are stripped, empty texts are skipped. If several elements have the same tag, the last text wins.

Parameters:
  • *paths – Tag names or paths in ElementTree syntax. Without paths, the direct children are used.

  • deep – If True, also collect texts from all descendants of the found elements.

Returns:

A dict of tags (local or Clark) and texts.

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

Collect texts from subelements.

Texts are stripped, empty texts are skipped.

Parameters:
  • *paths – Tag names or paths in ElementTree syntax. Without paths, the direct children are used.

  • deep – If True, also collect texts from all descendants of the found elements.

Returns:

A list of texts in document order.

textof(*paths) → str

Get the text of the first matching element that has text.

Parameters:

*paths – Tag names or paths in ElementTree syntax, tried in order.

Returns:

The text, or an empty string if no matching element has text.

to_dict() → dict

Convert the element tree to a dict.

Returns:

A dict with the keys tag, attrib, text, tail and children, where children is a list of such dicts.

to_string(opts: XmlOptions | None = None) → str

Serialize this element and its subtree.

Parameters:

opts – Serialization options.

Returns:

An XML string.

Raises:
  • gws.lib.xmlx.WriteError – If the tree contains an invalid or prefixed name.

  • gws.lib.xmlx.NamespaceError – If a namespace is unknown, or one prefix is used for different URIs.

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

Bases: Data

XML namespace.

extendsGml: bool

Namespace schema extends the GML3 schema.

prefix: str

Default prefix for this Namespace, empty for a default namespace declaration.

schemaLocation: Url

Namespace schema location.

uri: Url

Namespace uri.

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

Bases: Data

XML options for parsing and serialization.

compactWhitespace: bool = False

Collapse whitespace in text content (parsing and serialization).

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

prefixes to use instead of the default ones (namespace uri -> prefix).

Type:

Serialization

defaultNamespace: XmlNamespace | None = None

elements in this namespace are written without a prefix.

Type:

Serialization

doctype: str | None = None

document type definition (DTD), written after the XML declaration.

Type:

Serialization

removeNamespaces: bool = False

tags and attributes are local names, declarations are dropped.

Type:

Strip namespaces when parsing

withNamespaceDeclarations: bool = False

declare all namespaces used in the tree on the root element.

Type:

Serialization

withSchemaLocations: bool = False

add xsi:schemaLocation for declared namespaces that have a schema location.

Type:

Serialization

withXmlDeclaration: bool = False

write the <?xml ...?> declaration.

Type:

Serialization