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 onlib: 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 agws.extdecorator.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__.pyis 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:
EnumAccess 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)whereACL bitis1if the access is allowed and0otherwise.
- class gws.Action¶
Bases:
NodeServer action.
An action is a configurable object that provides server commands.
- class gws.ActionManager¶
Bases:
NodeAction 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
Noneto 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
Noneif 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
rawcommands, 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:
NotFoundError – If the command, the project or the action is not found.
BadRequestError – If the parameters cannot be parsed.
ForbiddenError – If the user may not use the project or the action.
- 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:
NodeApplication 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.
- authMgr: AuthManager¶
Authorization manager.
- databaseMgr: DatabaseManager¶
Database manager.
- exporterMgr: ExporterManager¶
Exporter manager.
- jobMgr: JobManager¶
Job manager.
- middlewareMgr: MiddlewareManager¶
Middleware manager.
- modelMgr: ModelManager¶
Model manager.
- monitor: ServerMonitor¶
Server monitor, watches configuration files and runs periodic tasks.
- owsServices: list[OwsService]¶
OWS services provided by the server.
- printerMgr: PrinterManager¶
Printer manager.
- 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.
- vars: dict¶
Custom variables from the configuration.
- webMgr: WebManager¶
Web manager.
- developer_option(key: str)¶
Return the value of a developer option.
Developer options are configured in the
developerproperty 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
Noneif 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
Noneif not found.
- class gws.ApplicationManifest(*args, **kwargs)¶
Bases:
DataApplication manifest, read from a
MANIFEST.jsonfile.The manifest is JSON; lines starting with
//or#are ignored.- plugins: list[ApplicationManifestPlugin] | None¶
Custom plugins.
- class gws.ApplicationManifestPlugin(*args, **kwargs)¶
Bases:
DataCustom plugin entry in the application manifest.
- class gws.AttributeType¶
Bases:
EnumFeature 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:
ForbiddenErrorCredentials are missing, wrong or expired.
- class gws.AuthManager¶
Bases:
NodeAuthorization 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.
- methods: list[AuthMethod]¶
Authentication methods.
- mfAdapters: list[AuthMultiFactorAdapter]¶
Multi-factor adapters.
- providers: list[AuthProvider]¶
Authentication providers.
- sessionMgr: AuthSessionManager¶
Session manager.
- 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
usernameandpassword.req – The web request.
- Returns:
The user, or
Noneif no provider accepts the credentials.- Raises:
ForbiddenError – If a provider rejects the credentials.
TooManyRequestsError – If the attempt is blocked by the throttle.
- 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:
Trueif 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
Noneif 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
Noneif not found.
- get_provider(uid: str) AuthProvider | None¶
Get an authentication provider by its uid.
- Parameters:
uid – Provider uid.
- Returns:
The provider, or
Noneif 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
Noneif 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:
Trueif the object is public.
- class gws.AuthMethod¶
Bases:
NodeAuthentication method.
Defines how credentials and sessions are passed between the client and the server, for example as a login form and a session cookie.
- 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
Noneif the request has no session for this method.
- class gws.AuthMultiFactorAdapter¶
Bases:
NodeMulti-factor authentication adapter.
Provides the second verification step of a login, for example a code sent by email or generated by an authenticator app.
- check_restart(mfa: AuthMultiFactorTransaction) bool¶
Check if a transaction can be restarted.
- Parameters:
mfa – The transaction.
- Returns:
Trueif 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:
Trueif 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, orNoneif 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
Noneif 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
Noneif 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:
EnumState 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:
DataMulti-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.
- state: AuthMultiFactorState¶
Current state.
- class gws.AuthProvider¶
Bases:
NodeAuthentication provider.
A source of users, for example a file, an LDAP directory or a database table, which verifies credentials.
- authenticate(method: AuthMethod, credentials: Data) User | None¶
Authenticate a user.
- Parameters:
method – The authentication method.
credentials – The credentials, for example
usernameandpassword.
- Returns:
The user, or
Noneif 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
Noneif not found.
- class gws.AuthSession¶
Authentication session.
Holds the user and arbitrary data between requests.
- created: datetime.datetime¶
Creation time.
- data: dict¶
Session data.
- method: AuthMethod | None¶
The method that created the session,
Nonefor the guest session.
- updated: datetime.datetime¶
Last update time.
- class gws.AuthSessionManager¶
Bases:
NodeAuthentication session manager.
Stores sessions persistently. A session is valid until
lifeTimehas passed since its last update, ormaxLifeTimesince its creation.- 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
Noneif 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:
EnumAxis orientation.
- xy = 'xy'¶
XY (longitude/latitude) axis orientation.
- yx = 'yx'¶
YX (latitude/longitude) axis orientation.
- class gws.Bounds(*args, **kwargs)¶
Bases:
DataGeo-referenced extent: an extent together with its CRS.
- type gws.ClassRef = type | str¶
a type, an
extclass or name likegws.ext.object.layer, or a full class name.- Type:
Class reference
- class gws.Client¶
Bases:
NodeSettings for the browser client: UI elements and client options.
- options: dict¶
Client options.
- class gws.ColumnDescription(*args, **kwargs)¶
Bases:
DataDescription of a dataset column.
- geometryType: GeometryType¶
The type of geometry stored in the column (e.g., Point, Polygon).
- 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:
EnumCommand 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.ConfigContext(*args, **kwargs)¶
Bases:
DataShared state for parsing and validating a configuration.
- errors: list[ConfigErrorInfo]¶
Errors collected so far.
- 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:
DataFull information about a configuration error.
- contextLines: list[str]¶
Source lines around the error, with line numbers, the error line is marked with
>>>.
- stack: list[ConfigLocation]¶
Locations of the objects being configured when the error occurred, innermost first.
- class gws.ConfigResult(*args, **kwargs)¶
Bases:
DataResult of a configuration run.
- errors: list[ConfigErrorInfo]¶
Configuration errors.
- warnings: list[ConfigErrorInfo]¶
Configuration warnings.
- class gws.ConfigWithAccess(*args, **kwargs)¶
Bases:
ConfigBasic config with permissions.
- permissions: PermissionsConfig | None¶
Access rules per operation.
- class gws.ContentResponse(*args, **kwargs)¶
Bases:
ResponseWeb response with literal content.
- contentFilename: str¶
File name for the attachment. If provided, the content is served as an attachment.
- headers: dict¶
Additional headers.
- 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_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,urlanduriformats imply XY, theurnandurnxformats 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
Noneif 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
urnname, as per the 2008 GeoJSON specification (https://geojson.org/geojson-spec#named-crs).- Returns:
A GeoJSON
crsdict.
- to_string(fmt: CrsFormat | None = None) str¶
Return the name of the CRS in a given format.
- Parameters:
fmt – Format to use,
CrsFormat.epsgby 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.0if the transformation fails.
- class gws.CrsFormat¶
Bases:
EnumCRS 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.
- class gws.Data(*args, **kwargs)¶
Basic data object.
This object can be instantiated by passing one or more
dictorDataarguments and/or keyword args. All keys and keywords become attributes of the object.Accessing an undefined attribute returns
Noneand 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
Dataobjects. Other values are ignored.**kwargs – Keyword args.
- class gws.DatabaseConnection¶
Database connection.
Wraps an SQLAlchemy
Connectionand provides some convenience methods. Returned byDatabaseProvider.begin. The connection does not control the transaction: it is committed or rolled back bybegin.Statements can be SQLAlchemy objects or SQL strings with
:namebind 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
Noneif 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
Noneif there are no rows or the value isNULL.- 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
Noneif 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
Noneif there are no rows or the value isNULL.
- 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
NULLvalues as empty strings.
- class gws.DatabaseManager¶
Bases:
NodeDatabase 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
providersis 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 typeext_type, if given). Withext_typeonly, 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
Noneif none matches.
- class gws.DatabaseModel¶
Bases:
ModelData model for a database table.
- db: DatabaseProvider¶
Database provider.
- 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 inmc.dbSelectandsqlFilter.- Parameters:
mc – Model context with
searchanddbSelectset.- Returns:
The SELECT statement, or
Noneif the search cannot match anything.
- column(column_name: str) sqlalchemy.Column¶
Return the SQLAlchemy
Columnobject 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
Tableobject 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
Columnobject 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, anINcondition for an iterable.- Raises:
gws.Error – If the model has no primary key or the key column does not exist.
- class gws.DatabaseProvider¶
Bases:
NodeDatabase provider.
Wraps an SQLAlchemy
Engineand 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 withbegin.- 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
nestedis 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
Columnobject 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
Engineobject 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
Engineobject 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
:namebind 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:
Trueif the table and the column exist.
- has_schema(schema_name: str) bool¶
Check if a schema exists.
- Parameters:
schema_name – Schema name.
- Returns:
Trueif the schema exists.
- has_table(table_name: str) bool¶
Check if a table exists.
- Parameters:
table_name – Table name, optionally schema-qualified.
- Returns:
Trueif 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.refreshis set. The reflected metadata is cached for the configured schema cache lifetime. Ifoptionsare given, theircacheLifeTimeis 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
:namebind 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
Tableobject 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
Noneif the table has no geometry or no data.
- type gws.DatabaseStmt = 'sqlalchemy.Executable' | str¶
An Executable SQLAlchemy object or a string SQL statement.
- type gws.DatabaseTableAlike = 'sqlalchemy.Table' | str¶
An SQLAlchemy
Tableobject or a string table name.
- class gws.DataSetDescription(*args, **kwargs)¶
Bases:
DataDescription 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.
- geometryType: GeometryType¶
The type of geometry stored in the dataset.
- 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 likedd.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.
- class gws.DateTimeFormat¶
Bases:
EnumDate or time format.
- iso = 'iso'¶
ISO 8601 format.
- long = 'long'¶
Local long format.
- medium = 'medium'¶
Local medium format.
- short = 'short'¶
Local short format.
- gws.deactivate_root()¶
Remove the current root.
- gws.EmptyValue¶
Special value for empty fields.
- class gws.Enum¶
Bases:
enum.EnumEnumeration 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 anyEnum-specific utilities.The rationale behind this is that we need
Enummembers (e.g.Color.RED) to be scalars, and not complex objects as in the standardEnum.
- exception gws.Error¶
Bases:
ExceptionGeneric GWS error.
Its
repris the first line oflog.exception_backtrace: the class name, the message and the location.
- gws.ErrorValue¶
Special value for invalid fields.
- class gws.ExportArgs(*args, **kwargs)¶
Bases:
DataArguments passed to
Exporter.run.- notify: Callable¶
Progress callback, called with an event name.
- class gws.Exporter¶
Bases:
NodeExporter.
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.
- 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:
NodeExporter 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
exporterslist, e.g. a project and the application.uid – Exporter uid.
user – User.
- Returns:
The exporter, or
Noneif 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
exporterslist, e.g. a project and the application.Noneentries 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:
RequestExport request from the client.
- 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:
EnumKind of data to export.
- raster = 'raster'¶
Raster data.
- vector = 'vector'¶
Vector features.
- class gws.ExportResponse(*args, **kwargs)¶
Bases:
ResponseExport response with the content of the result file.
- class gws.ExportTarget¶
Bases:
EnumExport 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:
DataCommand descriptor, describes the action method that handles a command.
- extCommandCategory: CommandCategory¶
Command category.
- methodPtr: Callable¶
Command method. Not set by
SpecRuntime.command_descriptor.
- owner: ExtObjectDescriptor¶
Object descriptor 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].
- 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.
- errors: list[ModelValidationError]¶
Validation errors.
- 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.
titleorlabel.
- 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:
Trueif the attribute exists.
- raw(name: str) Any¶
Get a raw attribute value from the record.
- Parameters:
name – Attribute name.
- Returns:
The value, or
Noneif 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.titlerenderstitle. The templates receive the feature attributes,featureand 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
Noneif 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_crsis set. The uid is added as theidproperty.- 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
Noneif the feature has no value.
- class gws.FeatureExportStrategy¶
Bases:
EnumHow 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:
EnumWhen 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:
PropsFeature Proprieties.
- attributes: dict¶
- createWithFeatures: list[FeatureProps] | None¶
- errors: list[ModelValidationError] | None¶
- views: dict¶
- class gws.FeatureRecord(*args, **kwargs)¶
Bases:
DataRaw data from a feature source.
- attributes: dict¶
Attribute values as read from the source or as written to it.
- meta: dict¶
Extra source information, e.g.
layerNamefor features from OWS responses.
- class gws.Finder¶
Bases:
NodeSearch provider, finds features for search queries.
- sourceLayers: list[SourceLayer]¶
Source layers to search in, for finders of OWS and QGIS sources.
- 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:
Trueif the finder can run the query.
- class gws.GeometryType¶
Bases:
EnumFeature geometry type.
OGC and SQL/MM geometry types.
References
OGC 06-103r4 (https://www.ogc.org/standards/sfa)
https://postgis.net/docs/manual-3.3/using_postgis_dbmanagement.html
- circularstring = 'circularstring'¶
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_rootorload_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.
- imageFormat: ImageFormat¶
Format tiles are stored and returned in.
- 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.
- 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:
0if 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.
- 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.
- 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
optionsdict can contain any PIL save option (see https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html).An additional option
modeis 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
backgroundsets 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.
- class gws.ImageFormat(*args, **kwargs)¶
Bases:
DataImage format: MIME types and encoding options.
- options: dict¶
Encoding options, as accepted by
Image.to_bytes.
- gws.is_data_object(x)¶
Check if the argument is a
Dataobject.- Parameters:
x – A value.
- Returns:
Trueif the value is aDataobject.
- class gws.Job(*args, **kwargs)¶
Bases:
DataBackground job data.
- payload: dict¶
Input data for the worker.
- result: dict¶
Result data from the worker.
- timeCreated: datetime.datetime¶
Creation time.
- timeUpdated: datetime.datetime¶
Time of the last update.
- class gws.JobManager¶
Bases:
NodeJob manager.
- cancel_job(job: Job) Job | None¶
Set a job to the
cancelstate.The worker notices the change on its next job update and stops.
- Parameters:
job – The job.
- Returns:
The updated job, or
Noneif the job does not exist.
- create_job(worker: type, user: User, payload: dict | Data = None) Job¶
Create a job in the
openstate.- 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
Noneif 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.
- 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
runmethod of its worker. If the worker raises an exception, the job goes into theerrorstate.- 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.
- class gws.JobState¶
Bases:
EnumBackground 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:
ResponseJob status.
- output: dict¶
Job-specific output, e.g. a download URL when the job is complete.
- exception gws.JobTerminated¶
Bases:
ExceptionRaised in a worker when its job is no longer running, e.g. because it was cancelled.
- class gws.Layer¶
Bases:
NodeLayer object.
- bounds: Bounds¶
the WGS extent clipped to the parent extent and to the CRS.
- Type:
Bounds in the map CRS
- canRenderInClient: bool¶
The layer can be drawn by the client directly from its source (
display: client).
- displayMode: LayerDisplayMode¶
How the client displays the layer.
- imageFormat: ImageFormat¶
Image format for box and tile rendering.
- loadingStrategy: FeatureLoadingStrategy¶
How the client loads features.
- ows: LayerOwsBinding¶
Binding to OWS services.
- sourceLayers: list[SourceLayer]¶
Source layers this layer is built from.
- 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
Noneif the layer has nothing to render.
- render_legend(args: dict | Data | None = None) LegendRenderOutput | None¶
Render the layer legend.
Without
argsthe output is cached for the server lifetime.- Parameters:
args – Arguments passed to the legend renderer.
- Returns:
Legend output, or
Noneif the layer has no legend.
- class gws.LayerDisplayMode¶
Bases:
EnumHow 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:
NodeBinding of a layer to OWS services: access, names and models.
- xmlNamespace: XmlNamespace | None¶
XML namespace for feature and layer names.
- class gws.LayerRenderInput(*args, **kwargs)¶
Bases:
DataInput of a layer render request.
- extraParams: dict¶
Additional request parameters, e.g.
compositeLayerUids.
- renderParams: dict¶
Parameters set by the layer for its grabber. Non-empty params mark a dynamic, uncached request.
- type: LayerRenderInputType¶
Request type.
- class gws.LayerRenderInputType¶
Bases:
EnumType 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:
DataOutput of a layer render request.
- tags: list[XmlElement]¶
SVG elements, for the
svgtype.
- class gws.Legend¶
Bases:
NodeLegend 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
Noneif there is nothing to show.
- gws.load_root(path: str = None) Root¶
Load a pickled root object, activate it and make it the current root.
sys.pathis restored first, so that plugin modules can be imported.- Parameters:
path – File path. Defaults to
config.picklein the config directory.- Returns:
The root object.
- class gws.Locale(*args, **kwargs)¶
Bases:
DataLocale data: language, territory, date and number conventions.
- gws.LockBusyError¶
Raised when a server lock cannot be acquired within the timeout.
- class gws.MapGrid(*args, **kwargs)¶
Bases:
DataFixed tile grid over a CRS, origin north-west.
Level
zhas the resolutionbaseResolution / 2**z. Seegws.lib.grid.
- class gws.MapRenderInput(*args, **kwargs)¶
Bases:
DataInput of the map renderer.
- 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.
- class gws.MapRenderInputPlane(*args, **kwargs)¶
Bases:
DataA plane of a map to render.
- compositeLayerUids: list[str]¶
Child layers to render in one composite image, for the
imageLayertype.
- styles: list[Style]¶
Styles. For
features, matched by CSS selector; forsvgLayer, the first style is used.
- type: MapRenderInputPlaneType¶
Plane type.
- class gws.MapRenderInputPlaneType¶
Bases:
EnumType 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:
DataOutput of the map renderer.
- planes: list[MapRenderOutputPlane]¶
Rendered planes, bottom to top.
- class gws.MapRenderOutputPlane(*args, **kwargs)¶
Bases:
DataA plane of a rendered map.
- elements: list[XmlElement]¶
SVG elements, for the
svgtype.
- type: MapRenderOutputPlaneType¶
Plane type.
- class gws.MapRenderOutputPlaneType¶
Bases:
EnumType 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:
DataOptions for a MapServer-based layer.
- style: StyleValues¶
Style for the layer; only a part of the style values is supported.
- type: MapServerLayerType¶
Layer type.
- class gws.MapServerLayerType¶
Bases:
EnumMapServer layer type.
- line = 'line'¶
Line layer.
- point = 'point'¶
Point layer.
- polygon = 'polygon'¶
Polygon layer.
- raster = 'raster'¶
Raster layer.
- 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.Metadata(*args, **kwargs)¶
Bases:
DataMetadata of an object, used in the client, in OWS services and in catalog records.
- dateCreated: datetime.datetime | None¶
Creation date.
- dateUpdated: datetime.datetime | None¶
Last update date.
- inspireThemeNameLocal: str¶
Name of the INSPIRE theme in the metadata language, derived from
inspireTheme.
- metaLinks: list[MetadataLink]¶
Links to metadata documents.
- temporalBegin: datetime.datetime | None¶
Start of the temporal extent.
- temporalEnd: datetime.datetime | None¶
End of the temporal extent.
- class gws.MetadataLink(*args, **kwargs)¶
Bases:
DataLink to a metadata document or another resource related to an object.
- class gws.MiddlewareManager¶
Bases:
NodeMiddleware manager.
Middleware objects process every web request: the web server calls
enter_middlewareon each of them in dependency order before the action, andexit_middlewarein reverse order after it.
- class gws.Model¶
Bases:
NodeData 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.
- geometryType: GeometryType | None¶
Type of the geometry field.
- loadingStrategy: FeatureLoadingStrategy¶
How the client loads features.
- 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.
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.ModelContext(*args, **kwargs)¶
Bases:
DataContext of a model operation.
- dbSelect: ModelSelectBuild¶
The select statement being built, for database read operations.
- op: ModelOperation¶
The operation.
- search: SearchQuery¶
The search query, for read operations.
- target: ModelReadTarget¶
Where the features are to be displayed, for read operations.
- class gws.ModelField¶
Bases:
NodeModel 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.recordandfeature.props.- attributeType: AttributeType¶
Type of the field value.
- 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.
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:
NodeModel manager.
Looks up models and provides 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
modelsattribute 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:
EnumModel 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:
EnumTarget 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:
DataParts of a database select statement, collected from the model fields.
- class gws.ModelValidator¶
Bases:
NodeModel validator.
Checks the value of a field.
- 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:
NodeModel value.
Computes a value for a field.
- 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:
NodeModel widget.
Describes how the client displays and edits a field value.
- class gws.Node¶
Bases:
ObjectGWS object tree node.
Nodes are created by the
Rootor 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 callsuper().- activate()¶
Activation hook.
Called by
Root.activateafter 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
Noneif 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
Noneif the configuration isNoneor 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
Noneto 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_configureandconfigure.- Parameters:
config – Configuration.
- is_a(classref: ClassRef) bool¶
Check if the node matches the class reference.
- Parameters:
classref – Class reference.
- Returns:
Trueif 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.
- class gws.NumberFormat¶
Bases:
EnumNumber 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.
- class gws.Object¶
Basic GWS object.
An object has permissions and can provide properties for the client.
- props(user: User) Props¶
Generate a
Propsstruct for this object.Do not call this method directly, use
gws.props_ofinstead, which also checks permissions.- Parameters:
user – The user for which the props should be generated.
- Returns:
A
Propsobject or a dict. Nested objects are converted to props as well.
- class gws.Origin¶
Bases:
EnumGrid 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.OwsCapabilities(*args, **kwargs)¶
Bases:
DataParsed capabilities of a remote OWS service.
- 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).
- class gws.OwsOperation(*args, **kwargs)¶
Bases:
DataOWS operation, as offered by a remote service or by our own service.
- class gws.OwsProtocol¶
Bases:
EnumSupported OWS protocols.
- CSW = 'CSW'¶
- WCS = 'WCS'¶
- WFS = 'WFS'¶
- WMS = 'WMS'¶
- WMTS = 'WMTS'¶
- class gws.OwsService¶
Bases:
NodeOWS service provided by GBD WebSuite.
- imageFormats: list[ImageFormat]¶
Supported image formats.
- protocol: OwsProtocol¶
Supported protocol.
- supportedOperations: list[OwsOperation]¶
Supported operations.
- 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.
- class gws.OwsServiceProvider¶
Bases:
NodeRemote OWS service used as a data provider.
- authorization: OwsAuthorization | None¶
Credentials for the service.
- operations: list[OwsOperation]¶
Operations offered by the service.
- protocol: OwsProtocol¶
Service protocol.
- sourceLayers: list[SourceLayer]¶
Layers or feature types of the service.
- 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
Noneif the service does not support it.
- class gws.OwsVerb¶
Bases:
EnumOWS 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.Printer¶
Bases:
NodePrinter, a print template offered to users.
- qualityLevels: list[TemplateQualityLevel]¶
Quality levels users can choose from.
- class gws.PrinterManager¶
Bases:
NodePrint 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:
DataMap properties for printing.
- planes: list[PrintPlane]¶
Map planes.
- styles: list[StyleProps] | None¶
Styles used by the planes.
- class gws.PrintPlane(*args, **kwargs)¶
Bases:
DataPrint plane, a single map layer in a print request.
- compositeLayerUids: list[str] | None¶
Uids of the sub-layers to render, for composite raster layers.
- features: list[FeatureProps] | None¶
Features, for features planes.
- type: PrintPlaneType¶
Plane type.
- class gws.PrintPlaneType¶
Bases:
EnumPrint 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:
RequestPrint request.
- args: dict | None¶
Template arguments.
- type: PrintRequestType¶
Request type.
- class gws.PrintRequestType¶
Bases:
EnumType of the print request.
- map = 'map'¶
- template = 'template'¶
- class gws.Project¶
Bases:
NodeProject: a map application with its own map, actions, templates and services.
- assetsRoot: WebDocumentRoot | None¶
Project assets directory, checked before the global assets directory.
- owsServices: list[OwsService]¶
OWS services published for the project.
- vars: dict¶
Custom variables.
- 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
Propsobject, orNoneif the user cannot use the object.- Raises:
Error – If the object’s
propsreturns an invalid type.
- class gws.RedirectResponse(*args, **kwargs)¶
Bases:
ResponseWeb redirect response.
- headers: dict¶
Additional headers.
- class gws.RequestMethod¶
Bases:
EnumWeb 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:
DataCommand response.
- error: ResponseError | None¶
Response error.
- class gws.Root(specs: SpecRuntime)¶
Root node of the object tree.
- app: Application¶
Application object.
- specs: SpecRuntime¶
Specs runtime.
- activate()¶
Run
activateon 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
configureorpost_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
Noneif 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 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
Noneif 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
Noneif 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:
Trueif the node was initialized,Falseif it failed.
- post_initialize()¶
Run
post_configureon 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.pathis pickled next to it, to<path>.syspath, so thatload_rootcan restore it.- Parameters:
root – The root object.
path – File path. Defaults to
config.picklein the config directory.
- Returns:
The file path.
- class gws.SearchFilter(*args, **kwargs)¶
Bases:
DataSearch filter, a tree of filter operators.
- matchAction: SearchFilterMatchAction¶
How to match multi-valued properties.
- operator: SearchFilterOperator¶
Filter operator.
- subFilters: list[SearchFilter]¶
Operands of logical operators.
- class gws.SearchFilterMatchAction¶
Bases:
EnumHow 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:
EnumSearch 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:
NodeSearch manager, runs search queries through the finders.
- run_search(search: SearchQuery, user: User) list[SearchResult]¶
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.limitif a limit is given.
- class gws.SearchQuery(*args, **kwargs)¶
Bases:
DataSearch query.
- extraArgs: dict¶
Extra arguments for custom searches.
- extraParams: dict¶
Extra parameters to pass to a provider.
- filter: SearchFilter¶
Search filter.
- sort: list[SearchSort]¶
Sort options.
- class gws.ServerManager¶
Bases:
NodeServer configuration manager.
Holds the
serverconfiguration and creates the configuration files for the embedded servers and the server 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:
NodeServer 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_taskmethod.frequency – Interval between runs in seconds, the monitor default if 0.
- Raises:
gws.Error – If the object has no
periodic_taskmethod.
- 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.
- class gws.Shape¶
Bases:
ObjectGeo-referenced geometry.
- type: GeometryType¶
Geometry type.
- 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.
- contains(other: Shape) bool¶
Check if this shape contains the other.
- Parameters:
other – Another shape.
- Returns:
Trueif this shape contains the other.
- covered_by(other: Shape) bool¶
Check if this shape is covered by the other.
- Parameters:
other – Another shape.
- Returns:
Trueif this shape is covered by the other.
- covers(other: Shape) bool¶
Check if this shape covers the other.
- Parameters:
other – Another shape.
- Returns:
Trueif this shape covers the other.
- crosses(other: Shape) bool¶
Check if this shape crosses the other.
- Parameters:
other – Another shape.
- Returns:
Trueif this shape crosses the other.
- disjoint(other: Shape) bool¶
Check if this shape does not intersect the other.
- Parameters:
other – Another shape.
- Returns:
Trueif 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:
Trueif 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:
Trueif the shapes have at least one point in common.
- is_ring() bool¶
Check if this shape is a closed and simple line.
- Returns:
Trueif this shape is a ring.
- is_simple() bool¶
Check if this shape is simple, that is, has no self-intersections.
- Returns:
Trueif this shape is simple.
- overlaps(other: Shape) bool¶
Check if this shape overlaps the other.
- Parameters:
other – Another shape.
- Returns:
Trueif 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_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.
geometryand the current type return this shape.- Returns:
A converted shape.
- Raises:
gws.Error – If the conversion is not supported.
- 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:
Trueif 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.
- class gws.SourceLayer(*args, **kwargs)¶
Bases:
DataA 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 bygws.gis.source.check_layers.- dataSource: dict¶
Parsed data source of a QGIS layer.
- defaultStyle: SourceStyle | None¶
Default style.
- layers: list[SourceLayer]¶
Sub-layers.
- properties: dict¶
Custom properties of a QGIS layer.
- resourceUrls: dict¶
WMTS resource URL templates, keyed by resource type.
- styles: list[SourceStyle]¶
Available styles.
- tileMatrixSets: list[TileMatrixSet]¶
WMTS tile matrix sets of the layer.
- class gws.SourceStyle(*args, **kwargs)¶
Bases:
DataA style of a source layer, as listed in the capabilities of a service.
- class gws.SpecReadOption¶
Bases:
EnumOptions 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
ReadErrorexceptions.
- class gws.SpecRuntime¶
Spec runtime.
Provides access to the generated specs: reading and validating values, looking up extension objects and commands, and loading classes.
- manifest: ApplicationManifest¶
Application manifest.
- 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
Noneif 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
classrefis an extension category name. Defaults todefault.
- Returns:
A class or
Noneif 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
Noneif 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
extNameandextTypeattributes.- 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:
NodeStorage 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
Noneif not found.
- class gws.StorageProvider¶
Bases:
NodeStorage 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
Noneif not found.
- class gws.StorageRecord(*args, **kwargs)¶
Bases:
DataStorage record.
- created: datetime.datetime¶
Record create time.
- updated: datetime.datetime¶
Record update time.
- class gws.Style¶
Feature style.
- values: StyleValues¶
Parsed style values.
- class gws.StyleValues(*args, **kwargs)¶
Bases:
DataStyle values, as parsed by
gws.lib.style.parser.- label_align: Literal['left', 'right', 'center']¶
Horizontal text alignment of the label.
- label_font_style: Literal['normal', 'italic']¶
Label font style.
- label_font_weight: Literal['normal', 'bold']¶
Label font weight.
- label_placement: Literal['start', 'end', 'middle']¶
the first point, the last point or the centroid.
- Type:
Label position along the geometry
- 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.
- marker: Literal['circle', 'square', 'arrow', 'cross']¶
Marker symbol drawn at the vertices of a geometry.
- marker_stroke_linecap: Literal['butt', 'round', 'square']¶
Shape of marker line ends.
- marker_stroke_linejoin: Literal['bevel', 'round', 'miter']¶
Shape of marker line corners.
- stroke_linecap: Literal['butt', 'round', 'square']¶
Shape of line ends.
- stroke_linejoin: Literal['bevel', 'round', 'miter']¶
Shape of line corners.
- 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:
NodeTemplate, generates content from data.
- render(tri: TemplateRenderInput) ContentResponse¶
Render the template.
- Parameters:
tri – Render input.
- Returns:
A response with the generated content.
- class gws.TemplateArgs(*args, **kwargs)¶
Bases:
DataTemplate arguments.
- app: Application¶
Application object.
- date: DateFormatter¶
Locale-aware date formatter.
- number: NumberFormatter¶
Locale-aware number formatter.
- time: TimeFormatter¶
Locale-aware time formatter.
- class gws.TemplateManager¶
Bases:
NodeTemplate 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
whereare searched in the given order, then the application templates. A template withoutmimeTypesmatches 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.
- class gws.TemplateOptions(*args, **kwargs)¶
Bases:
DataOptions for the built-in application and project home pages.
HTML text for the home page footer.
- class gws.TemplateQualityLevel(*args, **kwargs)¶
Bases:
ConfigPrint quality level users can choose.
- class gws.TemplateRenderInput(*args, **kwargs)¶
Bases:
DataTemplate render input.
- maps: list[MapRenderInput]¶
Maps to render, for print templates.
- notify: Callable¶
Callback for progress messages.
- class gws.TextSearchOptions(*args, **kwargs)¶
Bases:
DataHow keywords are matched against a text field.
- type: TextSearchType¶
Type of the search.
- class gws.TextSearchType¶
Bases:
EnumText 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:
DataTile matrix, one level of a tile matrix set, as in WMTS.
- class gws.TileMatrixSet(*args, **kwargs)¶
Bases:
DataTile matrix set, a pyramid of tile matrices, as in WMTS.
- 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 thanmaxAge.- drop()¶
Remove the whole store.
- 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:
Trueif the tile is stored and younger thanmaxAge.
- 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
Noneif 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.
- class gws.TileStoreStats(*args, **kwargs)¶
Bases:
DataTile store statistics.
- range: MapTileRange | None¶
Bounding tile range of the stored tiles, only for a single level.
- 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 likeHH: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.
- gws.to_data_object(x) Data¶
Convert a value to a
Dataobject.If the argument is already a
Dataobject, simply return it. If the argument isNone, an empty object is returned.- Parameters:
x – A
Dataobject, a Mapping orNone.- Returns:
A
Dataobject.- Raises:
ValueError – If the value cannot be converted.
- class gws.Uom¶
Bases:
EnumUnit 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 = 'link'¶
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).
- class gws.User¶
Bases:
ObjectUser.
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.
- data: dict¶
Private user data from the provider.
- 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.ALLOWorgws.c.DENYif the object’s permissions decide for one of the user’s roles,Noneotherwise.
- 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.readif omitted.
- Returns:
The object, or
Noneif 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:
Trueif access is granted.
- can_create(obj: Object, *context) bool¶
Check if the user has the
createpermission on an object.- Parameters:
obj – The object.
*context – Further objects to check, before the parents.
- Returns:
Trueif access is granted.
- can_delete(obj: Object, *context) bool¶
Check if the user has the
deletepermission on an object.- Parameters:
obj – The object.
*context – Further objects to check, before the parents.
- Returns:
Trueif access is granted.
- can_edit(obj: Object, *context) bool¶
Check if the user has any of the
write,createordeletepermissions on an object.- Parameters:
obj – The object.
*context – Further objects to check, before the parents.
- Returns:
Trueif access is granted.
- can_read(obj: Object, *context) bool¶
Check if the user has the
readpermission on an object.- Parameters:
obj – The object.
*context – Further objects to check, before the parents.
- Returns:
Trueif access is granted.
- can_use(obj: Object, *context) bool¶
Check if the user can use an object, which requires the
readpermission.- Parameters:
obj – The object.
*context – Further objects to check, before the parents.
- Returns:
Trueif access is granted.
- can_write(obj: Object, *context) bool¶
Check if the user has the
writepermission on an object.- Parameters:
obj – The object.
*context – Further objects to check, before the parents.
- Returns:
Trueif access is granted.
- has_role(role: str) bool¶
Check if the user has a role.
- Parameters:
role – Role name.
- Returns:
Trueif 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.readif omitted.
- Returns:
The object.
- Raises:
NotFoundError – If the object does not exist.
ForbiddenError – If the user may not access the object.
- require_layer(uid=None) Layer¶
Get a layer the user can read.
- Parameters:
uid – Layer uid.
- Returns:
The layer.
- Raises:
NotFoundError – If the layer does not exist.
ForbiddenError – If the user may not read the layer.
- require_project(uid: str = None) Project¶
Get a project the user can read.
- Parameters:
uid – Project uid.
- Returns:
The project.
- Raises:
NotFoundError – If the project does not exist.
ForbiddenError – If the user may not read the project.
- class gws.WebRequester¶
Web requester, gives access to an incoming web request.
- environ: dict¶
Request environment.
- method: RequestMethod¶
Request method.
- session: AuthSession¶
Current session.
- 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
cmdparameter.
- 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:
Trueif 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.
- class gws.WebResponder¶
Web responder, builds and sends the response to a web request.
- add_header(key: str, value: str)¶
Add a header.
- Parameters:
key – Header name.
value – Header value.
- delete_cookie(key: str, **kwargs)¶
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_responsefunction.
- 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.
- class gws.WebRewriteRule(*args, **kwargs)¶
Bases:
DataURL rewrite rule.
- options: dict¶
Extra options.
- class gws.WebSite¶
Bases:
NodeWeb site the server responds to.
- assetsRoot: WebDocumentRoot | None¶
Root directory for assets.
- rewriteRules: list[WebRewriteRule]¶
URL rewrite rules.
- 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
absoluteandcanonicalmodes, the URL gets the scheme of the request. The host is the canonical host in thecanonicalmode, and the request host and port otherwise or if there is no canonical host.- Parameters:
req – Web requester.
path – Request path.
mode –
absolute,relativeorcanonical.**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:
IterableXML Element.
Implements a subset of the
ElementTree.ElementAPI.tagis either a local name (Point) or a Clark name ({http://www.opengis.net/gml/3.2}Point);nameis always the local name. Prefixed names never occur in a tree:tag()resolvesID:nameto 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.
- namespaces: list[XmlNamespace]¶
Namespaces declared on this element (
prefix == ''for the default namespace).
- 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:nameresolution is done bytag()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
xmlnsattributes 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
ElementTreesyntax, with local or Clark names.- Returns:
The element, or
Noneif nothing matches.
- findall(path: str) list[XmlElement]¶
Find all matching subelements.
- Parameters:
path – Tag name or path in
ElementTreesyntax, 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
ElementTreesyntax, tried in order.- Returns:
The first match, or
None. Without paths, the first child, orNoneif 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
ElementTreesyntax, 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:
Trueif 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:
Trueif 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;
Noneor*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
ElementTreesyntax, 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.
- 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
ElementTreesyntax, 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
ElementTreesyntax. 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
ElementTreesyntax. 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
ElementTreesyntax, 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,tailandchildren, wherechildrenis 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.XmlOptions(*args, **kwargs)¶
Bases:
DataXML options for 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