Coverage for gws-app/gws/__init__.py: 99%
2084 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-23 16:12 +0200
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-23 16:12 +0200
1"""GBD WebSuite: basic types and interfaces.
3The ``gws`` package holds the types that all parts of GBD WebSuite share: the
4basic data containers, enums and type aliases, the error classes, the object
5tree interfaces, the base ``Config`` and ``Props`` classes, and the interfaces
6of all configurable objects (``gws.Layer``, ``gws.Map``, ``gws.Model``,
7``gws.Grabber``, ``gws.Project``, ``gws.Application`` and many more). Every GWS
8module imports it with ``import gws``.
10``gws/__init__.py`` is generated by ``app/_make_init.py`` from this file
11(``__init__.pyinc``). Each ``# @include`` line is replaced with the contents of
12a ``*.pyinc`` fragment, so the types defined in ``core/*.pyinc`` and in the
13``types.pyinc`` files of the other packages all end up in the ``gws``
14namespace. The package also re-exports these modules of ``gws.core`` under
15short names:
17- ``gws.u``: general utilities (``gws.core.util``),
18- ``gws.c``: constants (``gws.core.const``),
19- ``gws.log``: logging,
20- ``gws.debug``: debugging helpers,
21- ``gws.env``: environment variables,
23and ``gws.ext``, the decorators that register extension classes and command
24methods.
26Code base layout
27----------------
29- ``gws.core``: the lowest layer: basic types, the object tree, logging,
30 constants and general utilities.
31- ``gws.lib``: general purpose libraries (CRS, images, XML, networking, SVG,
32 styles and so on), independent of the GWS object tree.
33- ``gws.gis``: GIS functionality built on ``lib``: map rendering, zoom
34 levels, source layers and tile caches.
35- ``gws.base``: the base classes and managers of the configurable objects
36 (application, projects, maps, layers, models, actions, auth and others).
37- ``gws.plugin``: concrete implementations of the base classes (layer types,
38 auth providers, OWS services, templates, model fields and so on), each
39 registered with a ``gws.ext`` decorator.
40- ``gws.config``: configuration parsing and loading, which builds the object
41 tree from the configuration.
42- ``gws.spec``: the spec generator and runtime: type metadata used to read
43 configuration and requests and to find extension classes and commands.
44- ``gws.server``: configuration and control of the embedded servers (uWSGI,
45 NGINX, the spool server and the monitor).
46- ``gws.ext``: the extension decorators (``gws.ext.object.*``,
47 ``gws.ext.config.*``, ``gws.ext.props.*``, ``gws.ext.command.*``).
48 ``gws/ext/__init__.py`` is generated as well.
49- ``gws.test``: the test framework.
51The intended import hierarchy is ``core < lib < gis < base < plugin``: each
52layer imports only from the layers below it. ``config``, ``spec`` and
53``server`` import ``lib`` and each other, and ``base`` imports them. Nothing
54outside ``gws.plugin`` imports plugins; plugin classes are found through the
55specs and loaded on demand.
57Example::
59 import gws
60 import gws.base.layer
62 d = gws.Data(name='roads', crs='EPSG:3857')
63 d.name # 'roads'
64 d.title # None, missing attributes are None
65 gws.u.get({'a': {'b': 1}}, 'a.b') # 1
67 @gws.ext.config.layer('my')
68 class Config(gws.base.layer.Config):
69 pass
71 @gws.ext.object.layer('my')
72 class Object(gws.base.layer.Object):
73 def configure(self):
74 gws.log.info(f'configuring {self.uid}')
75"""
77from typing import (
78 TYPE_CHECKING,
79 TypeAlias,
80 cast,
81 Any,
82 Callable,
83 ContextManager,
84 Generator,
85 Iterable,
86 Iterator,
87 Literal,
88 Optional,
89 Protocol,
90 Union,
91)
93from collections.abc import (
94 Mapping,
95 Sequence,
96)
98import enum
99import datetime
101if TYPE_CHECKING:
102 import sqlalchemy
103 import numpy.typing
105# mypy: disable-error-code="empty-body"
108from . import ext
110from .core import (
111 log,
112 debug,
113 env,
114 const as c,
115 util as u,
116)
119################################################################################
120# /core/_data.pyinc
123# basic data type
125class Data:
126 """Basic data object.
128 This object can be instantiated by passing one or more ``dict`` or ``Data`` arguments
129 and/or keyword args. All keys and keywords become attributes of the object.
131 Accessing an undefined attribute returns ``None`` and no error is raised,
132 unless the attribute name starts with an underscore.
134 Example::
136 d = gws.Data({'a': 1}, b=2)
137 d.a # 1
138 d['b'] # 2
139 d.c # None
140 """
142 def __init__(self, *args, **kwargs):
143 """Create the object from dicts, ``Data`` objects and keyword args.
145 Args:
146 *args: Dicts, Mappings or ``Data`` objects. Other values are ignored.
147 **kwargs: Keyword args.
148 """
149 self.update(*args, **kwargs)
151 def __repr__(self):
152 """Return the ``repr`` of the attributes dict."""
153 return repr(vars(self))
155 def __getitem__(self, key):
156 """Return an attribute value or ``None`` if it is undefined."""
157 return vars(self).get(key)
159 def __setitem__(self, key, value):
160 """Set an attribute value."""
161 vars(self)[key] = value
163 # def __getattr__(self, attr):
164 # if attr.startswith('_'):
165 # # do not use None fallback for special props
166 # raise AttributeError(attr)
167 # return None
169 def get(self, key, default=None):
170 """Get an attribute value.
172 Args:
173 key: Attribute name.
174 default: Default value, returned if the attribute is undefined.
176 Returns:
177 The attribute value or the default.
178 """
179 return vars(self).get(key, default)
181 def setdefault(self, key, val):
182 """Set an attribute value if it is not already set.
184 Args:
185 key: Attribute name.
186 val: Attribute value.
188 Returns:
189 The current attribute value, existing or new.
190 """
191 return vars(self).setdefault(key, val)
193 def set(self, key, val):
194 """Set an attribute value.
196 Args:
197 key: Attribute name.
198 val: Attribute value.
199 """
200 vars(self)[key] = val
202 def update(self, *args, **kwargs):
203 """Update the object with keys and values from args and keywords.
205 Later values override earlier ones, keywords override args.
207 Args:
208 *args: Dicts, Mappings or ``Data`` objects. Other values are ignored.
209 **kwargs: Keyword args.
210 """
212 d = {}
213 for a in args:
214 if isinstance(a, Mapping):
215 d.update(a)
216 elif isinstance(a, Data):
217 d.update(vars(a))
218 d.update(kwargs)
219 vars(self).update(d)
222# getattr needs to be defined out of class, otherwise the type checker will accept any attribute
224def _data_getattr(self, attr):
225 """Return ``None`` for undefined attributes, raise ``AttributeError`` for names starting with an underscore."""
226 if attr.startswith('_'):
227 # do not use None fallback for special props
228 raise AttributeError(attr)
229 return None
232setattr(Data, '__getattr__', _data_getattr)
235def is_data_object(x):
236 """Check if the argument is a ``Data`` object.
238 Args:
239 x: A value.
241 Returns:
242 ``True`` if the value is a ``Data`` object.
243 """
244 return isinstance(x, Data)
247def to_data_object(x) -> 'Data':
248 """Convert a value to a ``Data`` object.
250 If the argument is already a ``Data`` object, simply return it.
251 If the argument is ``None``, an empty object is returned.
253 Args:
254 x: A ``Data`` object, a Mapping or ``None``.
256 Returns:
257 A ``Data`` object.
259 Raises:
260 ValueError: If the value cannot be converted.
261 """
263 if is_data_object(x):
264 return x
265 if isinstance(x, Mapping):
266 return Data(x)
267 if x is None:
268 return Data()
269 raise ValueError(f'cannot convert {x!r} to Data')
270################################################################################
274u.is_data_object = is_data_object
275u.to_data_object = to_data_object
279################################################################################
280# /core/_basic.pyinc
283class Enum(enum.Enum):
284 """Enumeration type.
286 Despite being declared as extending ``Enum`` (for IDE support), this class is actually just a simple object
287 and intended to be used as a collection of attributes. It doesn't provide any ``Enum``-specific utilities.
289 The rationale behind this is that we need ``Enum`` members (e.g. ``Color.RED``) to be scalars,
290 and not complex objects as in the standard ``Enum``.
291 """
292 pass
295# hack to make Enum a simple object
296globals()['Enum'] = type('Enum', (), {})
298Extent: TypeAlias = tuple[float, float, float, float]
299"""An array of 4 elements representing extent coordinates ``[min-x, min-y, max-x, max-y]``."""
301Point: TypeAlias = tuple[float, float]
302"""Point coordinates ``[x, y]``."""
304Size: TypeAlias = tuple[float, float]
305"""Size ``[width, height]``."""
308class Origin(Enum):
309 """Grid origin."""
311 nw = 'nw'
312 """North-west."""
313 sw = 'sw'
314 """South-west."""
315 ne = 'ne'
316 """North-east."""
317 se = 'se'
318 """South-east."""
319 lt = 'nw'
320 """Left top."""
321 lb = 'sw'
322 """Left bottom."""
323 rt = 'ne'
324 """Right top."""
325 rb = 'se'
326 """Right bottom."""
329FilePath: TypeAlias = str
330"""File path on the server."""
332DirPath: TypeAlias = str
333"""Directory path on the server."""
335Duration: TypeAlias = str
336"""Duration like ``1w 2d 3h 4m 5s`` or an integer number of seconds."""
338Color: TypeAlias = str
339"""CSS color name."""
341Regex: TypeAlias = str
342"""Regular expression, as used in Python."""
344FormatStr: TypeAlias = str
345"""Format string as used in Python."""
347DateStr: TypeAlias = str
348"""ISO date string like ``2019-01-30``."""
350DateTimeStr: TypeAlias = str
351"""ISO datetime string like ``2019-01-30 01:02:03``."""
353Url: TypeAlias = str
354"""URL."""
356ClassRef: TypeAlias = type | str
357"""Class reference: a type, an ``ext`` class or name like ``gws.ext.object.layer``, or a full class name."""
360class Config(Data):
361 """Object configuration."""
363 uid: str = ''
364 """Unique ID."""
367class Props(Data):
368 """Object properties."""
370 uid: str = ''
371 """Unique ID."""
374class Request(Data):
375 """Command request."""
377 projectUid: Optional[str]
378 """Unique ID of the project."""
379 localeUid: Optional[str]
380 """Locale ID for this request."""
383class EmptyRequest(Data):
384 """Empty command request."""
386 pass
389class ResponseError(Data):
390 """Response error."""
392 code: Optional[int]
393 """Error code."""
394 info: Optional[str]
395 """Information about the error."""
398class Response(Data):
399 """Command response."""
401 error: Optional[ResponseError]
402 """Response error."""
403 status: int
404 """Response status or exit code."""
407class ContentResponse(Response):
408 """Web response with literal content."""
410 content: bytes | str
411 """Response content."""
412 contentFilename: str
413 """File name for the attachment. If provided, the content is served as an attachment."""
414 contentPath: str
415 """Local path with the content."""
416 mimeType: str
417 """Response mime type."""
418 headers: dict
419 """Additional headers."""
422class RedirectResponse(Response):
423 """Web redirect response."""
425 location: str
426 """Redirect URL."""
427 headers: dict
428 """Additional headers."""
431class AttributeType(Enum):
432 """Feature attribute type."""
434 bool = 'bool'
435 """Boolean value."""
436 bytes = 'bytes'
437 """Binary data."""
438 date = 'date'
439 """Date value."""
440 datetime = 'datetime'
441 """Date and time value."""
442 feature = 'feature'
443 """Feature reference."""
444 featurelist = 'featurelist'
445 """List of features."""
446 file = 'file'
447 """File reference."""
448 float = 'float'
449 """Floating-point number."""
450 floatlist = 'floatlist'
451 """List of floating-point numbers."""
452 geometry = 'geometry'
453 """Geometry reference."""
454 int = 'int'
455 """Integer number."""
456 intlist = 'intlist'
457 """List of integer numbers."""
458 str = 'str'
459 """String value."""
460 strlist = 'strlist'
461 """List of strings."""
462 time = 'time'
463 """Time value."""
466class GeometryType(Enum):
467 """Feature geometry type.
469 OGC and SQL/MM geometry types.
471 References:
472 - OGC 06-103r4 (https://www.ogc.org/standards/sfa)
473 - https://postgis.net/docs/manual-3.3/using_postgis_dbmanagement.html
474 """
476 geometry = 'geometry'
477 """Any geometry."""
479 point = 'point'
480 """Point."""
481 curve = 'curve'
482 """Curve."""
483 surface = 'surface'
484 """Surface."""
486 geometrycollection = 'geometrycollection'
487 """Collection of geometries."""
489 linestring = 'linestring'
490 """Line string."""
491 line = 'line'
492 """Line."""
493 linearring = 'linearring'
494 """Linear ring."""
496 polygon = 'polygon'
497 """Polygon."""
498 triangle = 'triangle'
499 """Triangle."""
501 polyhedralsurface = 'polyhedralsurface'
502 """Polyhedral surface."""
503 tin = 'tin'
504 """Triangulated irregular network."""
506 multipoint = 'multipoint'
507 """Collection of points."""
508 multicurve = 'multicurve'
509 """Collection of curves."""
510 multilinestring = 'multilinestring'
511 """Collection of line strings."""
512 multipolygon = 'multipolygon'
513 """Collection of polygons."""
514 multisurface = 'multisurface'
515 """Collection of surfaces."""
517 circularstring = 'circularstring'
518 """Circular arc string."""
519 compoundcurve = 'compoundcurve'
520 """Curve composed of line strings and circular strings."""
521 curvepolygon = 'curvepolygon'
522 """Polygon with curved rings."""
525class CliParams(Data):
526 """Parameters of a command line command."""
527 pass
528################################################################################
531################################################################################
532# /core/_access.pyinc
535Acl: TypeAlias = list[tuple[int, str]]
536"""Access control list.
538A list of tuples ``(ACL bit, role-name)`` where ``ACL bit`` is ``1`` if the access is allowed and ``0`` otherwise.
539"""
541AclStr: TypeAlias = str
542"""Comma-separated rules ``allow <role>`` or ``deny <role>``."""
545class Access(Enum):
546 """Access mode."""
548 read = 'read'
549 """Permission to read the object."""
550 write = 'write'
551 """Permission to change the object."""
552 create = 'create'
553 """Permission to create new objects."""
554 delete = 'delete'
555 """Permission to delete objects."""
558class PermissionsConfig(Config):
559 """Access rules per operation."""
561 all: Optional[AclStr]
562 """Rules for read, write, create and delete at once."""
563 read: Optional[AclStr]
564 """Rules for reading or using the object."""
565 write: Optional[AclStr]
566 """Rules for changing existing objects."""
567 create: Optional[AclStr]
568 """Rules for creating new objects."""
569 delete: Optional[AclStr]
570 """Rules for deleting objects."""
571 edit: Optional[AclStr]
572 """Rules for write, create and delete at once."""
575class ConfigWithAccess(Config):
576 """Basic config with permissions."""
578 access: Optional[AclStr]
579 """Permission to read or use the object."""
580 permissions: Optional[PermissionsConfig]
581 """Access rules per operation."""
582################################################################################
585################################################################################
586# /core/_error.pyinc
589class Error(Exception):
590 """Generic GWS error.
592 Its ``repr`` is the first line of ``log.exception_backtrace``: the class name, the message and the location.
593 """
594 def __repr__(self):
595 return log.exception_backtrace(self)[0]
598class ConfigurationError(Error):
599 """GWS configuration error."""
600 pass
603class NotFoundError(Error):
604 """Generic 'object not found' error."""
605 pass
608class ForbiddenError(Error):
609 """Generic 'forbidden' error."""
610 pass
613class AuthenticationError(ForbiddenError):
614 """Credentials are missing, wrong or expired."""
615 pass
618class BadRequestError(Error):
619 """Generic 'bad request' error."""
620 pass
623class TooManyRequestsError(Error):
624 """Generic 'too many requests' error."""
626 retryAfter: int = 0
627 """Time in seconds after which the request can be repeated."""
630class ResponseTooLargeError(Error):
631 """Generic error when a response is too large."""
632 pass
635class ExternalServiceError(Error):
636 """Generic error when an external service fails."""
637 pass
640LockBusyError = u.LockBusyError
641"""Raised when a server lock cannot be acquired within the timeout."""
642################################################################################
646################################################################################
647# /spec/types.pyinc
650class ApplicationManifestPlugin(Data):
651 """Custom plugin entry in the application manifest."""
653 path: DirPath
654 """Path to the plugin directory; relative paths are resolved against the manifest location."""
656 name: str = ''
657 """Plugin name. When omitted, the directory name is used."""
660class ApplicationManifest(Data):
661 """Application manifest, read from a ``MANIFEST.json`` file.
663 The manifest is JSON; lines starting with ``//`` or ``#`` are ignored.
664 """
666 uid: Optional[str]
667 """Application identifier."""
668 release: Optional[str]
669 """Application release version."""
670 excludePlugins: Optional[list[str]]
671 """Names of the core plugins that should be deactivated."""
672 plugins: Optional[list[ApplicationManifestPlugin]]
673 """Custom plugins."""
674 locales: list[str]
675 """Locale names supported by this application."""
676 tsConfig: str
677 """Path to ``tsconfig.json``."""
678 withFallbackConfig: bool = False
679 """Use a minimal fallback configuration."""
680 withStrictConfig: bool = False
681 """Stop the application upon a configuration error."""
684class ExtObjectDescriptor(Data):
685 """Extension object descriptor."""
687 extName: str
688 """Full extension name like ``gws.ext.object.layer.wms``."""
689 extType: str
690 """Extension type like ``wms``."""
691 classPtr: type
692 """Class object."""
693 ident: str
694 """Identifier."""
695 modName: str
696 """Name of the module that contains the class."""
697 modPath: str
698 """Path to the module that contains the class."""
701class ExtCommandDescriptor(Data):
702 """Command descriptor, describes the action method that handles a command."""
704 extName: str
705 """Full command name like ``gws.ext.command.api.mapGetBox``."""
706 extType: str
707 """Command name like ``mapGetBox``."""
708 extCommandCategory: 'CommandCategory'
709 """Command category."""
710 methodName: str
711 """Name of the action method that handles the command."""
712 methodPtr: Callable
713 """Command method. Not set by ``SpecRuntime.command_descriptor``."""
714 request: 'Request'
715 """Request sent to the command. Not set by ``SpecRuntime.command_descriptor``."""
716 tArg: str
717 """Type uid of the command argument (the request)."""
718 tOwner: str
719 """Type uid of the action class that owns the command."""
720 owner: ExtObjectDescriptor
721 """Object descriptor of the action class that owns the command."""
724class SpecReadOption(Enum):
725 """Options for reading values with ``SpecRuntime.read``."""
727 acceptExtraProps = 'acceptExtraProps'
728 """Accept extra object properties."""
729 allowMissing = 'allowMissing'
730 """Allow otherwise required properties to be missing."""
731 caseInsensitive = 'caseInsensitive'
732 """Case insensitive search for properties."""
733 convertValues = 'convertValues'
734 """Try to convert values to specified types."""
735 ignoreExtraProps = 'ignoreExtraProps'
736 """Silently ignore extra object properties."""
737 verboseErrors = 'verboseErrors'
738 """Add the value and the location of an error to ``ReadError`` exceptions."""
741class CommandCategory(Enum):
742 """Command category."""
744 api = 'api'
745 """API command."""
746 cli = 'cli'
747 """CLI command."""
748 get = 'get'
749 """Web GET command."""
750 post = 'post'
751 """Web POST command."""
752 raw = 'raw'
753 """Raw Web command without preprocessing."""
756class SpecRuntime:
757 """Spec runtime.
759 Provides access to the generated specs: reading and validating values,
760 looking up extension objects and commands, and loading classes.
761 """
763 version: str
764 """Application version."""
765 manifest: ApplicationManifest
766 """Application manifest."""
767 appBundlePaths: list[str]
768 """Paths of the client bundles of all chunks."""
770 def read(self, value, type_name: str, path: str = '', options: set[SpecReadOption] = None):
771 """Read and validate a raw value according to a spec type.
773 Args:
774 value: Raw value from a config or a request.
775 type_name: Type uid or extension name.
776 path: Path of the config file, used to resolve relative paths and in error messages.
777 options: Read options.
779 Returns:
780 The parsed value. Objects are returned as ``gws.Data``.
782 Raises:
783 ``gws.spec.core.ReadError``: If the value does not match the type.
784 """
786 def object_descriptor(self, type_name: str) -> Optional[ExtObjectDescriptor]:
787 """Get an object descriptor.
789 Args:
790 type_name: Type uid or extension name.
792 Returns:
793 A descriptor or ``None`` if the type is not found.
794 """
796 def command_descriptor(self, command_category: CommandCategory, command_name: str) -> Optional[ExtCommandDescriptor]:
797 """Get a command descriptor.
799 Args:
800 command_category: Command category.
801 command_name: Command name.
803 Returns:
804 A descriptor or ``None`` if the command is not found.
805 """
807 def register_object(self, ext_name: ClassRef, obj_type: str, cls: type):
808 """Register an extension class at run time.
810 The class gets the ``extName`` and ``extType`` attributes.
812 Args:
813 ext_name: Extension category, like ``gws.ext.object.layer``.
814 obj_type: Extension type, like ``wms``.
815 cls: Class to register.
817 Raises:
818 ``gws.spec.core.Error``: If the class reference is invalid.
819 """
821 def get_class(self, classref: ClassRef, ext_type: Optional[str] = None) -> Optional[type]:
822 """Get a class object for a class reference.
824 The module defining the class is imported on demand.
826 Args:
827 classref: Class reference: a class, a class name or an extension name.
828 ext_type: Extension type, used when ``classref`` is an extension category name.
829 Defaults to ``default``.
831 Returns:
832 A class or ``None`` if the reference is not found.
834 Raises:
835 ``gws.spec.core.LoadError``: If the module cannot be imported.
836 """
838 def parse_classref(self, classref: ClassRef) -> tuple[Optional[type], str, str]:
839 """Parse a class reference.
841 Args:
842 classref: Class reference.
844 Returns:
845 A tuple ``(class object, class name, extension name)``, where only one element is set.
847 Raises:
848 ``gws.spec.core.Error``: If the class reference is invalid.
849 """
851 def get_config_types(self, lang: str) -> list[dict]:
852 """Get the configuration types as dictionaries.
854 Docstrings, titles and enum docs are taken from the strings in the given language.
856 Args:
857 lang: Language code.
859 Returns:
860 A list of type dictionaries.
861 """
862################################################################################
866################################################################################
867# /core/_tree.pyinc
870class Object:
871 """Basic GWS object.
873 An object has permissions and can provide properties for the client.
874 """
876 permissions: dict[Access, Acl]
877 """Mapping from an access mode to a list of ACL tuples."""
879 def props(self, user: 'User') -> Props:
880 """Generate a ``Props`` struct for this object.
882 Do not call this method directly, use ``gws.props_of`` instead, which also checks permissions.
884 Args:
885 user: The user for which the props should be generated.
887 Returns:
888 A ``Props`` object or a dict. Nested objects are converted to props as well.
889 """
891 def __init__(self):
892 self.permissions = {}
895from .core import tree_impl
897setattr(tree_impl, 'Access', Access)
898setattr(tree_impl, 'Error', Error)
899setattr(tree_impl, 'Data', Data)
900setattr(tree_impl, 'Props', Props)
901setattr(tree_impl, 'Object', Object)
903Object.__repr__ = tree_impl.object_repr
906class Node(Object):
907 """GWS object tree node.
909 Nodes are created by the ``Root`` or by their parent node. Configuration hooks
910 (``pre_configure``, ``configure``, ``post_configure``) are invoked for every class in the MRO
911 that defines them, base classes first, so they do not need to call ``super()``.
912 """
914 extName: str
915 """Full extension name like ``gws.ext.object.layer.wms``."""
916 extType: str
917 """Extension type like ``wms``."""
919 config: Config
920 """Configuration for this object."""
921 root: 'Root'
922 """Root object."""
923 parent: 'Node'
924 """Parent object."""
925 children: list['Node']
926 """Child objects."""
927 uid: str
928 """Unique ID."""
930 def initialize(self, config):
931 """Initialize the node.
933 Store the configuration, set up the permissions, then run ``pre_configure`` and ``configure``.
935 Args:
936 config: Configuration.
937 """
938 return tree_impl.node_initialize(self, config)
940 def pre_configure(self):
941 """Pre-configuration hook.
943 Called before ``configure``, when the node is initialized.
944 """
946 def configure(self):
947 """Configuration hook.
949 Called when the node is initialized. Raising an exception here aborts the creation of the node.
950 """
952 def post_configure(self):
953 """Post-configuration hook.
955 Called after the whole object tree has been created.
956 """
958 def activate(self):
959 """Activation hook.
961 Called by ``Root.activate`` after the configuration has been loaded.
962 """
964 def create_child(self, classref: ClassRef, config: Config = None, **kwargs) -> Optional['Node']:
965 """Create a child object.
967 Args:
968 classref: Class reference.
969 config: Configuration.
970 **kwargs: Additional configuration properties.
972 Returns:
973 A newly created object or ``None`` if the object cannot be initialized.
974 """
975 return tree_impl.node_create_child(self, classref, config, **kwargs)
977 def create_child_if_configured(self, classref: ClassRef, config=None, **kwargs) -> Optional['Node']:
978 """Create a child object if the configuration is not None.
980 Args:
981 classref: Class reference.
982 config: Configuration.
983 **kwargs: Additional configuration properties.
985 Returns:
986 A newly created object or ``None`` if the configuration is ``None`` or the object cannot be initialized.
987 """
988 return tree_impl.node_create_child_if_configured(self, classref, config, **kwargs)
990 def create_children(self, classref: ClassRef, configs: list[Config], **kwargs) -> list['Node']:
991 """Create a list of child objects from a list of configurations.
993 Args:
994 classref: Class reference.
995 configs: List of configurations.
996 **kwargs: Additional configuration properties.
998 Returns:
999 A list of newly created objects.
1000 """
1001 return tree_impl.node_create_children(self, classref, configs, **kwargs)
1003 def cfg(self, key: str, default=None):
1004 """Fetch a configuration property.
1006 Args:
1007 key: Property key. If it contains dots, fetch nested properties.
1008 default: Default to return if the property is not found.
1010 Returns:
1011 A property value.
1012 """
1013 return tree_impl.node_cfg(self, key, default)
1015 def is_a(self, classref: ClassRef) -> bool:
1016 """Check if the node matches the class reference.
1018 Args:
1019 classref: Class reference.
1021 Returns:
1022 ``True`` if the node matches.
1023 """
1024 return tree_impl.is_a(self.root, self, classref)
1026 def find_all(self, classref: Optional[ClassRef] = None) -> list['Node']:
1027 """Find all direct children that match a specific class.
1029 Args:
1030 classref: Class reference. If omitted, all children are returned.
1032 Returns:
1033 A list of objects.
1034 """
1035 return tree_impl.node_find_all(self, classref)
1037 def find_first(self, classref: Optional[ClassRef] = None) -> Optional['Node']:
1038 """Find the first direct child that matches a specific class.
1040 Args:
1041 classref: Class reference. If omitted, the first child is returned.
1043 Returns:
1044 An object or ``None``.
1045 """
1046 return tree_impl.node_find_first(self, classref)
1048 def find_closest(self, classref: Optional[ClassRef] = None) -> Optional['Node']:
1049 """Find the closest node ancestor that matches a specific class.
1051 Args:
1052 classref: Class reference. If omitted, the parent is returned.
1054 Returns:
1055 An object or ``None``.
1056 """
1058 return tree_impl.node_find_closest(self, classref)
1060 def find_ancestors(self, classref: Optional[ClassRef] = None) -> list['Node']:
1061 """Find node ancestors that match a specific class.
1063 Args:
1064 classref: Class reference. If omitted, all ancestors are returned.
1066 Returns:
1067 A list of objects, from the parent upwards.
1068 """
1069 return tree_impl.node_find_ancestors(self, classref)
1071 def find_descendants(self, classref: Optional[ClassRef] = None) -> list['Node']:
1072 """Find node descendants that match a specific class.
1074 Args:
1075 classref: Class reference. If omitted, all descendants are returned.
1077 Returns:
1078 A list of objects in the depth-first order.
1079 """
1081 return tree_impl.node_find_descendants(self, classref)
1083 def enter_middleware(self, req: 'WebRequester') -> Optional['WebResponder']:
1084 """Begin middleware processing.
1086 Args:
1087 req: Requester object.
1089 Returns:
1090 A Responder object to end the request processing, or ``None`` to continue.
1091 """
1093 def exit_middleware(self, req: 'WebRequester', res: 'WebResponder'):
1094 """Finish middleware processing.
1096 Args:
1097 req: Requester object.
1098 res: Current responder object.
1099 """
1101 def periodic_task(self):
1102 """Periodic task hook.
1104 Called by the server monitor for nodes registered with ``register_periodic_task``.
1105 """
1108class Root:
1109 """Root node of the object tree."""
1111 app: 'Application'
1112 """Application object."""
1113 specs: 'SpecRuntime'
1114 """Specs runtime."""
1115 configErrors: list
1116 """List of configuration errors."""
1117 configWarnings: list
1118 """List of configuration warnings."""
1120 nodes: list['Node']
1121 """All nodes in the tree, in the order of creation."""
1122 uidMap: dict[str, 'Node']
1123 """Mapping from uids to nodes."""
1124 uidCount: int
1125 """Counter for generated uids."""
1126 configStack: list['Node']
1127 """Nodes being configured, from the outermost to the current one."""
1128 configPaths: list[str]
1129 """Paths of the configuration files."""
1131 def __init__(self, specs: 'SpecRuntime'):
1132 """Create an empty root.
1134 Args:
1135 specs: Specs runtime.
1136 """
1137 tree_impl.root_init(self, specs)
1139 def initialize(self, obj, config):
1140 """Initialize a node and record configuration errors.
1142 Args:
1143 obj: The node.
1144 config: Configuration.
1146 Returns:
1147 ``True`` if the node was initialized, ``False`` if it failed.
1148 """
1149 return tree_impl.root_initialize(self, obj, config)
1151 def post_initialize(self):
1152 """Run ``post_configure`` on all nodes, in the reverse order of creation.
1154 Errors are logged and recorded in ``configErrors``.
1155 """
1156 return tree_impl.root_post_initialize(self)
1158 def activate(self):
1159 """Run ``activate`` on all nodes."""
1160 return tree_impl.root_activate(self)
1162 def config_warning(self, message: str):
1163 """Register a configuration warning.
1165 The warning is logged immediately and reported again after the configuration is complete.
1166 The object stack is only available when called from ``configure`` or ``post_configure``.
1168 Args:
1169 message: Warning message.
1170 """
1171 return tree_impl.root_config_warning(self, message)
1173 def find_all(self, classref: Optional[ClassRef] = None) -> list['Node']:
1174 """Find all objects that match a specific class.
1176 Args:
1177 classref: Class reference.
1179 Returns:
1180 A list of objects.
1181 """
1182 return tree_impl.root_find_all(self, classref)
1184 def find_first(self, classref: Optional[ClassRef] = None) -> Optional['Node']:
1185 """Find the first object that matches a specific class.
1187 Args:
1188 classref: Class reference.
1190 Returns:
1191 An object or ``None``.
1192 """
1193 return tree_impl.root_find_first(self, classref)
1195 def get(self, uid: str = None, classref: Optional[ClassRef] = None) -> Optional['Node']:
1196 """Get an object by its unique ID.
1198 Args:
1199 uid: Object uid.
1200 classref: Class reference. If provided, ensures that the object matches the reference.
1202 Returns:
1203 An object or ``None``.
1204 """
1205 return tree_impl.root_get(self, uid, classref)
1207 def object_count(self) -> int:
1208 """Return the number of objects in the tree.
1210 Returns:
1211 The number of objects.
1212 """
1213 return tree_impl.root_object_count(self)
1215 def create(
1216 self,
1217 classref: ClassRef,
1218 parent: Optional['Node'] = None,
1219 config: Config = None,
1220 **kwargs,
1221 ) -> Optional['Node']:
1222 """Create an object.
1224 Args:
1225 classref: Class reference.
1226 parent: Parent object.
1227 config: Configuration.
1228 **kwargs: Additional configuration properties.
1230 Returns:
1231 A newly created object or ``None`` if the object cannot be initialized.
1232 """
1233 return tree_impl.root_create(self, classref, parent, config, **kwargs)
1235 def create_shared(self, classref: ClassRef, config: Config = None, **kwargs) -> Optional['Node']:
1236 """Create a shared object, attached directly to the root.
1238 If the config has no uid, it is computed from the class reference and the configuration.
1239 If an object with this uid already exists, it is returned instead of creating a new one.
1241 Args:
1242 classref: Class reference.
1243 config: Configuration.
1244 **kwargs: Additional configuration properties.
1246 Returns:
1247 A newly created object or ``None`` if the object cannot be initialized.
1248 """
1249 return tree_impl.root_create_shared(self, classref, config, **kwargs)
1251 def create_temporary(self, classref: ClassRef, config: Config = None, **kwargs) -> Optional['Node']:
1252 """Create a temporary object, not attached to the tree.
1254 Args:
1255 classref: Class reference.
1256 config: Configuration.
1257 **kwargs: Additional configuration properties.
1259 Returns:
1260 A newly created object or ``None`` if the object cannot be initialized.
1261 """
1262 return tree_impl.root_create_temporary(self, classref, config, **kwargs)
1264 def create_application(self, config: Config = None, **kwargs) -> 'Application':
1265 """Create the Application object.
1267 Args:
1268 config: Configuration.
1269 **kwargs: Additional configuration properties.
1271 Returns:
1272 The Application object.
1273 """
1274 return tree_impl.root_create_application(self, config, **kwargs)
1277def create_root(specs: 'SpecRuntime') -> Root:
1278 """Create a new root object.
1280 Args:
1281 specs: Specs runtime.
1283 Returns:
1284 The root object.
1285 """
1286 return Root(specs)
1289def save_root(root: Root, path: str = None) -> str:
1290 """Pickle the root object to a file.
1292 ``sys.path`` is pickled next to it, to ``<path>.syspath``, so that ``load_root`` can restore it.
1294 Args:
1295 root: The root object.
1296 path: File path. Defaults to ``config.pickle`` in the config directory.
1298 Returns:
1299 The file path.
1300 """
1301 return tree_impl.save_root(root, path)
1304def load_root(path: str = None) -> Root:
1305 """Load a pickled root object, activate it and make it the current root.
1307 ``sys.path`` is restored first, so that plugin modules can be imported.
1309 Args:
1310 path: File path. Defaults to ``config.pickle`` in the config directory.
1312 Returns:
1313 The root object.
1314 """
1315 return tree_impl.load_root(path)
1318def activate_root(root: Root) -> Root:
1319 """Activate the root object and make it the current root.
1321 Args:
1322 root: The root object.
1324 Returns:
1325 The root object.
1326 """
1327 return tree_impl.activate_root(root)
1330def deactivate_root():
1331 """Remove the current root."""
1332 return tree_impl.deactivate_root()
1335def get_root() -> Root:
1336 """Return the current root object.
1338 Returns:
1339 The root object set by ``activate_root`` or ``load_root``.
1341 Raises:
1342 Error: If there is no current root.
1343 """
1344 return tree_impl.get_root()
1347def props_of(obj: Object, user: 'User', *context) -> Optional['Props']:
1348 """Generate props for an object, if the user is allowed to use it.
1350 Nested objects the user cannot read are removed from the result.
1352 Args:
1353 obj: The object.
1354 user: The user.
1355 *context: Context objects for the permission check.
1357 Returns:
1358 A ``Props`` object, or ``None`` if the user cannot use the object.
1360 Raises:
1361 Error: If the object's ``props`` returns an invalid type.
1362 """
1363 return tree_impl.props_of(obj, user, *context)
1364################################################################################
1368################################################################################
1369# /lib/mapserver/types.pyinc
1372class MapServerLayerType(Enum):
1373 """MapServer layer type."""
1375 point = 'point'
1376 """Point layer."""
1377 line = 'line'
1378 """Line layer."""
1379 polygon = 'polygon'
1380 """Polygon layer."""
1381 raster = 'raster'
1382 """Raster layer."""
1384class MapServerLayerOptions(Data):
1385 """Options for a MapServer-based layer."""
1387 type: MapServerLayerType
1388 """Layer type."""
1389 path: str
1390 """Path to the data file, e.g. an image (layer DATA option)."""
1391 tileIndex: str
1392 """Path to the tile index SHP file."""
1393 crs: 'Crs'
1394 """Layer CRS."""
1395 connectionType: str
1396 """Type of connection, only ``postgres`` is supported."""
1397 connectionString: str
1398 """Connection string for the data source."""
1399 dataString: str
1400 """Layer DATA option, overrides ``path``."""
1401 style: 'StyleValues'
1402 """Style for the layer; only a part of the style values is supported."""
1403 processing: list[str]
1404 """Processing options for the layer."""
1405 transparentColor: str
1406 """Color to treat as transparent in the layer (OFFSITE)."""
1407 sldPath: str
1408 """Path to SLD file for styling the layer."""
1409 sldName: str
1410 """Name of an SLD NamedLayer to apply."""
1411################################################################################
1414################################################################################
1415# /lib/mime/types.pyinc
1418MimeType: TypeAlias = str
1419"""A MIME type or a file extension."""
1420################################################################################
1423################################################################################
1424# /lib/uom/types.pyinc
1427class Uom(Enum):
1428 """Unit of measure."""
1430 mi = 'mi'
1431 """Statute mile (EPSG 9093)."""
1432 us_ch = 'us-ch'
1433 """US survey chain (EPSG 9033)."""
1434 us_ft = 'us-ft'
1435 """US survey foot (EPSG 9003)."""
1436 us_in = 'us-in'
1437 """US survey inch."""
1438 us_mi = 'us-mi'
1439 """US survey mile (EPSG 9035)."""
1440 us_yd = 'us-yd'
1441 """US survey yard."""
1442 cm = 'cm'
1443 """Centimetre (EPSG 1033)."""
1444 ch = 'ch'
1445 """Chain (EPSG 9097)."""
1446 dm = 'dm'
1447 """Decimetre."""
1448 deg = 'deg'
1449 """Degree (EPSG 9102)."""
1450 fath = 'fath'
1451 """Fathom (EPSG 9014)."""
1452 ft = 'ft'
1453 """Foot (EPSG 9002)."""
1454 grad = 'grad'
1455 """Grad (EPSG 9105)."""
1456 inch = 'in'
1457 """Inch."""
1458 km = 'km'
1459 """Kilometre (EPSG 9036)."""
1460 link = 'link'
1461 """Link (EPSG 9098)."""
1462 m = 'm'
1463 """Metre (EPSG 9001)."""
1464 mm = 'mm'
1465 """Millimetre (EPSG 1025)."""
1466 kmi = 'kmi'
1467 """Nautical mile (EPSG 9030)."""
1468 rad = 'rad'
1469 """Radian (EPSG 9101)."""
1470 yd = 'yd'
1471 """Yard (EPSG 9096)."""
1472 px = 'px'
1473 """Pixel."""
1474 pt = 'pt'
1475 """Typographic point (1/72 inch)."""
1478UomValue: TypeAlias = tuple[float, Uom]
1479"""A value with a unit, like ``(5, Uom.mm)``."""
1481UomValueStr: TypeAlias = str
1482"""A value with a unit like ``5mm``."""
1484UomPoint: TypeAlias = tuple[float, float, Uom]
1485"""A point with a unit, like ``(1, 2, Uom.mm)``."""
1487UomPointStr: TypeAlias = list[str]
1488"""A point with a unit like ``["1mm", "2mm"]``."""
1490UomSize: TypeAlias = tuple[float, float, Uom]
1491"""A size with a unit, like ``(10, 20, Uom.mm)``."""
1493UomSizeStr: TypeAlias = list[str]
1494"""A size with a unit like ``["1mm", "2mm"]``."""
1496UomExtent: TypeAlias = tuple[float, float, float, float, Uom]
1497"""An extent with a unit, like ``(0, 0, 10, 20, Uom.mm)``."""
1499UomExtentStr: TypeAlias = list[str]
1500"""An extent with a unit like ``["1mm", "2mm", "3mm", "4mm"]``."""
1501################################################################################
1504################################################################################
1505# /lib/image/types.pyinc
1508class ImageFormat(Data):
1509 """Image format: MIME types and encoding options."""
1511 name: str
1512 """Name of the format."""
1513 mimeTypes: list[str]
1514 """MIME types for this format."""
1515 options: dict
1516 """Encoding options, as accepted by ``Image.to_bytes``."""
1519class Image:
1520 """Raster image.
1522 Manipulation methods change the image in place and return the image itself, so that calls can be chained.
1523 """
1525 def size(self) -> Size:
1526 """Get the image size.
1528 Returns:
1529 A tuple ``(width, height)`` in pixels.
1530 """
1532 def mode(self) -> str:
1533 """Get the image mode.
1535 Returns:
1536 PIL image mode, e.g. ``RGBA``.
1537 """
1539 def convert(self, mode: str) -> 'Image':
1540 """Convert the image to a mode.
1542 Args:
1543 mode: PIL image mode.
1545 Returns:
1546 The image.
1547 """
1549 def add_box(self, color=None) -> 'Image':
1550 """Draw a 1 pixel wide frame along the image edges.
1552 The image is converted to RGBA.
1554 Args:
1555 color: Line color, black by default.
1557 Returns:
1558 The image.
1559 """
1561 def add_text(self, text: str, x=0, y=0, color=None) -> 'Image':
1562 """Draw text on the image with the default font.
1564 The image is converted to RGBA.
1566 Args:
1567 text: Text, can contain multiple lines.
1568 x: X coordinate of the top left corner of the text.
1569 y: Y coordinate of the top left corner of the text.
1570 color: Text color, black by default.
1572 Returns:
1573 The image.
1574 """
1576 def compose(self, other: 'Image', opacity=1) -> 'Image':
1577 """Place another image on top of this one, using alpha composition.
1579 The other image is resized to the size of this one if needed.
1581 Args:
1582 other: Image to place on top.
1583 opacity: Opacity of the other image, from 0 to 1.
1585 Returns:
1586 The image.
1587 """
1589 def crop(self, box) -> 'Image':
1590 """Crop the image.
1592 Args:
1593 box: Crop rectangle ``(left, upper, right, lower)`` in pixels.
1595 Returns:
1596 The image.
1597 """
1599 def paste(self, other: 'Image', where=None) -> 'Image':
1600 """Paste another image into this one.
1602 Args:
1603 other: Image to paste.
1604 where: Position ``(x, y)`` of the upper left corner, or a box ``(left, upper, right, lower)``.
1605 By default, the image is pasted at ``(0, 0)``.
1607 Returns:
1608 The image.
1609 """
1611 def resize(self, size: Size, **kwargs) -> 'Image':
1612 """Resize the image to a size, without keeping the aspect ratio.
1614 Args:
1615 size: New size ``(width, height)``.
1616 **kwargs: Options for ``PIL.Image.resize``. The default resampling is bicubic.
1618 Returns:
1619 The image.
1620 """
1622 def resize_to(self, width: int = 0, height: int = 0, **kwargs) -> 'Image':
1623 """Resize the image to a width, a height or both.
1625 If only one dimension is given, the other is computed to keep the aspect ratio.
1626 If none is given, the image is not changed.
1628 Args:
1629 width: New width.
1630 height: New height.
1631 **kwargs: Options for ``PIL.Image.resize``.
1633 Returns:
1634 The image.
1635 """
1637 def rotate(self, angle: int, **kwargs) -> 'Image':
1638 """Rotate the image counter-clockwise.
1640 Args:
1641 angle: Angle in degrees.
1642 **kwargs: Options for ``PIL.Image.rotate``. The default resampling is bicubic.
1644 Returns:
1645 The image.
1646 """
1648 def to_bytes(self, mime: MimeType = '', options: Optional[dict] = None) -> bytes:
1649 """Encode the image.
1651 The ``options`` dict can contain any PIL save option
1652 (see https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html).
1654 An additional option ``mode`` is the image mode
1655 (see https://pillow.readthedocs.io/en/stable/handbook/concepts.html#concept-modes).
1656 If provided, the image is converted to that mode before saving, with an adaptive palette.
1658 An additional option ``background`` sets the color to replace the alpha channel with
1659 when an RGBA image is saved as JPEG (default is white).
1661 Args:
1662 mime: MIME type of the output, PNG by default.
1663 options: Encoding options.
1665 Returns:
1666 The encoded image.
1667 """
1669 def to_base64(self, mime: MimeType = '', options: Optional[dict] = None) -> str:
1670 """Encode the image as a base64 string.
1672 Args:
1673 mime: MIME type of the output, PNG by default.
1674 options: Encoding options, as in ``to_bytes``.
1676 Returns:
1677 The base64 encoded image.
1678 """
1680 def to_data_url(self, mime: MimeType = '', options: Optional[dict] = None) -> str:
1681 """Encode the image as a base64 data URL.
1683 Args:
1684 mime: MIME type of the output, PNG by default.
1685 options: Encoding options, as in ``to_bytes``.
1687 Returns:
1688 A ``data:`` URL.
1689 """
1691 def to_path(self, path: str, mime: MimeType = '', options: Optional[dict] = None) -> str:
1692 """Encode the image and save it to a file.
1694 Args:
1695 path: File path.
1696 mime: MIME type of the output, PNG by default.
1697 options: Encoding options, as in ``to_bytes``.
1699 Returns:
1700 The file path.
1701 """
1703 def to_array(self) -> 'numpy.typing.NDArray':
1704 """Convert the image to a numpy array.
1706 Returns:
1707 An array of shape ``(height, width)`` or ``(height, width, channels)``.
1708 """
1710 def compare_to(self, other: 'Image') -> float:
1711 """Compare this image to another one.
1713 Computes the mean squared difference of the RGBA channels over all pixels,
1714 normalized to the range 0 to 1. Both images must be RGBA and have the same size.
1716 Args:
1717 other: Image to compare to.
1719 Returns:
1720 ``0`` if the images are equal, larger values for larger differences.
1721 """
1722################################################################################
1725################################################################################
1726# /lib/intl/types.pyinc
1729LocaleUid: TypeAlias = str
1730"""Locale UID like ``de_DE``."""
1733class Locale(Data):
1734 """Locale data: language, territory, date and number conventions."""
1736 uid: str
1737 """Locale uid like ``de_DE``. A locale without a territory has the territory ``ZZ``."""
1738 dateFormatLong: str
1739 """Long date format pattern."""
1740 dateFormatMedium: str
1741 """Medium date format pattern."""
1742 dateFormatShort: str
1743 """Short date format pattern."""
1744 dateUnits: str
1745 """Narrow names of year, month and day, e.g. ``YMD`` for ``en``, ``JMT`` for ``de``."""
1746 dayNamesLong: list[str]
1747 """Full day names."""
1748 dayNamesShort: list[str]
1749 """Abbreviated day names."""
1750 dayNamesNarrow: list[str]
1751 """Narrow day names."""
1752 firstWeekDay: int
1753 """First day of the week, ``0`` is Monday."""
1755 language: str
1756 """Language code: ``de``."""
1757 language3: str
1758 """ISO 639 alpha-3 language code: ``deu``."""
1759 languageBib: str
1760 """ISO 639-2 bibliographic language code: ``ger``."""
1761 languageName: str
1762 """Native language name: ``Deutsch``."""
1763 languageNameEn: str
1764 """English language name: ``German``."""
1766 territory: str
1767 """Territory code: ``DE``."""
1768 territoryName: str
1769 """Native territory name: ``Deutschland``."""
1770 monthNamesLong: list[str]
1771 """Full month names."""
1772 monthNamesShort: list[str]
1773 """Abbreviated month names."""
1774 monthNamesNarrow: list[str]
1775 """Narrow month names."""
1776 numberDecimal: str
1777 """Decimal separator."""
1778 numberGroup: str
1779 """Group (thousands) separator."""
1782class DateTimeFormat(Enum):
1783 """Date or time format."""
1784 short = 'short'
1785 """Local short format."""
1786 medium = 'medium'
1787 """Local medium format."""
1788 long = 'long'
1789 """Local long format."""
1790 iso = 'iso'
1791 """ISO 8601 format."""
1794class NumberFormat(Enum):
1795 """Number format."""
1796 decimal = 'decimal'
1797 """Locale decimal format."""
1798 grouped = 'grouped'
1799 """Locale grouped format."""
1800 currency = 'currency'
1801 """Locale currency format."""
1802 percent = 'percent'
1803 """Locale percent format."""
1806class DateFormatter:
1807 """Locale-aware date formatter."""
1809 def format(self, fmt: DateTimeFormat | str, date: Optional[Union['datetime.date', str]] = None) -> str:
1810 """Format a date.
1812 Args:
1813 fmt: Format type, or a ``babel`` (CLDR) date pattern like ``dd.MM.yyyy``.
1814 date: Date or date string, the current date by default.
1816 Returns:
1817 The formatted date.
1819 Raises:
1820 ``Error``: If the date cannot be parsed.
1821 """
1823 def short(self, date=None) -> str:
1824 """Format a date in the short format of the locale, e.g. ``11.12.13``.
1826 Args:
1827 date: Date or date string, the current date by default.
1829 Returns:
1830 The formatted date.
1831 """
1833 def medium(self, date=None) -> str:
1834 """Format a date in the medium format of the locale, e.g. ``11.12.2013``.
1836 Args:
1837 date: Date or date string, the current date by default.
1839 Returns:
1840 The formatted date.
1841 """
1843 def long(self, date=None) -> str:
1844 """Format a date in the long format of the locale, e.g. ``11. Dezember 2013``.
1846 Args:
1847 date: Date or date string, the current date by default.
1849 Returns:
1850 The formatted date.
1851 """
1853 def iso(self, date=None) -> str:
1854 """Format a date in the ISO 8601 format, e.g. ``2013-12-11``.
1856 Args:
1857 date: Date or date string, the current date by default.
1859 Returns:
1860 The formatted date.
1861 """
1864class TimeFormatter:
1865 """Locale-aware time formatter."""
1867 def format(self, fmt: DateTimeFormat | str, time: Optional[Union['datetime.time', str]] = None) -> str:
1868 """Format a time.
1870 Args:
1871 fmt: Format type, or a ``babel`` (CLDR) time pattern like ``HH:mm``.
1872 time: Time, datetime or time string, the current time by default.
1874 Returns:
1875 The formatted time.
1877 Raises:
1878 ``Error``: If the time cannot be parsed.
1879 """
1881 def short(self, time=None) -> str:
1882 """Format a time in the short format of the locale, e.g. ``11:22``.
1884 Args:
1885 time: Time, datetime or time string, the current time by default.
1887 Returns:
1888 The formatted time.
1889 """
1891 def medium(self, time=None) -> str:
1892 """Format a time in the medium format of the locale, e.g. ``11:22:33``.
1894 Args:
1895 time: Time, datetime or time string, the current time by default.
1897 Returns:
1898 The formatted time.
1899 """
1901 def long(self, time=None) -> str:
1902 """Format a time in the long format of the locale, which usually includes the time zone.
1904 Args:
1905 time: Time, datetime or time string, the current time by default.
1907 Returns:
1908 The formatted time.
1909 """
1911 def iso(self, time=None) -> str:
1912 """Format a time in the ISO 8601 format, with the time zone offset, e.g. ``11:22:33+0100``.
1914 Args:
1915 time: Time, datetime or time string, the current time by default.
1917 Returns:
1918 The formatted time.
1919 """
1922class NumberFormatter:
1923 """Locale-aware number formatter."""
1925 def format(self, fmt: NumberFormat | str, n, *args, **kwargs) -> str:
1926 """Format a number.
1928 Args:
1929 fmt: Format type. For an unknown format, the number is converted with ``str``.
1930 n: Number.
1931 *args: Arguments for the format method, e.g. the currency for ``currency``.
1932 **kwargs: Keyword arguments for the format method.
1934 Returns:
1935 The formatted number.
1936 """
1938 def decimal(self, n, *args, **kwargs) -> str:
1939 """Format a number as a decimal without group separators.
1941 Args:
1942 n: Number.
1943 *args: Arguments for ``babel.numbers.format_decimal``.
1944 **kwargs: Keyword arguments for ``babel.numbers.format_decimal``.
1946 Returns:
1947 The formatted number.
1948 """
1950 def grouped(self, n, *args, **kwargs) -> str:
1951 """Format a number as a decimal with group separators.
1953 Args:
1954 n: Number.
1955 *args: Arguments for ``babel.numbers.format_decimal``.
1956 **kwargs: Keyword arguments for ``babel.numbers.format_decimal``.
1958 Returns:
1959 The formatted number.
1960 """
1962 def currency(self, n, currency: str, *args, **kwargs) -> str:
1963 """Format a number as a currency value.
1965 Args:
1966 n: Number.
1967 currency: Currency code like ``EUR``.
1968 *args: Arguments for ``babel.numbers.format_currency``.
1969 **kwargs: Keyword arguments for ``babel.numbers.format_currency``.
1971 Returns:
1972 The formatted value.
1973 """
1975 def percent(self, n, *args, **kwargs) -> str:
1976 """Format a number as a percentage, ``0.5`` is 50 percent.
1978 Args:
1979 n: Number.
1980 *args: Arguments for ``babel.numbers.format_percent``.
1981 **kwargs: Keyword arguments for ``babel.numbers.format_percent``.
1983 Returns:
1984 The formatted value.
1985 """
1986################################################################################
1989################################################################################
1990# /lib/style/types.pyinc
1993class StyleValues(Data):
1994 """Style values, as parsed by ``gws.lib.style.parser``."""
1996 fill: Color
1997 """Fill color."""
1999 stroke: Color
2000 """Stroke (line) color."""
2001 stroke_dasharray: list[int]
2002 """Dash pattern, as a list of dash and gap lengths."""
2003 stroke_dashoffset: int
2004 """Offset of the dash pattern."""
2005 stroke_linecap: Literal['butt', 'round', 'square']
2006 """Shape of line ends."""
2007 stroke_linejoin: Literal['bevel', 'round', 'miter']
2008 """Shape of line corners."""
2009 stroke_miterlimit: int
2010 """Limit for miter joins."""
2011 stroke_width: int
2012 """Stroke width in pixels."""
2014 marker: Literal['circle', 'square', 'arrow', 'cross']
2015 """Marker symbol drawn at the vertices of a geometry."""
2016 marker_fill: Color
2017 """Marker fill color."""
2018 marker_size: int
2019 """Marker size in pixels."""
2020 marker_stroke: Color
2021 """Marker stroke color."""
2022 marker_stroke_dasharray: list[int]
2023 """Marker dash pattern."""
2024 marker_stroke_dashoffset: int
2025 """Offset of the marker dash pattern."""
2026 marker_stroke_linecap: Literal['butt', 'round', 'square']
2027 """Shape of marker line ends."""
2028 marker_stroke_linejoin: Literal['bevel', 'round', 'miter']
2029 """Shape of marker line corners."""
2030 marker_stroke_miterlimit: int
2031 """Limit for marker miter joins."""
2032 marker_stroke_width: int
2033 """Marker stroke width in pixels."""
2035 with_geometry: Literal['all', 'none']
2036 """Draw the geometry (``all``) or not (``none``)."""
2037 with_label: Literal['all', 'none']
2038 """Draw the label (``all``) or not (``none``)."""
2040 label_align: Literal['left', 'right', 'center']
2041 """Horizontal text alignment of the label."""
2042 label_background: Color
2043 """Label background color."""
2044 label_fill: Color
2045 """Label text color."""
2046 label_font_family: str
2047 """Label font family."""
2048 label_font_size: int
2049 """Label font size in pixels."""
2050 label_font_style: Literal['normal', 'italic']
2051 """Label font style."""
2052 label_font_weight: Literal['normal', 'bold']
2053 """Label font weight."""
2054 label_line_height: int
2055 """Line spacing for multi-line labels."""
2056 label_max_scale: int
2057 """Maximal scale denominator at which the label is shown."""
2058 label_min_scale: int
2059 """Minimal scale denominator at which the label is shown."""
2060 label_offset_x: int
2061 """Horizontal label offset in pixels."""
2062 label_offset_y: int
2063 """Vertical label offset in pixels."""
2064 label_padding: list[int]
2065 """Label padding in pixels, as ``[top, right, bottom, left]``."""
2066 label_placement: Literal['start', 'end', 'middle']
2067 """Label position along the geometry: the first point, the last point or the centroid."""
2068 label_stroke: Color
2069 """Label text stroke color."""
2070 label_stroke_dasharray: list[int]
2071 """Label text dash pattern."""
2072 label_stroke_dashoffset: int
2073 """Offset of the label text dash pattern."""
2074 label_stroke_linecap: Literal['butt', 'round', 'square']
2075 """Shape of label text line ends."""
2076 label_stroke_linejoin: Literal['bevel', 'round', 'miter']
2077 """Shape of label text line corners."""
2078 label_stroke_miterlimit: int
2079 """Limit for label text miter joins."""
2080 label_stroke_width: int
2081 """Label text stroke width in pixels."""
2083 point_size: int
2084 """Diameter of point geometries in pixels."""
2085 icon: Optional['XmlElement']
2086 """Icon for point geometries, the normalized SVG element."""
2088 offset_x: int
2089 """Horizontal offset of the drawn geometry in pixels."""
2090 offset_y: int
2091 """Vertical offset of the drawn geometry in pixels."""
2094class StyleProps(Props):
2095 """CSS Style properties."""
2097 cssSelector: Optional[str]
2098 text: Optional[str]
2099 values: Optional[dict]
2102class Style:
2103 """Feature style."""
2105 cssSelector: str
2106 """CSS selector of the style."""
2107 text: str
2108 """Raw CSS text of the style."""
2109 values: StyleValues
2110 """Parsed style values."""
2111################################################################################
2114################################################################################
2115# /lib/xmlx/types.pyinc
2118class XmlNamespace(Data):
2119 """XML namespace."""
2121 prefix: str
2122 """Default prefix for this Namespace, empty for a default namespace declaration."""
2123 uri: Url
2124 """Namespace uri."""
2125 schemaLocation: Url
2126 """Namespace schema location."""
2127 extendsGml: bool
2128 """Namespace schema extends the GML3 schema."""
2131class XmlOptions(Data):
2132 """XML options for parsing and serialization."""
2134 removeNamespaces: bool = False
2135 """Strip namespaces when parsing: tags and attributes are local names, declarations are dropped."""
2137 customNamespacePrefixes: Optional[dict[str, str]] = None
2138 """Serialization: prefixes to use instead of the default ones (namespace uri -> prefix)."""
2140 defaultNamespace: Optional['XmlNamespace'] = None
2141 """Serialization: elements in this namespace are written without a prefix."""
2143 doctype: Optional[str] = None
2144 """Serialization: document type definition (DTD), written after the XML declaration."""
2146 compactWhitespace: bool = False
2147 """Collapse whitespace in text content (parsing and serialization)."""
2149 withNamespaceDeclarations: bool = False
2150 """Serialization: declare all namespaces used in the tree on the root element."""
2152 withSchemaLocations: bool = False
2153 """Serialization: add ``xsi:schemaLocation`` for declared namespaces that have a schema location."""
2155 withXmlDeclaration: bool = False
2156 """Serialization: write the ``<?xml ...?>`` declaration."""
2159class XmlElement(Iterable):
2160 """XML Element.
2162 Implements a subset of the ``ElementTree.Element`` API.
2164 ``tag`` is either a local name (``Point``) or a Clark name (``{http://www.opengis.net/gml/3.2}Point``);
2165 ``name`` is always the local name. Prefixed names never occur in a tree: ``tag()`` resolves ``ID:name``
2166 to a Clark name, the parser resolves prefixes against the document's declarations. The element itself
2167 (constructor, ``add()``, ``set()``) takes names as they are; it has no namespace map to resolve against.
2168 """
2170 tag: str
2171 """Tag name, local or Clark."""
2173 name: str
2174 """Element name (tag without a namespace)."""
2176 text: str
2177 """Text before first subelement."""
2179 tail: str
2180 """Text after this element's end tag."""
2182 attrib: dict
2183 """Dictionary of element attributes."""
2185 namespaces: list[XmlNamespace]
2186 """Namespaces declared on this element (``prefix == ''`` for the default namespace)."""
2188 def __len__(self) -> int: ...
2190 def __iter__(self) -> Iterator['XmlElement']: ...
2192 def __getitem__(self, item: int) -> 'XmlElement': ...
2194 def append(self, subelement: 'XmlElement'):
2195 """Add a child at the end of the list of children.
2197 Args:
2198 subelement: The element to add.
2199 """
2201 def clear(self):
2202 """Remove the attributes, namespace declarations, children, text and tail of this element."""
2204 def extend(self, subelements: Iterable['XmlElement']):
2205 """Add children at the end of the list of children.
2207 Args:
2208 subelements: The elements to add.
2209 """
2211 def find(self, path: str) -> Optional['XmlElement']:
2212 """Find the first matching subelement.
2214 Args:
2215 path: Tag name or path in ``ElementTree`` syntax, with local or Clark names.
2217 Returns:
2218 The element, or ``None`` if nothing matches.
2219 """
2221 def require(self, path: str) -> 'XmlElement':
2222 """Find the first matching subelement, which must exist.
2224 Args:
2225 path: Tag name or path in ``ElementTree`` syntax, with local or Clark names.
2227 Returns:
2228 The element.
2230 Raises:
2231 gws.lib.xmlx.Error: If nothing matches.
2232 """
2234 def findall(self, path: str) -> list['XmlElement']:
2235 """Find all matching subelements.
2237 Args:
2238 path: Tag name or path in ``ElementTree`` syntax, with local or Clark names.
2240 Returns:
2241 A list of elements in document order.
2242 """
2244 def findtext(self, path: str, default: str = '') -> str:
2245 """Find the text of the first matching subelement.
2247 Args:
2248 path: Tag name or path in ``ElementTree`` syntax, with local or Clark names.
2249 default: Value to return if nothing matches.
2251 Returns:
2252 The text of the element, or ``default``.
2253 """
2255 def get(self, key: str, default: str = '') -> str:
2256 """Get an attribute value.
2258 Args:
2259 key: Attribute name, local or Clark.
2260 default: Value to return if the attribute does not exist.
2262 Returns:
2263 The attribute value, or ``default``.
2264 """
2266 def insert(self, index: int, subelement: 'XmlElement'):
2267 """Insert a child at the given position.
2269 Args:
2270 index: Position in the list of children.
2271 subelement: The element to insert.
2272 """
2274 def items(self) -> Iterable[tuple[str, Any]]:
2275 """Get the attributes.
2277 Returns:
2278 The attributes as ``(name, value)`` pairs.
2279 """
2281 def iter(self, tag: Optional[str] = None) -> Iterable['XmlElement']:
2282 """Iterate over this element and all its descendants, depth-first.
2284 Args:
2285 tag: Only return elements with this tag; ``None`` or ``*`` returns all elements.
2287 Returns:
2288 An iterator of elements, starting with this element if it matches.
2289 """
2291 def iterfind(self, path: str) -> Iterable['XmlElement']:
2292 """Iterate over all matching subelements.
2294 Args:
2295 path: Tag name or path in ``ElementTree`` syntax, with local or Clark names.
2297 Returns:
2298 An iterator of elements in document order.
2299 """
2301 def itertext(self) -> Iterable[str]:
2302 """Iterate over the text content of this element and its descendants.
2304 Returns:
2305 An iterator of the non-empty texts and tails in document order, without the tail of this element.
2306 """
2308 def keys(self) -> Iterable[str]:
2309 """Get the attribute names.
2311 Returns:
2312 The attribute names.
2313 """
2315 def remove(self, other: 'XmlElement'):
2316 """Remove a child.
2318 Args:
2319 other: The child to remove.
2321 Raises:
2322 ValueError: If the element is not a child of this element.
2323 """
2325 def set(self, key: str, value: Any):
2326 """Set an attribute.
2328 Args:
2329 key: Attribute name, local or Clark.
2330 value: Attribute value.
2331 """
2333 # extensions
2335 def hasattr(self, key: str) -> bool:
2336 """Check if an attribute exists.
2338 Args:
2339 key: Attribute name, local or Clark.
2341 Returns:
2342 ``True`` if the attribute exists.
2343 """
2345 def isa(self, *names: str) -> bool:
2346 """Check if the local name of this element matches one of the given names, case-insensitively.
2348 Args:
2349 *names: Local names.
2351 Returns:
2352 ``True`` if the name matches.
2353 """
2355 def add(self, tag: str, attrib: Optional[dict] = None, **extra) -> 'XmlElement':
2356 """Create a new element and add it as a child.
2358 Names are taken as they are (local or Clark); ``ID:name`` resolution is done by ``tag()`` only.
2360 Args:
2361 tag: Tag name, local or Clark.
2362 attrib: Attributes.
2363 **extra: Additional attributes.
2365 Returns:
2366 The new element.
2367 """
2369 def children(self) -> list['XmlElement']:
2370 """Get the children of this element.
2372 Returns:
2373 The list of children. This is the internal list, not a copy.
2374 """
2376 def declare(self, *namespaces: XmlNamespace):
2377 """Add namespace declarations to this element.
2379 The declarations are written as ``xmlns`` attributes on output. Namespaces already declared
2380 with the same prefix and URI are skipped.
2382 Args:
2383 *namespaces: Namespaces to declare.
2384 """
2386 def findfirst(self, *paths) -> Optional['XmlElement']:
2387 """Find the first element that matches one of the given paths.
2389 Args:
2390 *paths: Tag names or paths in ``ElementTree`` syntax, tried in order.
2392 Returns:
2393 The first match, or ``None``. Without paths, the first child, or ``None`` if there are no children.
2394 """
2396 def textof(self, *paths) -> str:
2397 """Get the text of the first matching element that has text.
2399 Args:
2400 *paths: Tag names or paths in ``ElementTree`` syntax, tried in order.
2402 Returns:
2403 The text, or an empty string if no matching element has text.
2404 """
2406 def textlist(self, *paths, deep=False) -> list[str]:
2407 """Collect texts from subelements.
2409 Texts are stripped, empty texts are skipped.
2411 Args:
2412 *paths: Tag names or paths in ``ElementTree`` syntax. Without paths, the direct children are used.
2413 deep: If ``True``, also collect texts from all descendants of the found elements.
2415 Returns:
2416 A list of texts in document order.
2417 """
2419 def textdict(self, *paths, deep=False) -> dict[str, str]:
2420 """Collect texts from subelements, keyed by tag.
2422 Texts are stripped, empty texts are skipped. If several elements have the same tag, the last text wins.
2424 Args:
2425 *paths: Tag names or paths in ``ElementTree`` syntax. Without paths, the direct children are used.
2426 deep: If ``True``, also collect texts from all descendants of the found elements.
2428 Returns:
2429 A dict of tags (local or Clark) and texts.
2430 """
2432 def to_string(self, opts: Optional[XmlOptions] = None) -> str:
2433 """Serialize this element and its subtree.
2435 Args:
2436 opts: Serialization options.
2438 Returns:
2439 An XML string.
2441 Raises:
2442 gws.lib.xmlx.WriteError: If the tree contains an invalid or prefixed name.
2443 gws.lib.xmlx.NamespaceError: If a namespace is unknown, or one prefix is used for different URIs.
2444 """
2446 def to_dict(self) -> dict:
2447 """Convert the element tree to a dict.
2449 Returns:
2450 A dict with the keys ``tag``, ``attrib``, ``text``, ``tail`` and ``children``,
2451 where ``children`` is a list of such dicts.
2452 """
2453################################################################################
2457################################################################################
2458# /lib/crs/types.pyinc
2461CrsName: TypeAlias = int | str
2462"""A CRS code like ``EPSG:3857`` or a SRID like ``3857``."""
2465class CrsFormat(Enum):
2466 """CRS name format."""
2468 none = ''
2469 """No format."""
2470 crs = 'crs'
2471 """Like ``crs84``."""
2472 srid = 'srid'
2473 """Like ``3857``."""
2474 epsg = 'epsg'
2475 """Like ``EPSG:3857``."""
2476 url = 'url'
2477 """Like ``http://www.opengis.net/gml/srs/epsg.xml#3857``."""
2478 uri = 'uri'
2479 """Like ``http://www.opengis.net/def/crs/epsg/0/3857``."""
2480 urnx = 'urnx'
2481 """Like ``urn:x-ogc:def:crs:EPSG:3857``."""
2482 urn = 'urn'
2483 """Like ``urn:ogc:def:crs:EPSG::3857``."""
2486class Axis(Enum):
2487 """Axis orientation."""
2489 xy = 'xy'
2490 """XY (longitude/latitude) axis orientation."""
2491 yx = 'yx'
2492 """YX (latitude/longitude) axis orientation."""
2495class Bounds(Data):
2496 """Geo-referenced extent: an extent together with its CRS."""
2498 crs: 'Crs'
2499 """Coordinate reference system of the extent."""
2500 extent: Extent
2501 """Extent in the coordinates of ``crs``."""
2504class Crs:
2505 """Coordinate reference system."""
2507 axis: Axis
2508 """Axis orientation."""
2509 base: int
2510 """Base CRS code."""
2511 bounds: Bounds
2512 """CRS own Bounds."""
2513 coordinatePrecision: int
2514 """Preferred precision for coordinates in this CRS."""
2515 datum: str
2516 """Datum."""
2517 epsg: str
2518 """Name in the "epsg" format."""
2519 extent: Extent
2520 """CRS own Extent."""
2521 isGeographic: bool
2522 """This CRS is geographic."""
2523 isProjected: bool
2524 """This CRS is projected."""
2525 isYX: bool
2526 """This CRS has a lat/lon axis."""
2527 name: str
2528 """CRS name."""
2529 proj4text: str
2530 """Proj4 definition."""
2531 srid: int
2532 """CRS SRID."""
2533 uom: Uom
2534 """CRS unit."""
2535 uri: str
2536 """Name in the "uri" format."""
2537 url: str
2538 """Name in the "url" format."""
2539 urn: str
2540 """Name in the "urn" format."""
2541 urnx: str
2542 """Name in the "urnx" format."""
2543 wgsExtent: Extent
2544 """CRS Extent in the WGS projection."""
2545 wgsMaxExtent: Extent
2546 """Maximal extent that makes sense for this CRS, in the WGS projection."""
2547 wkt: str
2548 """WKT definition."""
2550 def axis_for_format(self, fmt: 'CrsFormat') -> Axis:
2551 """Get the axis orientation implied by a CRS name format.
2553 For CRSs with a lat/lon axis, the orientation depends on how the CRS is named.
2554 We adhere to the GeoServer convention: the ``srid``, ``epsg``, ``url`` and ``uri``
2555 formats imply XY, the ``urn`` and ``urnx`` formats imply YX
2556 (see https://docs.geoserver.org/latest/en/user/services/wfs/axis_order.html).
2557 For XY CRSs, the own axis is always returned.
2559 Args:
2560 fmt: CRS name format.
2562 Returns:
2563 The axis orientation.
2564 """
2566 def clip_wgs_extent(self, wgs_extent: Extent) -> Optional[Extent]:
2567 """Clip a WGS extent to the maximal extent of this CRS.
2569 Args:
2570 wgs_extent: Extent in the WGS projection.
2572 Returns:
2573 The clipped extent in the WGS projection, or ``None`` if there is no intersection.
2574 """
2576 def extent_size_in_meters(self, extent: Extent) -> Size:
2577 """Calculate the width and height of an extent in meters.
2579 For projected CRSs, the extent size is returned as is. For geographic CRSs,
2580 geodesic distances on the WGS84 ellipsoid are measured along the middle
2581 latitude and the middle longitude of the extent.
2583 Args:
2584 extent: Extent in this CRS.
2586 Returns:
2587 A ``(width, height)`` tuple in meters.
2589 Raises:
2590 ``gws.lib.crs.Error``: If this is a projected CRS with units other than meters.
2591 """
2593 def point_offset_in_meters(self, xy: Point, dist: float, az: int) -> Point:
2594 """Calculate a point at a given distance and direction from another point.
2596 Args:
2597 xy: Point in this CRS.
2598 dist: Distance in meters.
2599 az: Azimuth in degrees (0 = North, 90 = East, etc.).
2601 Returns:
2602 The offset point in this CRS.
2604 Raises:
2605 ``gws.lib.crs.Error``: If this is a projected CRS with units other than meters.
2606 """
2608 def to_geojson(self) -> dict:
2609 """Return a GeoJSON representation of the CRS.
2611 The CRS is represented as a "named CRS" with its ``urn`` name,
2612 as per the 2008 GeoJSON specification (https://geojson.org/geojson-spec#named-crs).
2614 Returns:
2615 A GeoJSON ``crs`` dict.
2616 """
2618 def to_string(self, fmt: Optional['CrsFormat'] = None) -> str:
2619 """Return the name of the CRS in a given format.
2621 Args:
2622 fmt: Format to use, ``CrsFormat.epsg`` by default.
2624 Returns:
2625 The CRS name, like ``EPSG:3857``.
2626 """
2628 def transform_extent(self, extent: Extent, crs_to: 'Crs') -> Extent:
2629 """Transform an Extent from this CRS to another.
2631 The transformation goes through WGS84. If the extent is very large
2632 (almost the whole world) and the target CRS has a limited area of use,
2633 the result is computed by sampling points, so that it stays finite.
2635 Args:
2636 extent: Extent in this CRS.
2637 crs_to: Target CRS.
2639 Returns:
2640 The transformed Extent, with min and max values in order.
2641 """
2643 def transform_resolution(self, extent: Extent, res: float, crs_to: 'Crs') -> float:
2644 """Transform a resolution over an extent from this CRS to another.
2646 The returned resolution is the finest one found at a set of sample points of the extent,
2647 so that the target resolution is never coarser than the source resolution anywhere in the extent.
2649 Args:
2650 extent: Extent in this CRS.
2651 res: Resolution in units of this CRS per pixel.
2652 crs_to: Target CRS.
2654 Returns:
2655 The resolution in units of the target CRS per pixel, or ``0.0`` if the transformation fails.
2656 """
2658 def transformer(self, crs_to: 'Crs') -> Callable:
2659 """Create a transformer function to another CRS.
2661 The function always uses the XY (easting/longitude first) axis order.
2663 Args:
2664 crs_to: Target CRS.
2666 Returns:
2667 A function that takes ``x, y`` and returns a transformed ``(x, y)`` tuple.
2668 """
2669################################################################################
2672################################################################################
2673# /lib/shape/types.pyinc
2676class ShapeProps(Props):
2677 """Shape properties."""
2679 crs: str
2680 geometry: dict
2683class Shape(Object):
2684 """Geo-referenced geometry."""
2686 type: GeometryType
2687 """Geometry type."""
2689 crs: 'Crs'
2690 """CRS of this shape."""
2692 x: Optional[float]
2693 """X-coordinate for Point geometries, None otherwise."""
2695 y: Optional[float]
2696 """Y-coordinate for Point geometries, None otherwise."""
2698 # common props
2700 def area(self) -> float:
2701 """Compute the area of the geometry.
2703 Returns:
2704 The area in CRS units, 0 for geometries without an area.
2705 """
2707 def bounds(self) -> Bounds:
2708 """Compute the bounds of this shape.
2710 Returns:
2711 A Bounds object in the CRS of this shape.
2712 """
2714 def centroid(self) -> 'Shape':
2715 """Compute the centroid of this shape.
2717 Returns:
2718 A Point shape.
2719 """
2721 def center(self) -> tuple[float, float]:
2722 """Compute the coordinates of the centroid.
2724 Returns:
2725 A tuple ``(x, y)``.
2726 """
2728 # formats
2730 def to_wkb(self) -> bytes:
2731 """Convert this shape to WKB.
2733 Returns:
2734 WKB bytes.
2735 """
2737 def to_wkb_hex(self) -> str:
2738 """Convert this shape to hex-encoded WKB.
2740 Returns:
2741 A hex string.
2742 """
2744 def to_ewkb(self) -> bytes:
2745 """Convert this shape to EWKB, which includes the SRID.
2747 Returns:
2748 EWKB bytes.
2749 """
2751 def to_ewkb_hex(self) -> str:
2752 """Convert this shape to hex-encoded EWKB, which includes the SRID.
2754 Returns:
2755 A hex string.
2756 """
2758 def to_wkt(self, trim=False, rounding_precision=-1, output_dimension=3) -> str:
2759 """Convert this shape to WKT.
2761 Whitespace around commas and parentheses is removed.
2763 Args:
2764 trim: Remove trailing zeros from the coordinates.
2765 rounding_precision: Number of decimal places, -1 for full precision.
2766 output_dimension: Max. number of dimensions to output.
2768 Returns:
2769 A WKT string.
2770 """
2772 def to_ewkt(self, trim=False, rounding_precision=-1, output_dimension=3) -> str:
2773 """Convert this shape to EWKT, which is WKT prefixed with ``SRID=<srid>;``.
2775 Args:
2776 trim: Remove trailing zeros from the coordinates.
2777 rounding_precision: Number of decimal places, -1 for full precision.
2778 output_dimension: Max. number of dimensions to output.
2780 Returns:
2781 An EWKT string.
2782 """
2784 def to_geojson(self, keep_crs=False) -> dict:
2785 """Convert this shape to a GeoJSON geometry dict.
2787 Args:
2788 keep_crs: Keep the CRS of this shape, otherwise transform the coordinates to WGS84.
2790 Returns:
2791 A GeoJSON geometry dict.
2792 """
2794 def to_precision(self, prec: int) -> 'Shape':
2795 """Create a copy of this shape with coordinates snapped to the given precision.
2797 Args:
2798 prec: Number of decimal places.
2800 Returns:
2801 A new shape.
2802 """
2804 def to_props(self) -> ShapeProps:
2805 """Convert this shape to props, with the EPSG code and a GeoJSON geometry in the CRS of this shape.
2807 Returns:
2808 Shape props.
2809 """
2811 # predicates (https://shapely.readthedocs.io/en/stable/manual.html#predicates-and-relationships)
2813 def is_empty(self) -> bool:
2814 """Check if this shape is empty.
2816 Returns:
2817 ``True`` if this shape is empty.
2818 """
2820 def is_ring(self) -> bool:
2821 """Check if this shape is a closed and simple line.
2823 Returns:
2824 ``True`` if this shape is a ring.
2825 """
2827 def is_simple(self) -> bool:
2828 """Check if this shape is simple, that is, has no self-intersections.
2830 Returns:
2831 ``True`` if this shape is simple.
2832 """
2834 def is_valid(self) -> bool:
2835 """Check if this shape is valid.
2837 Returns:
2838 ``True`` if this shape is valid.
2839 """
2841 def equals(self, other: 'Shape') -> bool:
2842 """Check if this shape is spatially equal to the other.
2844 The other shape is transformed to the CRS of this shape. The same applies to
2845 all binary predicates.
2847 Args:
2848 other: Another shape.
2850 Returns:
2851 ``True`` if the shapes are equal.
2852 """
2854 def contains(self, other: 'Shape') -> bool:
2855 """Check if this shape contains the other.
2857 Args:
2858 other: Another shape.
2860 Returns:
2861 ``True`` if this shape contains the other.
2862 """
2864 def covers(self, other: 'Shape') -> bool:
2865 """Check if this shape covers the other.
2867 Args:
2868 other: Another shape.
2870 Returns:
2871 ``True`` if this shape covers the other.
2872 """
2874 def covered_by(self, other: 'Shape') -> bool:
2875 """Check if this shape is covered by the other.
2877 Args:
2878 other: Another shape.
2880 Returns:
2881 ``True`` if this shape is covered by the other.
2882 """
2884 def crosses(self, other: 'Shape') -> bool:
2885 """Check if this shape crosses the other.
2887 Args:
2888 other: Another shape.
2890 Returns:
2891 ``True`` if this shape crosses the other.
2892 """
2894 def disjoint(self, other: 'Shape') -> bool:
2895 """Check if this shape does not intersect the other.
2897 Args:
2898 other: Another shape.
2900 Returns:
2901 ``True`` if the shapes have no point in common.
2902 """
2904 def intersects(self, other: 'Shape') -> bool:
2905 """Check if this shape intersects the other.
2907 Args:
2908 other: Another shape.
2910 Returns:
2911 ``True`` if the shapes have at least one point in common.
2912 """
2914 def overlaps(self, other: 'Shape') -> bool:
2915 """Check if this shape overlaps the other.
2917 Args:
2918 other: Another shape.
2920 Returns:
2921 ``True`` if this shape overlaps the other.
2922 """
2924 def touches(self, other: 'Shape') -> bool:
2925 """Check if this shape touches the other.
2927 Args:
2928 other: Another shape.
2930 Returns:
2931 ``True`` if this shape touches the other.
2932 """
2934 def within(self, other: 'Shape') -> bool:
2935 """Check if this shape is within the other.
2937 Args:
2938 other: Another shape.
2940 Returns:
2941 ``True`` if this shape is within the other.
2942 """
2944 # set operations
2946 def union(self, others: list['Shape']) -> 'Shape':
2947 """Compute the union of this shape and other shapes.
2949 Args:
2950 others: Other shapes, transformed to the CRS of this shape.
2952 Returns:
2953 A new shape, or this shape if ``others`` is empty.
2954 """
2956 def intersection(self, *others: 'Shape') -> 'Shape':
2957 """Compute the intersection of this shape and other shapes.
2959 Args:
2960 *others: Other shapes, transformed to the CRS of this shape.
2962 Returns:
2963 A new shape, or this shape if no others are given.
2964 """
2966 # convertors
2968 def to_multi(self) -> 'Shape':
2969 """Convert a single geometry shape to a multi-geometry one.
2971 Returns:
2972 A multi-geometry shape for a point, a line string or a polygon, otherwise this shape.
2973 """
2975 def to_type(self, new_type: 'GeometryType') -> 'Shape':
2976 """Convert this shape to another geometry type.
2978 Only the conversion from a single to the respective multi-geometry is supported.
2980 Args:
2981 new_type: Target geometry type. ``geometry`` and the current type return this shape.
2983 Returns:
2984 A converted shape.
2986 Raises:
2987 ``gws.Error``: If the conversion is not supported.
2988 """
2990 def to_2d(self) -> 'Shape':
2991 """Convert this shape to 2 dimensions.
2993 Returns:
2994 A 2D shape, or this shape if it is already 2D.
2995 """
2997 # misc
2999 def tolerance_polygon(self, tolerance=None, quad_segs=None) -> 'Shape':
3000 """Build a buffer polygon around this shape.
3002 Polygons without a tolerance are returned as is. Other shapes always get a
3003 buffer, with a small minimal radius if no tolerance is given. Shapes in a
3004 geographic CRS are buffered in Web Mercator.
3006 Args:
3007 tolerance: Buffer radius in CRS units, or in meters for geographic CRS.
3008 quad_segs: Number of segments per quarter circle.
3010 Returns:
3011 A polygon shape.
3012 """
3014 def transformed_to(self, crs: 'Crs') -> 'Shape':
3015 """Transform this shape to another CRS.
3017 Args:
3018 crs: Target CRS.
3020 Returns:
3021 A transformed shape, or this shape if the CRS is the same.
3022 """
3023################################################################################
3026################################################################################
3027# /lib/grid/types.pyinc
3030MapTile: TypeAlias = tuple[int, int, int]
3031"""Grid tile: ``(x, y, z)``."""
3033MapTileRange: TypeAlias = tuple[int, int, int, int, int]
3034"""Rectangle of tiles at one level: ``(min_x, min_y, max_x, max_y, z)``."""
3036class MapGrid(Data):
3037 """Fixed tile grid over a CRS, origin north-west.
3039 Level ``z`` has the resolution ``baseResolution / 2**z``. See ``gws.lib.grid``.
3040 """
3042 crs: Crs
3043 """Grid CRS."""
3044 extent: Extent
3045 """Frame extent; the origin is its north-west corner."""
3046 baseResolution: float
3047 """Resolution at level 0, in CRS units per pixel."""
3048 tileSize: int
3049 """Tile width and height in pixels."""
3052class TileMatrix(Data):
3053 """Tile matrix, one level of a tile matrix set, as in WMTS."""
3055 identifier: str
3056 """Matrix identifier."""
3057 scale: float
3058 """Scale denominator."""
3059 resolution: float
3060 """Resolution in CRS units per pixel."""
3061 x: float
3062 """X coordinate of the top left corner."""
3063 y: float
3064 """Y coordinate of the top left corner."""
3065 width: float
3066 """Matrix width in tiles."""
3067 height: float
3068 """Matrix height in tiles."""
3069 tileWidth: float
3070 """Tile width in pixels."""
3071 tileHeight: float
3072 """Tile height in pixels."""
3073 extent: Extent
3074 """Matrix extent."""
3077class TileMatrixSet(Data):
3078 """Tile matrix set, a pyramid of tile matrices, as in WMTS."""
3080 identifier: str
3081 """Matrix set identifier."""
3082 crs: 'Crs'
3083 """CRS of the matrices."""
3084 matrices: list[TileMatrix]
3085 """Matrices of the set."""
3086################################################################################
3089################################################################################
3090# /gis/cache/types.pyinc
3093class MapCache(Data):
3094 """Tile cache settings of a grabber."""
3096 name: str
3097 """Cache name, also the name of the cache directory."""
3098 maxAge: int
3099 """Max. age of cached tiles in seconds, 0 disables storing."""
3100 maxLevel: int
3101 """Finest zoom level to store."""
3102 requestBuffer: int
3103 """Pixel buffer around source requests."""
3104 requestTiles: int
3105 """Tiles per side of the block rendered in one source request."""
3108class TileStoreStats(Data):
3109 """Tile store statistics."""
3111 count: int
3112 """Number of stored tiles."""
3113 size: int
3114 """Total size of stored tiles in bytes."""
3115 range: Optional[MapTileRange]
3116 """Bounding tile range of the stored tiles, only for a single level."""
3119class TileStore:
3120 """Storage for encoded map tiles of one grid.
3122 Tiles are addressed by ``(x, y, z)``. A tile counts as stored only while it is younger than ``maxAge``.
3123 """
3125 baseDir: str
3126 """Base directory of the store."""
3127 maxAge: int
3128 """Max. age of stored tiles in seconds."""
3130 def stats(self) -> TileStoreStats:
3131 """Compute statistics for the whole store.
3133 Returns:
3134 Number and size of stored tiles. The tile range is not set.
3135 """
3137 def stats_for_level(self, z: int) -> TileStoreStats:
3138 """Compute statistics for a level.
3140 Args:
3141 z: Zoom level.
3143 Returns:
3144 Number, size and bounding tile range of the stored tiles of the level.
3145 """
3147 def path(self, mt: MapTile) -> str:
3148 """Return the file path of a tile.
3150 Args:
3151 mt: Tile.
3153 Returns:
3154 The file path, whether the tile exists or not.
3155 """
3157 def has(self, mt: MapTile) -> bool:
3158 """Check if a tile is stored.
3160 Args:
3161 mt: Tile.
3163 Returns:
3164 ``True`` if the tile is stored and younger than ``maxAge``.
3165 """
3167 def read(self, mt: MapTile) -> Optional[bytes]:
3168 """Read a stored tile.
3170 Args:
3171 mt: Tile.
3173 Returns:
3174 The tile content, or ``None`` if the tile is missing, stale or unreadable.
3175 """
3177 def write(self, mt: MapTile, blob: bytes):
3178 """Store a tile.
3180 Args:
3181 mt: Tile.
3182 blob: Encoded tile content.
3183 """
3185 def drop(self):
3186 """Remove the whole store."""
3188 def drop_level(self, z: int):
3189 """Remove all tiles of a level.
3191 Args:
3192 z: Zoom level.
3193 """
3195 def drop_range(self, mtr: MapTileRange):
3196 """Remove the tiles of a range.
3198 Args:
3199 mtr: Tile range.
3200 """
3201################################################################################
3204################################################################################
3205# /gis/render/types.pyinc
3208class MapView(Data):
3209 """Geometry of a rendered map."""
3211 bounds: Bounds
3212 """Bounds of the map, not rotated."""
3213 center: Point
3214 """Center point."""
3215 rotation: int
3216 """Rotation angle in degrees."""
3217 scale: int
3218 """Scale denominator."""
3219 mmSize: Size
3220 """Map size in mm."""
3221 pxSize: Size
3222 """Map size in pixels."""
3223 dpi: int
3224 """Resolution in dots per inch."""
3227class MapRenderInputPlaneType(Enum):
3228 """Type of a map render input plane."""
3230 features = 'features'
3231 """A list of features, rendered as SVG."""
3232 image = 'image'
3233 """A raster image."""
3234 imageLayer = 'imageLayer'
3235 """A layer, rendered as an image."""
3236 svgLayer = 'svgLayer'
3237 """A layer, rendered as SVG."""
3238 svgSoup = 'svgSoup'
3239 """An SVG soup, a resolution-independent drawing, see ``gws.lib.svg.soup_to_fragment``."""
3242class MapRenderInputPlane(Data):
3243 """A plane of a map to render."""
3245 type: MapRenderInputPlaneType
3246 """Plane type."""
3247 features: list['Feature']
3248 """Features, for the ``features`` type."""
3249 image: 'Image'
3250 """Image, for the ``image`` type."""
3251 layer: 'Layer'
3252 """Layer, for the ``imageLayer`` and ``svgLayer`` types."""
3253 opacity: float
3254 """Opacity from 0 to 1, defaults to the layer opacity or 1."""
3255 soupPoints: list[Point]
3256 """Points in map coordinates, for the ``svgSoup`` type."""
3257 soupTags: list[Any]
3258 """Tags that refer to the points, for the ``svgSoup`` type."""
3259 styles: list['Style']
3260 """Styles. For ``features``, matched by CSS selector; for ``svgLayer``, the first style is used."""
3261 compositeLayerUids: list[str]
3262 """Child layers to render in one composite image, for the ``imageLayer`` type."""
3265class MapRenderInput(Data):
3266 """Input of the map renderer."""
3268 backgroundColor: int
3269 """Background color of the first raster plane."""
3270 bbox: Extent
3271 """Bounding box of the map. If not set, ``center`` and ``scale`` are used."""
3272 center: Point
3273 """Center point of the map."""
3274 targetCrs: 'Crs'
3275 """CRS of the map."""
3276 dpi: int
3277 """Resolution of raster planes, for maps sized in mm."""
3278 mapSize: UomSize
3279 """Map size in mm or pixels."""
3280 notify: Callable
3281 """Callback, called with an event name and the plane before and after each plane is rendered."""
3282 planes: list['MapRenderInputPlane']
3283 """Planes to render, top to bottom."""
3284 project: 'Project'
3285 """Project of the map."""
3286 rotation: int
3287 """Rotation angle in degrees."""
3288 scale: int
3289 """Scale denominator, used with ``center``."""
3290 user: 'User'
3291 """User who requests the map."""
3292 visibleLayers: Optional[list['Layer']]
3293 """Visible layers of the map."""
3296class MapRenderOutputPlaneType(Enum):
3297 """Type of a map render output plane."""
3299 image = 'image'
3300 """A raster image."""
3301 path = 'path'
3302 """A path to an image file."""
3303 svg = 'svg'
3304 """A list of SVG elements."""
3307class MapRenderOutputPlane(Data):
3308 """A plane of a rendered map."""
3310 type: MapRenderOutputPlaneType
3311 """Plane type."""
3312 path: str
3313 """Image file path, for the ``path`` type."""
3314 elements: list[XmlElement]
3315 """SVG elements, for the ``svg`` type."""
3316 image: 'Image'
3317 """Image, for the ``image`` type."""
3320class MapRenderOutput(Data):
3321 """Output of the map renderer."""
3323 planes: list['MapRenderOutputPlane']
3324 """Rendered planes, bottom to top."""
3325 view: MapView
3326 """Map view of the vector planes."""
3329class LayerRenderInputType(Enum):
3330 """Type of a layer render request."""
3332 box = 'box'
3333 """Render an image of the view extent."""
3334 tile = 'tile'
3335 """Render a tile of the layer grid."""
3336 svg = 'svg'
3337 """Render SVG elements for the view."""
3340class LayerRenderInput(Data):
3341 """Input of a layer render request."""
3343 extraParams: dict
3344 """Additional request parameters, e.g. ``compositeLayerUids``."""
3345 renderParams: dict
3346 """Parameters set by the layer for its grabber. Non-empty params mark a dynamic, uncached request."""
3347 project: 'Project'
3348 """Project of the request."""
3349 style: 'Style'
3350 """Style for the ``svg`` type."""
3351 targetCrs: 'Crs'
3352 """CRS of the output."""
3353 type: LayerRenderInputType
3354 """Request type."""
3355 user: 'User'
3356 """User who requests the rendering."""
3357 view: MapView
3358 """Map view, for the ``box`` and ``svg`` types."""
3359 x: int
3360 """Tile column, for the ``tile`` type."""
3361 y: int
3362 """Tile row, for the ``tile`` type."""
3363 z: int
3364 """Zoom level, for the ``tile`` type."""
3367class LayerRenderOutput(Data):
3368 """Output of a layer render request."""
3370 content: bytes
3371 """Encoded image, for the ``box`` and ``tile`` types."""
3372 tags: list[XmlElement]
3373 """SVG elements, for the ``svg`` type."""
3374################################################################################
3377################################################################################
3378# /gis/source/types.pyinc
3381class SourceStyle(Data):
3382 """A style of a source layer, as listed in the capabilities of a service."""
3384 isDefault: bool
3385 """The style is the default style of the layer."""
3386 legendUrl: Url
3387 """URL of the legend image."""
3388 metadata: 'Metadata'
3389 """Style metadata."""
3390 name: str
3391 """Style name."""
3394class SourceLayer(Data):
3395 """A layer of an external source, such as a WMS, WFS or WMTS service or a QGIS project.
3397 Source layers are read from capabilities and form a tree. The ``a*`` properties
3398 are set by ``gws.gis.source.check_layers``.
3399 """
3401 aLevel: int
3402 """Depth in the layer tree, 1 for top-level layers."""
3403 aPath: str
3404 """Path of uids from the top of the tree, e.g. ``/root/roads``."""
3405 aUid: str
3406 """Uid derived from the name or title."""
3408 dataSource: dict
3409 """Parsed data source of a QGIS layer."""
3410 metadata: 'Metadata'
3411 """Layer metadata."""
3413 supportedCrs: list['Crs']
3414 """CRS supported by the source for this layer."""
3415 wgsExtent: Extent
3416 """Layer extent in WGS84."""
3418 isExpanded: bool
3419 """The layer is expanded in the source layer tree."""
3420 isGroup: bool
3421 """The layer is a group."""
3422 isImage: bool
3423 """The layer can be rendered as an image."""
3424 isQueryable: bool
3425 """The layer can be queried for features."""
3426 isReadOnly: bool
3427 """The layer has the readOnly flag set."""
3428 isVisible: bool
3429 """The layer is visible by default."""
3431 layers: list['SourceLayer']
3432 """Sub-layers."""
3434 name: str
3435 """Layer name, used in requests to the source."""
3436 title: str
3437 """Layer title."""
3439 legendUrl: Url
3440 """URL of the legend image."""
3441 opacity: float
3442 """Layer opacity from 0 to 1."""
3443 scaleRange: list[float]
3444 """Min. and max. scale denominators at which the layer is visible."""
3446 styles: list[SourceStyle]
3447 """Available styles."""
3448 defaultStyle: Optional[SourceStyle]
3449 """Default style."""
3451 tileMatrixIds: list[str]
3452 """Ids of the WMTS tile matrix sets the layer links to."""
3453 tileMatrixSets: list[TileMatrixSet]
3454 """WMTS tile matrix sets of the layer."""
3455 imageFormat: str
3456 """Image format for WMTS requests."""
3457 resourceUrls: dict
3458 """WMTS resource URL templates, keyed by resource type."""
3460 sourceId: str
3461 """Id of the layer in the source, e.g. the QGIS layer id."""
3462 properties: dict
3463 """Custom properties of a QGIS layer."""
3464################################################################################
3468################################################################################
3469# /config/types.pyinc
3472class ConfigLocation(Data):
3473 """Location in the configuration tree."""
3475 objectUid: str
3476 """UID of the object."""
3477 objectType: str
3478 """Type of the object."""
3479 objectName: str
3480 """Name of the object."""
3481 propName: str
3482 """Property of the parent this object is located at."""
3485class ConfigErrorInfo(Data):
3486 """Full information about a configuration error."""
3488 message: str
3489 """Error message."""
3490 path: str
3491 """Path to the configuration file."""
3492 line: int
3493 """Line number where the error occurred."""
3494 value: str
3495 """Value that caused the error."""
3496 stack: list[ConfigLocation]
3497 """Locations of the objects being configured when the error occurred, innermost first."""
3498 contextLines: list[str]
3499 """Source lines around the error, with line numbers, the error line is marked with ``>>>``."""
3500 cause: str
3501 """Representation of the exception that caused the error."""
3504class ConfigContext(Data):
3505 """Shared state for parsing and validating a configuration."""
3507 specs: SpecRuntime
3508 """Specs used to validate the configuration."""
3509 readOptions: set[SpecReadOption]
3510 """Options passed to the spec reader."""
3511 errors: list[ConfigErrorInfo]
3512 """Errors collected so far."""
3513 warnings: list[ConfigErrorInfo]
3514 """Warnings collected so far."""
3515 paths: set[str]
3516 """Paths of all configuration files that were read, including included files."""
3520class ConfigResult(Data):
3521 """Result of a configuration run."""
3523 root: Optional['Root']
3524 """Configured root object, or ``None`` if configuration failed or was not requested."""
3525 config: Optional['Config']
3526 """Parsed application configuration."""
3527 errors: list[ConfigErrorInfo]
3528 """Configuration errors."""
3529 warnings: list[ConfigErrorInfo]
3530 """Configuration warnings."""
3531 info: str
3532 """Summary with the number of objects, time and memory used."""
3533################################################################################
3536################################################################################
3537# /server/types.pyinc
3540class ServerManager(Node):
3541 """Server configuration manager.
3543 Holds the ``server`` configuration and creates the configuration files for
3544 the embedded servers and the server start script.
3545 """
3547 templates: list['Template']
3548 """Templates for the server configuration files and the start script."""
3550 def create_server_configs(self, target_dir: str, script_path: str, pid_paths: dict):
3551 """Create the server configuration files and the start script.
3553 Args:
3554 target_dir: Directory for the configuration files.
3555 script_path: Path of the start script.
3556 pid_paths: Paths of the pid files, keyed by server name (``web``, ``spool``, ``nginx``).
3557 """
3560class ServerMonitor(Node):
3561 """Server monitor.
3563 Watches configuration files and directories and reconfigures the server
3564 when they change, and runs periodic tasks of registered objects.
3565 """
3567 def watch_directory(self, path: str, pattern: 'Regex', recursive=False):
3568 """Add a directory to watch.
3570 Args:
3571 path: Directory path.
3572 pattern: Regex pattern for file names to watch.
3573 recursive: Also watch subdirectories.
3574 """
3576 def watch_file(self, path: str):
3577 """Add a file to watch.
3579 Args:
3580 path: File path.
3581 """
3583 def register_periodic_task(self, obj: Node, frequency: int = 0):
3584 """Register an object as a periodic task handler.
3586 Args:
3587 obj: A node with a ``periodic_task`` method.
3588 frequency: Interval between runs in seconds, the monitor default if 0.
3590 Raises:
3591 ``gws.Error``: If the object has no ``periodic_task`` method.
3592 """
3594 def schedule_reload(self, with_reconfigure: bool = False):
3595 """Schedule a reload of the web and spool backends.
3597 The reload is performed by the monitor on its next tick.
3599 Args:
3600 with_reconfigure: Reconfigure the server before reloading.
3601 """
3603 def start(self):
3604 """Start watching files and register the timer that drives the monitor.
3606 Must be called in a uWSGI process.
3607 """
3608################################################################################
3612################################################################################
3613# /base/metadata/types.pyinc
3616class MetadataLink(Data):
3617 """Link to a metadata document or another resource related to an object."""
3619 about: str
3620 """Aspect of the object the link describes."""
3621 description: str
3622 """Description of the linked resource."""
3623 format: str
3624 """Format of the linked resource."""
3625 formatVersion: str
3626 """Version of the format of the linked resource."""
3627 function: str
3628 """Function of the link."""
3629 mimeType: str
3630 """MIME type of the linked resource."""
3631 scheme: str
3632 """Link scheme or protocol."""
3633 title: str
3634 """Link title."""
3635 type: str
3636 """Link type."""
3637 url: str
3638 """Link URL."""
3641class Metadata(Data):
3642 """Metadata of an object, used in the client, in OWS services and in catalog records."""
3644 name: str
3645 """Object name."""
3646 title: str
3647 """Object title."""
3649 abstract: str
3650 """Abstract, a brief description of the object."""
3651 accessConstraints: str
3652 """Access constraints."""
3653 accessConstraintsType: str
3654 """Type of the access constraints."""
3655 attribution: str
3656 """Attribution text."""
3657 attributionUrl: str
3658 """URL of the attribution."""
3659 dateCreated: Optional['datetime.datetime']
3660 """Creation date."""
3661 dateUpdated: Optional['datetime.datetime']
3662 """Last update date."""
3663 fees: str
3664 """Fees for using the object."""
3665 image: str
3666 """Image URL or path associated with the object."""
3667 keywords: list[str]
3668 """Keywords, optionally prefixed with a vocabulary, e.g. ``gemet:river``."""
3669 license: str
3670 """License text."""
3671 licenseUrl: str
3672 """License URL."""
3674 contactAddress: str
3675 """Street address of the contact."""
3676 contactAddressType: str
3677 """Type of the contact address."""
3678 contactArea: str
3679 """Administrative area, state or province of the contact address."""
3680 contactCity: str
3681 """Contact city."""
3682 contactCountry: str
3683 """Contact country."""
3684 contactEmail: str
3685 """Contact email address."""
3686 contactFax: str
3687 """Contact fax number."""
3688 contactOrganization: str
3689 """Contact organization."""
3690 contactPerson: str
3691 """Contact person name."""
3692 contactPhone: str
3693 """Contact phone number."""
3694 contactPosition: str
3695 """Contact position or job title."""
3696 contactProviderName: str
3697 """Name of the service provider."""
3698 contactProviderSite: str
3699 """Website of the service provider."""
3700 contactRole: str
3701 """Role of the contact, an ISO ``CI_RoleCode`` value."""
3702 contactUrl: str
3703 """Website of the contact."""
3704 contactZip: str
3705 """Contact postal code."""
3707 authorityIdentifier: str
3708 """Identifier issued by the authority."""
3709 authorityName: str
3710 """Name of the authority that issues identifiers."""
3711 authorityUrl: str
3712 """URL of the authority that issues identifiers."""
3714 metaLinks: list[MetadataLink]
3715 """Links to metadata documents."""
3716 serviceMetadataURL: str
3717 """URL of the service metadata document."""
3719 catalogCitationUid: str
3720 """Identifier of the resource in catalog records."""
3721 catalogUid: str
3722 """Identifier of the metadata record."""
3724 language: str
3725 """Language as an ISO 639-1 code."""
3726 language3: str
3727 """Language as an ISO 639-2 three-letter code, derived from ``language``."""
3728 languageBib: str
3729 """Language as an ISO 639-2 bibliographic code, derived from ``language``."""
3730 languageName: str
3731 """Name of the language."""
3733 parentIdentifier: str
3734 """Identifier of the parent metadata record."""
3735 wgsExtent: Optional[Extent]
3736 """Geographic extent in WGS84."""
3737 crs: Optional['Crs']
3738 """Reference system of the data."""
3739 temporalBegin: Optional['datetime.datetime']
3740 """Start of the temporal extent."""
3741 temporalEnd: Optional['datetime.datetime']
3742 """End of the temporal extent."""
3744 inspireMandatoryKeyword: str
3745 """INSPIRE mandatory keyword (service type)."""
3746 inspireDegreeOfConformity: str
3747 """Degree of conformity with the INSPIRE implementing rules."""
3748 inspireResourceType: str
3749 """INSPIRE resource type."""
3750 inspireSpatialDataServiceType: str
3751 """INSPIRE spatial data service type."""
3752 inspireSpatialScope: str
3753 """INSPIRE spatial scope."""
3754 inspireSpatialScopeName: str
3755 """Display name of the INSPIRE spatial scope."""
3756 inspireTheme: str
3757 """INSPIRE data theme code."""
3759 inspireThemeNameLocal: str
3760 """Name of the INSPIRE theme in the metadata language, derived from ``inspireTheme``."""
3761 inspireThemeNameEn: str
3762 """English name of the INSPIRE theme, derived from ``inspireTheme``."""
3764 isoMaintenanceFrequencyCode: str
3765 """How often the data is updated."""
3766 isoQualityConformanceExplanation: str
3767 """Explanation of the conformance result."""
3768 isoQualityConformanceQualityPass: bool
3769 """The data passes the conformance test."""
3770 isoQualityConformanceSpecificationDate: str
3771 """Publication date of the conformance specification."""
3772 isoQualityConformanceSpecificationTitle: str
3773 """Title of the conformance specification."""
3774 isoQualityLineageSource: str
3775 """Description of the source data."""
3776 isoQualityLineageSourceScale: int
3777 """Scale denominator of the source data."""
3778 isoQualityLineageStatement: str
3779 """Statement on the lineage of the data."""
3780 isoRestrictionCode: str
3781 """Restrictions on access or use of the data."""
3782 isoServiceFunction: str
3783 """ISO service function."""
3784 isoScope: str
3785 """Scope of the metadata."""
3786 isoScopeName: str
3787 """Name of the scope."""
3788 isoSpatialRepresentationType: str
3789 """How the data is represented spatially."""
3790 isoTopicCategories: list[str]
3791 """ISO 19115 topic categories."""
3792 isoSpatialResolution: int
3793 """Spatial resolution as a scale denominator."""
3794################################################################################
3797################################################################################
3798# /base/feature/types.pyinc
3801FeatureUid: TypeAlias = str
3802"""Unique Feature id."""
3804class FeatureRecord(Data):
3805 """Raw data from a feature source."""
3807 attributes: dict
3808 """Attribute values as read from the source or as written to it."""
3809 meta: dict
3810 """Extra source information, e.g. ``layerName`` for features from OWS responses."""
3811 uid: Optional[str]
3812 """Feature id provided by the source."""
3813 shape: Optional['Shape']
3814 """Geometry provided by the source."""
3815 ewkt: str
3816 """Geometry as EWKT, provided by some sources."""
3819class FeatureProps(Props):
3820 """Feature Proprieties."""
3822 attributes: dict
3823 category: Optional[str]
3824 cssSelector: str
3825 errors: Optional[list['ModelValidationError']]
3826 createWithFeatures: Optional[list['FeatureProps']]
3827 isNew: bool
3828 modelUid: str
3829 uid: str
3830 views: dict
3833class Feature:
3834 """Feature object.
3836 A set of named attributes that belongs to a model. The model defines the
3837 uid attribute (``uidName``) and the geometry attribute (``geometryName``).
3838 """
3840 attributes: dict
3841 """Attribute values as python values."""
3842 category: str
3843 """Category for grouping features in the client, e.g. the source layer name."""
3844 cssSelector: str
3845 """CSS selector for the feature style in the client."""
3846 errors: list['ModelValidationError']
3847 """Validation errors."""
3848 isNew: bool
3849 """The feature is new and not yet saved."""
3850 model: 'Model'
3851 """Model the feature belongs to."""
3852 props: 'FeatureProps'
3853 """Data from or for the client."""
3854 record: 'FeatureRecord'
3855 """Raw data from or for the source."""
3856 views: dict
3857 """Rendered views, keyed by view name, e.g. ``title`` or ``label``."""
3858 createWithFeatures: list['Feature']
3859 """Related features a new feature is created with."""
3860 insertedPrimaryKey: Optional[int | str]
3861 """Primary key of the row inserted when the feature was created."""
3863 def get(self, name: str, default=None) -> Any:
3864 """Get an attribute value.
3866 Args:
3867 name: Attribute name.
3868 default: Value to return if the attribute does not exist.
3870 Returns:
3871 The attribute value, or ``default``.
3872 """
3874 def has(self, name: str) -> bool:
3875 """Check if an attribute exists.
3877 Args:
3878 name: Attribute name.
3880 Returns:
3881 ``True`` if the attribute exists.
3882 """
3884 def set(self, name: str, value: Any) -> 'Feature':
3885 """Set an attribute value.
3887 Args:
3888 name: Attribute name.
3889 value: Attribute value.
3891 Returns:
3892 The feature itself.
3893 """
3895 def raw(self, name: str) -> Any:
3896 """Get a raw attribute value from the record.
3898 Args:
3899 name: Attribute name.
3901 Returns:
3902 The value, or ``None`` if the record has no such attribute.
3903 """
3905 def render_views(self, templates: list['Template'], **kwargs) -> 'Feature':
3906 """Render feature views and store them in ``views``.
3908 Each template renders the view named after the last part of its subject,
3909 e.g. ``feature.title`` renders ``title``. The templates receive the
3910 feature attributes, ``feature`` and the extra arguments.
3912 Args:
3913 templates: Feature templates.
3914 **kwargs: Extra template arguments.
3916 Returns:
3917 The feature itself.
3918 """
3920 def shape(self) -> Optional['Shape']:
3921 """Get the feature geometry.
3923 Returns:
3924 The geometry, or ``None`` if the model has no geometry or the feature has no value.
3925 """
3927 def to_svg(self, view: 'MapView', label: Optional[str] = None, style: Optional['Style'] = None) -> list[XmlElement]:
3928 """Render the feature geometry as SVG fragments for a map view.
3930 Args:
3931 view: Map view. The geometry is transformed to its CRS.
3932 label: Label text.
3933 style: Style.
3935 Returns:
3936 A list of SVG elements, empty if the feature has no geometry.
3937 """
3939 def to_geojson(self, keep_crs=False) -> dict:
3940 """Convert the feature to a GeoJSON feature.
3942 The geometry is converted to WGS84 unless ``keep_crs`` is set. The uid
3943 is added as the ``id`` property.
3945 Args:
3946 keep_crs: Keep the geometry coordinates in the feature CRS.
3948 Returns:
3949 A GeoJSON feature dict.
3950 """
3952 def transform_to(self, crs: 'Crs') -> 'Feature':
3953 """Transform the feature geometry to another CRS, in place.
3955 Args:
3956 crs: Target CRS.
3958 Returns:
3959 The feature itself.
3960 """
3962 def uid(self) -> FeatureUid:
3963 """Get the unique id of the feature.
3965 Returns:
3966 The value of the uid attribute as a string, an empty string if the model
3967 has no uid attribute, or ``None`` if the feature has no value.
3968 """
3969################################################################################
3973################################################################################
3974# /base/action/types.pyinc
3977class ActionManager(Node):
3978 """Action manager.
3980 Locates actions in projects and the application and prepares command calls.
3981 """
3983 def actions_for_project(self, project: 'Project', user: 'User') -> list['Action']:
3984 """Get the actions a user can use in a project.
3986 Includes the project actions and the application actions, one action per type.
3987 A project action takes precedence over an application action of the same type.
3989 Args:
3990 project: The project.
3991 user: The user.
3993 Returns:
3994 A list of actions.
3995 """
3997 def find_action(self, project: Optional['Project'], ext_type: str, user: 'User') -> Optional['Action']:
3998 """Find an action by its type.
4000 Searches the project actions first, if a project is given, then the application actions.
4002 Args:
4003 project: The project, or ``None`` to search the application actions only.
4004 ext_type: Action type, for example ``map``.
4005 user: The user who wants to use the action.
4007 Returns:
4008 The action object, or ``None`` if not found.
4010 Raises:
4011 ForbiddenError: If the action is found but the user may not use it.
4012 """
4014 def prepare_action(
4015 self,
4016 command_category: CommandCategory,
4017 command_name: str,
4018 params: dict,
4019 path: str,
4020 user: 'User',
4021 read_options: Optional[set[SpecReadOption]]=None,
4022 ) -> tuple[Callable, Request]:
4023 """Prepare a command call.
4025 Parses the parameters into the command's request type, finds the action
4026 that owns the command (in the requested project, then in the application)
4027 and checks the user's access.
4029 Args:
4030 command_category: Command category.
4031 command_name: Command name, for example ``mapDescribeLayer``.
4032 params: Raw request parameters.
4033 path: Request path; for ``raw`` commands, the project uid can be given as a ``/projectUid/<uid>`` segment.
4034 user: The user who runs the command.
4035 read_options: Options for the spec reader.
4037 Returns:
4038 A tuple of the bound command method and the parsed request object.
4040 Raises:
4041 NotFoundError: If the command, the project or the action is not found.
4042 BadRequestError: If the parameters cannot be parsed.
4043 ForbiddenError: If the user may not use the project or the action.
4044 """
4047class Action(Node):
4048 """Server action.
4050 An action is a configurable object that provides server commands.
4051 """
4052################################################################################
4055################################################################################
4056# /base/auth/types.pyinc
4059class User(Object):
4060 """User.
4062 A user has a set of roles, which are checked against the permissions of
4063 objects to decide access.
4064 """
4066 isGuest: bool
4067 """The user is the guest user."""
4069 authProvider: 'AuthProvider'
4070 """The provider that created the user."""
4072 attributes: dict
4073 """Public user attributes, sent to the client."""
4074 data: dict
4075 """Private user data from the provider."""
4076 roles: set[str]
4077 """User roles."""
4078 uid: str
4079 """Global user uid, made of the provider uid and the local uid."""
4081 authToken: str
4082 """Token for the ``token`` authentication method."""
4083 displayName: str
4084 """User display name."""
4085 email: str
4086 """User email."""
4087 localUid: str
4088 """User uid within its provider."""
4089 loginName: str
4090 """User login name."""
4091 mfaUid: str
4092 """Uid of the multi-factor adapter for this user, empty if none."""
4093 mfaSecret: str
4094 """Secret for the multi-factor adapter."""
4096 def acl_bit(self, access: Access, obj: Object) -> Optional[int]:
4097 """Get the access decision for an object itself, without parents.
4099 Args:
4100 access: Access mode.
4101 obj: The object.
4103 Returns:
4104 ``gws.c.ALLOW`` or ``gws.c.DENY`` if the object's permissions decide
4105 for one of the user's roles, ``None`` otherwise.
4106 """
4108 def can(self, access: Access, obj: Object, *context) -> bool:
4109 """Check if the user can access an object.
4111 If the object's permissions do not decide, the context objects are
4112 checked in turn, then the parents of the last checked object.
4114 Args:
4115 access: Access mode.
4116 obj: The object.
4117 *context: Further objects to check, before the parents.
4119 Returns:
4120 ``True`` if access is granted.
4121 """
4123 def can_create(self, obj: Object, *context) -> bool:
4124 """Check if the user has the ``create`` permission on an object.
4126 Args:
4127 obj: The object.
4128 *context: Further objects to check, before the parents.
4130 Returns:
4131 ``True`` if access is granted.
4132 """
4134 def can_delete(self, obj: Object, *context) -> bool:
4135 """Check if the user has the ``delete`` permission on an object.
4137 Args:
4138 obj: The object.
4139 *context: Further objects to check, before the parents.
4141 Returns:
4142 ``True`` if access is granted.
4143 """
4145 def can_read(self, obj: Object, *context) -> bool:
4146 """Check if the user has the ``read`` permission on an object.
4148 Args:
4149 obj: The object.
4150 *context: Further objects to check, before the parents.
4152 Returns:
4153 ``True`` if access is granted.
4154 """
4156 def can_use(self, obj: Object, *context) -> bool:
4157 """Check if the user can use an object, which requires the ``read`` permission.
4159 Args:
4160 obj: The object.
4161 *context: Further objects to check, before the parents.
4163 Returns:
4164 ``True`` if access is granted.
4165 """
4167 def can_write(self, obj: Object, *context) -> bool:
4168 """Check if the user has the ``write`` permission on an object.
4170 Args:
4171 obj: The object.
4172 *context: Further objects to check, before the parents.
4174 Returns:
4175 ``True`` if access is granted.
4176 """
4178 def can_edit(self, obj: Object, *context) -> bool:
4179 """Check if the user has any of the ``write``, ``create`` or ``delete`` permissions on an object.
4181 Args:
4182 obj: The object.
4183 *context: Further objects to check, before the parents.
4185 Returns:
4186 ``True`` if access is granted.
4187 """
4189 def has_role(self, role: str) -> bool:
4190 """Check if the user has a role.
4192 Args:
4193 role: Role name.
4195 Returns:
4196 ``True`` if the user has the role.
4197 """
4199 def acquire(self, uid: str = None, classref: Optional[ClassRef] = None, access: Optional[Access] = None) -> Optional[Object]:
4200 """Get an object by uid, if the user can access it.
4202 Args:
4203 uid: Object uid.
4204 classref: Class reference. If provided, the object must match it.
4205 access: Access mode, ``Access.read`` if omitted.
4207 Returns:
4208 The object, or ``None`` if it does not exist or the user may not access it.
4209 """
4211 def require(self, uid: str = None, classref: Optional[ClassRef] = None, access: Optional[Access] = None) -> Object:
4212 """Get an object by uid and fail if it is not found or not accessible.
4214 Args:
4215 uid: Object uid.
4216 classref: Class reference. If provided, the object must match it.
4217 access: Access mode, ``Access.read`` if omitted.
4219 Returns:
4220 The object.
4222 Raises:
4223 NotFoundError: If the object does not exist.
4224 ForbiddenError: If the user may not access the object.
4225 """
4227 def require_project(self, uid: str = None) -> 'Project':
4228 """Get a project the user can read.
4230 Args:
4231 uid: Project uid.
4233 Returns:
4234 The project.
4236 Raises:
4237 NotFoundError: If the project does not exist.
4238 ForbiddenError: If the user may not read the project.
4239 """
4241 def require_layer(self, uid=None) -> 'Layer':
4242 """Get a layer the user can read.
4244 Args:
4245 uid: Layer uid.
4247 Returns:
4248 The layer.
4250 Raises:
4251 NotFoundError: If the layer does not exist.
4252 ForbiddenError: If the user may not read the layer.
4253 """
4256class AuthManager(Node):
4257 """Authorization manager.
4259 Holds the authentication methods, providers, multi-factor adapters and the
4260 session manager, authenticates users and opens a session for every web request.
4261 """
4263 guestSession: 'AuthSession'
4264 """Session of the guest user, used for requests without a session."""
4266 guestUser: 'User'
4267 """The guest user."""
4268 systemUser: 'User'
4269 """The system user, allowed everything."""
4271 providers: list['AuthProvider']
4272 """Authentication providers."""
4273 methods: list['AuthMethod']
4274 """Authentication methods."""
4275 mfAdapters: list['AuthMultiFactorAdapter']
4276 """Multi-factor adapters."""
4278 sessionMgr: 'AuthSessionManager'
4279 """Session manager."""
4281 def authenticate(self, method: 'AuthMethod', credentials: Data, req: 'WebRequester') -> Optional['User']:
4282 """Authenticate a user with the providers that allow the method.
4284 Args:
4285 method: The authentication method.
4286 credentials: The credentials, for example ``username`` and ``password``.
4287 req: The web request.
4289 Returns:
4290 The user, or ``None`` if no provider accepts the credentials.
4292 Raises:
4293 ForbiddenError: If a provider rejects the credentials.
4294 TooManyRequestsError: If the attempt is blocked by the throttle.
4295 """
4297 def create_transient_session(self, method: 'AuthMethod', user: 'User', data: Optional[dict] = None) -> 'AuthSession':
4298 """Create a session that lives only for the duration of the request.
4300 The session is not stored in the session manager.
4302 Args:
4303 method: The method that creates the session.
4304 user: The session user.
4305 data: Session data.
4307 Returns:
4308 A new session.
4309 """
4311 def get_user(self, user_uid: str) -> Optional['User']:
4312 """Get a user by its global uid.
4314 Args:
4315 user_uid: Global user uid.
4317 Returns:
4318 The user, or ``None`` if the provider is not found or does not return the user.
4319 """
4321 def add_provider(self, provider: 'AuthProvider'):
4322 """Add an authentication provider.
4324 Args:
4325 provider: The provider.
4326 """
4328 def add_method(self, method: 'AuthMethod'):
4329 """Add an authentication method.
4331 Args:
4332 method: The method.
4333 """
4335 def add_multi_factor_adapter(self, adapter: 'AuthMultiFactorAdapter'):
4336 """Add a multi-factor adapter.
4338 Args:
4339 adapter: The adapter.
4340 """
4342 def can_use_method(self, req: 'WebRequester', method: 'AuthMethod') -> bool:
4343 """Check if a method may be used for a request.
4345 A secure method can only be used on secure requests, or from the addresses
4346 listed in its ``allowInsecureFrom``.
4348 Args:
4349 req: The web request.
4350 method: The method.
4352 Returns:
4353 ``True`` if the method may be used.
4354 """
4356 def get_provider(self, uid: str) -> Optional['AuthProvider']:
4357 """Get an authentication provider by its uid.
4359 Args:
4360 uid: Provider uid.
4362 Returns:
4363 The provider, or ``None`` if not found.
4364 """
4366 def get_method(self, uid: str) -> Optional['AuthMethod']:
4367 """Get an authentication method by its uid.
4369 Args:
4370 uid: Method uid.
4372 Returns:
4373 The method, or ``None`` if not found.
4374 """
4376 def get_multi_factor_adapter(self, uid: str) -> Optional['AuthMultiFactorAdapter']:
4377 """Get a multi-factor adapter by its uid.
4379 Args:
4380 uid: Adapter uid.
4382 Returns:
4383 The adapter, or ``None`` if not found.
4384 """
4386 def serialize_user(self, user: 'User') -> str:
4387 """Serialize a user to a string, together with its provider uid.
4389 Args:
4390 user: The user.
4392 Returns:
4393 A JSON string.
4394 """
4396 def unserialize_user(self, ser: str) -> Optional['User']:
4397 """Restore a user serialized by ``serialize_user``.
4399 Args:
4400 ser: The serialized user.
4402 Returns:
4403 The user, or ``None`` if the provider is not found.
4404 """
4406 def is_public_object(self, obj: Object, *context) -> bool:
4407 """Check if the guest user can read an object.
4409 Args:
4410 obj: The object.
4411 *context: Further objects to check, before the parents.
4413 Returns:
4414 ``True`` if the object is public.
4415 """
4418class AuthMethod(Node):
4419 """Authentication method.
4421 Defines how credentials and sessions are passed between the client and the
4422 server, for example as a login form and a session cookie.
4423 """
4425 secure: bool
4426 """The method may only be used on secure (HTTPS) requests."""
4428 allowInsecureFrom: list[str]
4429 """IP addresses from which the method may be used without HTTPS."""
4431 def open_session(self, req: 'WebRequester') -> Optional['AuthSession']:
4432 """Try to open a session for a request.
4434 Called at the start of every web request.
4436 Args:
4437 req: The web request.
4439 Returns:
4440 A session, or ``None`` if the request has no session for this method.
4441 """
4443 def close_session(self, req: 'WebRequester', res: 'WebResponder') -> None:
4444 """Close the session of a request.
4446 Called at the end of every web request whose session was opened by this
4447 method, for example to set or delete the session cookie.
4449 Args:
4450 req: The web request.
4451 res: The web response.
4452 """
4455class AuthMultiFactorState(Enum):
4456 """State of a multi-factor authentication transaction."""
4458 open = 'open'
4459 """The transaction is started and waits for verification."""
4460 ok = 'ok'
4461 """The verification was successful."""
4462 retry = 'retry'
4463 """The verification failed and can be retried."""
4464 failed = 'failed'
4465 """The transaction failed."""
4468class AuthMultiFactorTransaction(Data):
4469 """Multi-factor authentication transaction.
4471 Kept in the user's session from the login until the verification succeeds,
4472 fails or expires.
4473 """
4475 state: AuthMultiFactorState
4476 """Current state."""
4477 restartCount: int
4478 """Number of restarts."""
4479 verifyCount: int
4480 """Number of verification attempts."""
4481 secret: str
4482 """Secret for code generation."""
4483 startTime: int
4484 """Start time, as a Unix timestamp."""
4485 generateTime: int
4486 """Time when the code was last generated, as a Unix timestamp."""
4487 message: str
4488 """Message shown to the user."""
4489 adapter: 'AuthMultiFactorAdapter'
4490 """The adapter handling the transaction."""
4491 user: 'User'
4492 """The user who logs in."""
4495class AuthMultiFactorAdapter(Node):
4496 """Multi-factor authentication adapter.
4498 Provides the second verification step of a login, for example a code sent by
4499 email or generated by an authenticator app.
4500 """
4502 message: str
4503 """Message shown to the user during the verification step."""
4504 lifeTime: int
4505 """Time in seconds allowed to complete the verification."""
4506 maxRestarts: int
4507 """How often a transaction can be restarted."""
4508 maxVerifyAttempts: int
4509 """Number of verification attempts allowed."""
4511 def start(self, user: 'User') -> Optional[AuthMultiFactorTransaction]:
4512 """Start a transaction for a user.
4514 Args:
4515 user: The user who logs in.
4517 Returns:
4518 A new transaction, or ``None`` if the adapter cannot be used for this
4519 user, for example because a required user attribute is missing.
4520 """
4522 def verify(self, mfa: AuthMultiFactorTransaction, payload: dict) -> AuthMultiFactorTransaction:
4523 """Verify a payload submitted by the user.
4525 Args:
4526 mfa: The transaction.
4527 payload: The payload, for example ``{'code': '123456'}``.
4529 Returns:
4530 The transaction with an updated state.
4531 """
4533 def check_state(self, mfa: AuthMultiFactorTransaction) -> bool:
4534 """Check if a transaction is still valid, and mark it failed if not.
4536 Args:
4537 mfa: The transaction.
4539 Returns:
4540 ``True`` if the transaction is valid.
4541 """
4543 def check_restart(self, mfa: AuthMultiFactorTransaction) -> bool:
4544 """Check if a transaction can be restarted.
4546 Args:
4547 mfa: The transaction.
4549 Returns:
4550 ``True`` if a restart is allowed.
4551 """
4553 def restart(self, mfa: AuthMultiFactorTransaction) -> Optional[AuthMultiFactorTransaction]:
4554 """Restart a transaction, for example by sending a new code.
4556 Args:
4557 mfa: The transaction.
4559 Returns:
4560 A new transaction, or ``None`` if a restart is not possible.
4561 """
4563 def key_uri(self, secret: str | bytes, issuer_name: str, account_name: str) -> Optional[str]:
4564 """Generate a key URI for authenticator apps.
4566 Args:
4567 secret: The user's secret.
4568 issuer_name: Issuer name shown in the app.
4569 account_name: Account name shown in the app.
4571 Returns:
4572 An ``otpauth://`` URI, or ``None`` if the adapter does not support it.
4573 """
4576class AuthProvider(Node):
4577 """Authentication provider.
4579 A source of users, for example a file, an LDAP directory or a database table,
4580 which verifies credentials.
4581 """
4583 allowedMethods: list[str]
4584 """Method types this provider accepts, all methods if empty."""
4586 def get_user(self, local_uid: str) -> Optional['User']:
4587 """Get a user by its local uid.
4589 Args:
4590 local_uid: User uid within the provider.
4592 Returns:
4593 The user, or ``None`` if not found.
4594 """
4596 def authenticate(self, method: 'AuthMethod', credentials: Data) -> Optional['User']:
4597 """Authenticate a user.
4599 Args:
4600 method: The authentication method.
4601 credentials: The credentials, for example ``username`` and ``password``.
4603 Returns:
4604 The user, or ``None`` if the provider does not know the user.
4606 Raises:
4607 AuthenticationError: If the credentials are wrong or match more than one user.
4608 """
4610 def serialize_user(self, user: 'User') -> str:
4611 """Serialize a user to a string.
4613 Args:
4614 user: The user.
4616 Returns:
4617 The serialized user.
4618 """
4620 def unserialize_user(self, ser: str) -> Optional['User']:
4621 """Restore a user serialized by ``serialize_user``.
4623 Args:
4624 ser: The serialized user.
4626 Returns:
4627 The user, or ``None`` if it cannot be restored.
4628 """
4631class AuthSession:
4632 """Authentication session.
4634 Holds the user and arbitrary data between requests.
4635 """
4637 uid: str
4638 """Session uid."""
4639 method: Optional['AuthMethod']
4640 """The method that created the session, ``None`` for the guest session."""
4641 user: 'User'
4642 """The session user."""
4643 data: dict
4644 """Session data."""
4645 created: 'datetime.datetime'
4646 """Creation time."""
4647 updated: 'datetime.datetime'
4648 """Last update time."""
4649 isChanged: bool
4650 """The session data has changed since the session was loaded."""
4651 isTransient: bool
4652 """The session lives only for the duration of the request and is not stored."""
4654 def get(self, key: str, default=None):
4655 """Get a session data value.
4657 Args:
4658 key: Value name.
4659 default: Default value.
4661 Returns:
4662 The value, or the default if it is not set.
4663 """
4665 def set(self, key: str, value):
4666 """Set a session data value and mark the session as changed.
4668 Args:
4669 key: Value name.
4670 value: The value.
4671 """
4674class AuthSessionManager(Node):
4675 """Authentication session manager.
4677 Stores sessions persistently. A session is valid until ``lifeTime`` has passed
4678 since its last update, or ``maxLifeTime`` since its creation.
4679 """
4681 lifeTime: int
4682 """Session life time in seconds, counted from the last update."""
4684 maxLifeTime: int
4685 """Absolute session life time in seconds, counted from the creation, or 0 if not limited."""
4687 def create(self, method: 'AuthMethod', user: 'User', data: Optional[dict] = None) -> 'AuthSession':
4688 """Create and store a new session.
4690 Args:
4691 method: The method that creates the session.
4692 user: The session user.
4693 data: Session data.
4695 Returns:
4696 The new session.
4697 """
4699 def delete(self, sess: 'AuthSession'):
4700 """Delete a session.
4702 Args:
4703 sess: The session.
4704 """
4706 def delete_all(self):
4707 """Delete all sessions."""
4709 def get(self, uid: str) -> Optional['AuthSession']:
4710 """Get a valid session by its uid.
4712 Args:
4713 uid: Session uid.
4715 Returns:
4716 The session, or ``None`` if it does not exist or has expired.
4717 """
4719 def list_all(self) -> list['AuthSession']:
4720 """Get all stored sessions.
4722 Returns:
4723 A list of sessions.
4724 """
4726 def save(self, sess: 'AuthSession'):
4727 """Save the session data.
4729 Args:
4730 sess: The session.
4731 """
4733 def touch(self, sess: 'AuthSession'):
4734 """Update the last activity time of a session.
4736 Args:
4737 sess: The session.
4738 """
4740 def cleanup(self):
4741 """Remove expired sessions from the storage."""
4742################################################################################
4746################################################################################
4747# /base/layer/types.pyinc
4750class LayerDisplayMode(Enum):
4751 """How a layer is rendered."""
4753 box = 'box'
4754 """Render the map view as a single image."""
4755 tile = 'tile'
4756 """Render the layer as tiles of a grid."""
4757 client = 'client'
4758 """Let the client render the layer from its source."""
4761class FeatureLoadingStrategy(Enum):
4762 """When the client loads a layer's features."""
4764 all = 'all'
4765 """Load all features once, on first display."""
4766 bbox = 'bbox'
4767 """Reload features for the current map extent whenever it changes."""
4768 lazy = 'lazy'
4769 """Load features only when a search text is entered."""
4772class LayerOwsBinding(Node):
4773 """Binding of a layer to OWS services: access, names and models."""
4775 allowedServiceUids: list[str]
4776 """UIDs of services which can use this layer; empty means any."""
4777 deniedServiceUids: list[str]
4778 """UIDs of services which can not use this layer."""
4779 featureName: str
4780 """Name for features in this layer."""
4781 geometryName: str
4782 """Name for geometries in this layer."""
4783 layerName: str
4784 """Name for this layer in OWS services."""
4785 models: list['Model']
4786 """OWS-specific models."""
4787 xmlNamespace: Optional['XmlNamespace']
4788 """XML namespace for feature and layer names."""
4791class Layer(Node):
4792 """Layer object."""
4794 bounds: Bounds
4795 """Bounds in the map CRS: the WGS extent clipped to the parent extent and to the CRS."""
4796 canRenderBox: bool
4797 """The layer can render a single image for an arbitrary extent."""
4798 canRenderInClient: bool
4799 """The layer can be drawn by the client directly from its source (``display: client``)."""
4800 canRenderSvg: bool
4801 """The layer can render its features as SVG."""
4802 canRenderTile: bool
4803 """The layer can render tiles in a fixed grid."""
4804 cssSelector: str
4805 """CSS selector for feature styling."""
4806 displayMode: LayerDisplayMode
4807 """How the client displays the layer."""
4808 finders: list['Finder']
4809 """Search providers."""
4810 grabbers: dict[int, 'Grabber']
4811 """Grabbers by CRS code, one for each CRS the application supports."""
4812 hasLegend: bool
4813 """The layer has a legend."""
4814 imageFormat: ImageFormat
4815 """Image format for box and tile rendering."""
4816 isEnabledForOws: bool
4817 """The layer can be used by OWS services."""
4818 isGroup: bool
4819 """The layer is a group of other layers."""
4820 isSearchable: bool
4821 """The layer has at least one search provider."""
4822 layers: list['Layer']
4823 """Child layers."""
4824 legend: Optional['Legend']
4825 """Legend object."""
4826 loadingStrategy: FeatureLoadingStrategy
4827 """How the client loads features."""
4828 mapCrs: 'Crs'
4829 """CRS of the map this layer belongs to."""
4830 metadata: 'Metadata'
4831 """Layer metadata."""
4832 models: list['Model']
4833 """Data models."""
4834 opacity: float
4835 """Layer opacity, 0 to 1."""
4836 ows: 'LayerOwsBinding'
4837 """Binding to OWS services."""
4838 resolutions: list[float]
4839 """Resolutions the layer is visible at, in map units per pixel."""
4840 sourceLayers: list['SourceLayer']
4841 """Source layers this layer is built from."""
4842 templates: list['Template']
4843 """Layer templates."""
4844 title: str
4845 """Layer title."""
4846 wgsExtent: Extent
4847 """Layer extent in WGS84."""
4848 zoomBounds: Bounds
4849 """Bounds the client zooms to for this layer; defaults to ``bounds``."""
4851 def find_features(self, search: 'SearchQuery', user: 'User') -> list['Feature']:
4852 """Find features in the layer.
4854 Vector layers search in the first model the user can read; other
4855 layers return an empty list.
4857 Args:
4858 search: Search query.
4859 user: The user who searches.
4861 Returns:
4862 Found features.
4863 """
4865 def render(self, lri: LayerRenderInput) -> Optional['LayerRenderOutput']:
4866 """Render a box, a tile or an SVG fragment, depending on the input type.
4868 Args:
4869 lri: Render input.
4871 Returns:
4872 Render output with image content or SVG tags, or ``None`` if the
4873 layer has nothing to render.
4874 """
4876 def render_legend(self, args: Optional[dict | Data] = None) -> Optional['LegendRenderOutput']:
4877 """Render the layer legend.
4879 Without ``args`` the output is cached for the server lifetime.
4881 Args:
4882 args: Arguments passed to the legend renderer.
4884 Returns:
4885 Legend output, or ``None`` if the layer has no legend.
4886 """
4888 def url_path_for(self, kind: str) -> str:
4889 """Return the URL path for requests to this layer.
4891 Args:
4892 kind: ``box``, ``tile``, ``legend`` or ``features``. The ``tile``
4893 path contains ``{z}``, ``{x}`` and ``{y}`` placeholders.
4895 Returns:
4896 URL path.
4898 Raises:
4899 ``gws.Error``: If ``kind`` is not recognized.
4900 """
4901################################################################################
4904################################################################################
4905# /base/grabber/types.pyinc
4908class Grabber:
4909 """Raster grabber.
4911 Provides raster images for a layer: fetches them from a source, aligns them to a
4912 tile grid, stores and reads them back.
4913 """
4915 cache: MapCache
4916 """Cache settings; the name (``<layer cache name>_<srid>``) keys the tile store."""
4917 extent: Extent
4918 """Extent covered by this grabber, in the target CRS."""
4919 grid: MapGrid
4920 """The fixed target grid for the CRS."""
4921 imageFormat: ImageFormat
4922 """Format tiles are stored and returned in."""
4923 sourceCrs: Crs
4924 """Source CRS; defines the original CRS of the raster data."""
4925 store: 'TileStore'
4926 """Persistent tile store."""
4927 targetCrs: Crs
4928 """Target CRS; one grabber serves exactly one CRS."""
4930 def get_tile_as_bytes(self, mt: MapTile, params: Optional[dict] = None) -> bytes:
4931 """Return a single tile as an encoded image, composing and storing it if needed.
4933 A tile outside the layer's range is a transparent image.
4935 Args:
4936 mt: Tile.
4937 params: Dynamic request parameters. With ``params``, the persistent store is bypassed.
4939 Returns:
4940 The encoded tile.
4942 Raises:
4943 ``Exception``: Errors of the source request are passed through.
4944 """
4946 def get_tile_as_image(self, mt: MapTile, params: Optional[dict] = None) -> 'Image':
4947 """Return a single tile as an image, composing and storing it if needed.
4949 Same contract as ``get_tile_as_bytes``, decoded pixels instead of bytes.
4951 Args:
4952 mt: Tile.
4953 params: Dynamic request parameters. With ``params``, the persistent store is bypassed.
4955 Returns:
4956 The tile image.
4958 Raises:
4959 ``Exception``: Errors of the source request are passed through.
4960 """
4962 def get_tiles_as_bytes_dict(self, mtr: MapTileRange, params: Optional[dict] = None) -> dict[MapTile, bytes]:
4963 """Return a rectangular block of tiles as encoded images.
4965 Args:
4966 mtr: Tile range.
4967 params: Dynamic request parameters. With ``params``, the persistent store is bypassed.
4969 Returns:
4970 Encoded tiles, keyed by tile. Sparse: contains entries only for tiles present in the grid.
4972 Raises:
4973 ``Exception``: Errors of the source request are passed through.
4974 """
4976 def get_tiles_as_image_dict(self, mtr: MapTileRange, params: Optional[dict] = None) -> dict[MapTile, 'Image']:
4977 """Return a rectangular block of tiles as images.
4979 Same contract as ``get_tiles_as_bytes_dict``, decoded pixels instead of bytes.
4981 Args:
4982 mtr: Tile range.
4983 params: Dynamic request parameters. With ``params``, the persistent store is bypassed.
4985 Returns:
4986 Tile images, keyed by tile.
4988 Raises:
4989 ``Exception``: Errors of the source request are passed through.
4990 """
4992 def get_box_as_bytes(self, extent: Extent, w: int, h: int, params: Optional[dict] = None) -> bytes:
4993 """Return an encoded image for arbitrary extent and pixel size.
4995 A box overlapping no data is a transparent image.
4997 Args:
4998 extent: Extent in the target CRS.
4999 w: Width in pixels.
5000 h: Height in pixels.
5001 params: Dynamic request parameters. With ``params``, the persistent store is bypassed.
5003 Returns:
5004 The encoded image.
5006 Raises:
5007 ``Exception``: Errors of the source request are passed through.
5008 """
5010 def get_box_as_image(self, extent: Extent, w: int, h: int, params: Optional[dict] = None) -> 'Image':
5011 """Return an image for arbitrary extent and pixel size.
5013 Same contract as ``get_box_as_bytes``, decoded pixels instead of bytes.
5015 Args:
5016 extent: Extent in the target CRS.
5017 w: Width in pixels.
5018 h: Height in pixels.
5019 params: Dynamic request parameters. With ``params``, the persistent store is bypassed.
5021 Returns:
5022 The image.
5024 Raises:
5025 ``Exception``: Errors of the source request are passed through.
5026 """
5028 def levels(self) -> list[int]:
5029 """Return the levels this grabber supports.
5031 Returns:
5032 A list of levels.
5033 """
5035 def tile_range_for_level(self, z: int) -> MapTileRange:
5036 """Return the tile range covered by the grabber's extent at a level.
5038 Args:
5039 z: Level.
5041 Returns:
5042 The tile range in the grabber's grid.
5043 """
5044################################################################################
5047################################################################################
5048# /base/legend/types.pyinc
5051class LegendRenderOutput(Data):
5052 """Legend render output."""
5054 html: str
5055 """HTML representation of the legend; not set by the built-in legend types."""
5056 image: 'Image'
5057 """Legend image."""
5058 size: Size
5059 """Size of the legend image in pixels."""
5062class Legend(Node):
5063 """Legend object."""
5065 def render(self, args: Optional[dict | Data] = None) -> Optional[LegendRenderOutput]:
5066 """Render the legend.
5068 Args:
5069 args: Arguments for the renderer, for example template arguments.
5071 Returns:
5072 Legend output, or ``None`` if there is nothing to show.
5073 """
5074################################################################################
5077################################################################################
5078# /base/map/types.pyinc
5081class Map(Node):
5082 """Map object."""
5084 rootLayer: 'Layer'
5085 """Root group layer that holds the map layers."""
5087 bounds: Bounds
5088 """Map extent in the map CRS."""
5089 center: Point
5090 """Initial map center."""
5091 coordinatePrecision: int
5092 """Decimal places for coordinates."""
5093 initResolution: float
5094 """Initial resolution."""
5095 resolutions: list[float]
5096 """Resolutions the map can be displayed at, in map units per pixel."""
5097 title: str
5098 """Map title."""
5099 wgsExtent: Extent
5100 """Map extent in WGS84."""
5101################################################################################
5105################################################################################
5106# /base/model/types.pyinc
5109class ModelClientOptions(Data):
5110 """Client options for a model."""
5112 keepFormOpen: Optional[bool]
5113 """Keep the edit form open after saving."""
5116class ModelValidationError(Data):
5117 """Validation error of a feature field."""
5119 fieldName: str
5120 """Name of the field that failed validation."""
5121 message: str
5122 """Error message, or a message key for the client."""
5125class ModelOperation(Enum):
5126 """Model operation."""
5128 read = 'read'
5129 """Read features."""
5130 create = 'create'
5131 """Create new features."""
5132 update = 'update'
5133 """Update existing features."""
5134 delete = 'delete'
5135 """Delete features."""
5136 export = 'export'
5137 """Export features."""
5140class ModelReadTarget(Enum):
5141 """Target for the read operation."""
5143 map = 'map'
5144 """The feature is to be drawn on a map."""
5145 searchResults = 'searchResults'
5146 """The feature is to be displayed in the search results list."""
5147 list = 'list'
5148 """The feature is to be displayed in a list view."""
5149 editList = 'editList'
5150 """The feature is to be displayed in an editable list view."""
5151 editForm = 'editForm'
5152 """The feature is to be displayed in an edit form."""
5155class ModelSelectBuild(Data):
5156 """Parts of a database select statement, collected from the model fields."""
5158 columns: list['sqlalchemy.Column']
5159 """Columns to select."""
5160 geometryWhere: list
5161 """Conditions for the geometry search, combined with OR."""
5162 keywordWhere: list
5163 """Conditions for the keyword search, combined with OR."""
5164 where: list
5165 """Other conditions, combined with AND."""
5166 order: list
5167 """Sort expressions."""
5170class ModelContext(Data):
5171 """Context of a model operation."""
5173 op: ModelOperation
5174 """The operation."""
5175 target: ModelReadTarget
5176 """Where the features are to be displayed, for read operations."""
5177 user: 'User'
5178 """The user performing the operation."""
5179 project: Optional['Project']
5180 """The current project."""
5181 relDepth: int = 0
5182 """Current depth of related features."""
5183 maxDepth: int = 0
5184 """Maximum depth of related features to process."""
5185 search: 'SearchQuery'
5186 """The search query, for read operations."""
5187 dbSelect: ModelSelectBuild
5188 """The select statement being built, for database read operations."""
5191EmptyValue = object()
5192"""Special value for empty fields."""
5194ErrorValue = object()
5195"""Special value for invalid fields."""
5198class ModelWidget(Node):
5199 """Model widget.
5201 Describes how the client displays and edits a field value.
5202 """
5204 supportsTableView: bool = True
5205 """The widget can be used in the table view."""
5208class ModelValidator(Node):
5209 """Model validator.
5211 Checks the value of a field.
5212 """
5214 message: str
5215 """Error message, or a message key for the client."""
5216 ops: set[ModelOperation]
5217 """Operations the validator applies to."""
5219 def validate(self, field: 'ModelField', feature: 'Feature', mc: ModelContext) -> bool:
5220 """Check the value of a field in a feature.
5222 Args:
5223 field: The field.
5224 feature: The feature.
5225 mc: The model context.
5227 Returns:
5228 True if the value is valid.
5229 """
5232class ModelValue(Node):
5233 """Model value.
5235 Computes a value for a field.
5236 """
5238 isDefault: bool
5239 """The value is used only when the source provides no value."""
5240 ops: set[ModelOperation]
5241 """Operations the value applies to."""
5243 def compute(self, field: 'ModelField', feature: 'Feature', mc: 'ModelContext'):
5244 """Compute the value of a field.
5246 Args:
5247 field: The field.
5248 feature: The feature.
5249 mc: The model context.
5251 Returns:
5252 The computed value.
5253 """
5256class ModelField(Node):
5257 """Model field.
5259 Handles a subset of feature data. The model calls the field methods when it performs
5260 an operation; the methods read and write ``feature.attributes``, ``feature.record``
5261 and ``feature.props``.
5262 """
5264 name: str
5265 """Field name."""
5266 title: str
5267 """Field title."""
5269 attributeType: AttributeType
5270 """Type of the field value."""
5272 widget: Optional['ModelWidget'] = None
5273 """Widget for the client."""
5275 values: list['ModelValue']
5276 """Value objects."""
5277 validators: list['ModelValidator']
5278 """Validators."""
5280 isPrimaryKey: bool
5281 """The field is a primary key."""
5282 isRequired: bool
5283 """The field must not be empty."""
5284 isUnique: bool
5285 """The field is unique."""
5286 isAuto: bool
5287 """The value is set by the database and never written."""
5288 isHidden: bool
5289 """The field is not automatically displayed in the client."""
5291 supportsFilterSearch: bool = False
5292 """The field supports filter search."""
5293 supportsGeometrySearch: bool = False
5294 """The field supports geometry search."""
5295 supportsKeywordSearch: bool = False
5296 """The field supports keyword search."""
5298 model: 'Model'
5299 """The model of the field."""
5301 def before_select(self, mc: ModelContext):
5302 """Called before features are selected, adds columns and conditions to ``mc.dbSelect``.
5304 Args:
5305 mc: The model context.
5306 """
5308 def after_select(self, features: list['Feature'], mc: ModelContext):
5309 """Called after features are selected, sets the field value in the features.
5311 Args:
5312 features: The selected features.
5313 mc: The model context.
5314 """
5316 def before_create(self, feature: 'Feature', mc: ModelContext):
5317 """Called before a feature is inserted, writes the field value to ``feature.record``.
5319 Args:
5320 feature: The feature.
5321 mc: The model context.
5322 """
5324 def after_create(self, feature: 'Feature', mc: ModelContext):
5325 """Called after a feature is inserted.
5327 Args:
5328 feature: The feature.
5329 mc: The model context.
5330 """
5332 def before_create_related(self, dst_feature: 'Feature', mc: ModelContext):
5333 """Called before a feature of another model, created together with features of this model, is inserted.
5335 Args:
5336 dst_feature: The feature being created.
5337 mc: The model context.
5338 """
5340 def after_create_related(self, dst_feature: 'Feature', mc: ModelContext):
5341 """Called after a feature of another model, created together with features of this model, is inserted.
5343 Args:
5344 dst_feature: The created feature.
5345 mc: The model context.
5346 """
5348 def before_update(self, feature: 'Feature', mc: ModelContext):
5349 """Called before a feature is updated, writes the field value to ``feature.record``.
5351 Args:
5352 feature: The feature.
5353 mc: The model context.
5354 """
5356 def after_update(self, feature: 'Feature', mc: ModelContext):
5357 """Called after a feature is updated.
5359 Args:
5360 feature: The feature.
5361 mc: The model context.
5362 """
5364 def before_delete(self, feature: 'Feature', mc: ModelContext):
5365 """Called before a feature is deleted.
5367 Args:
5368 feature: The feature.
5369 mc: The model context.
5370 """
5372 def after_delete(self, feature: 'Feature', mc: ModelContext):
5373 """Called after a feature is deleted.
5375 Args:
5376 feature: The feature.
5377 mc: The model context.
5378 """
5380 def do_init(self, feature: 'Feature', mc: ModelContext):
5381 """Set the initial field value of a new feature.
5383 Args:
5384 feature: The feature.
5385 mc: The model context.
5386 """
5388 def do_init_related(self, dst_feature: 'Feature', mc: ModelContext):
5389 """Initialize a new feature of another model that is created together with features of this model.
5391 Args:
5392 dst_feature: The new feature.
5393 mc: The model context.
5394 """
5396 def do_validate(self, feature: 'Feature', mc: ModelContext):
5397 """Validate the field value and append errors to ``feature.errors``.
5399 Args:
5400 feature: The feature.
5401 mc: The model context.
5402 """
5404 def from_props(self, feature: 'Feature', mc: ModelContext):
5405 """Set the field value from ``feature.props``.
5407 Args:
5408 feature: The feature.
5409 mc: The model context.
5410 """
5412 def to_props(self, feature: 'Feature', mc: ModelContext):
5413 """Write the field value to ``feature.props``.
5415 Args:
5416 feature: The feature.
5417 mc: The model context.
5418 """
5420 def from_record(self, feature: 'Feature', mc: ModelContext):
5421 """Set the field value from ``feature.record``.
5423 Args:
5424 feature: The feature.
5425 mc: The model context.
5426 """
5428 def to_record(self, feature: 'Feature', mc: ModelContext):
5429 """Write the field value to ``feature.record``.
5431 Args:
5432 feature: The feature.
5433 mc: The model context.
5434 """
5436 def related_models(self) -> list['Model']:
5437 """Return the models related to this field.
5439 Returns:
5440 A list of models, empty for fields that are not related fields.
5441 """
5443 def find_relatable_features(self, search: 'SearchQuery', mc: ModelContext) -> list['Feature']:
5444 """Find features that can be linked by this field.
5446 Args:
5447 search: The search query.
5448 mc: The model context.
5450 Returns:
5451 The features found in the related models.
5452 """
5454 def raw_to_python(self, feature: 'Feature', value, mc: ModelContext):
5455 """Convert a raw source value to a python value.
5457 Args:
5458 feature: The feature.
5459 value: The value to convert.
5460 mc: The model context.
5462 Returns:
5463 The converted value.
5464 """
5466 def prop_to_python(self, feature: 'Feature', value, mc: ModelContext):
5467 """Convert a client props value to a python value.
5469 Args:
5470 feature: The feature.
5471 value: The value to convert.
5472 mc: The model context.
5474 Returns:
5475 The converted value.
5476 """
5478 def python_to_raw(self, feature: 'Feature', value, mc: ModelContext):
5479 """Convert a python value to a raw source value.
5481 Args:
5482 feature: The feature.
5483 value: The value to convert.
5484 mc: The model context.
5486 Returns:
5487 The converted value.
5488 """
5490 def python_to_prop(self, feature: 'Feature', value, mc: ModelContext):
5491 """Convert a python value to a client props value.
5493 Args:
5494 feature: The feature.
5495 value: The value to convert.
5496 mc: The model context.
5498 Returns:
5499 The converted value.
5500 """
5502 def describe(self) -> Optional['ColumnDescription']:
5503 """Return the description of the source column of this field.
5505 Returns:
5506 The column description, or None if the source has no such column.
5507 """
5510class Model(Node):
5511 """Data model.
5513 Reads features from a source, converts them to and from client props and,
5514 if editable, writes them back.
5515 """
5517 clientOptions: ModelClientOptions
5518 """Client options."""
5519 defaultSort: list['SearchSort']
5520 """Default sort order of features."""
5521 fields: list['ModelField']
5522 """Model fields."""
5523 geometryCrs: Optional['Crs']
5524 """CRS of the geometry field."""
5525 geometryName: str
5526 """Name of the geometry field."""
5527 geometryType: Optional[GeometryType]
5528 """Type of the geometry field."""
5529 isEditable: bool
5530 """Features of this model can be edited."""
5531 loadingStrategy: 'FeatureLoadingStrategy'
5532 """How the client loads features."""
5533 exportStrategy: 'FeatureExportStrategy'
5534 """How features are obtained for export."""
5535 title: str
5536 """Model title."""
5537 uidName: str
5538 """Name of the uid (primary key) field."""
5539 withTableView: bool
5540 """The table view of features is enabled in the client."""
5542 def find_features(self, search: 'SearchQuery', mc: ModelContext) -> list['Feature']:
5543 """Find features matching a search query.
5545 Args:
5546 search: The search query.
5547 mc: The model context.
5549 Returns:
5550 The features found.
5551 """
5553 def get_features(self, uids: Iterable[str | int], mc: ModelContext) -> list['Feature']:
5554 """Return features by uid.
5556 Args:
5557 uids: Feature uids.
5558 mc: The model context.
5560 Returns:
5561 The features found, empty if no uids are given.
5562 """
5564 def get_feature(self, uid: str | int, mc: ModelContext) -> Optional['Feature']:
5565 """Return a feature by uid.
5567 Args:
5568 uid: The feature uid.
5569 mc: The model context.
5571 Returns:
5572 The feature, or None if it is not found.
5573 """
5575 def init_feature(self, feature: 'Feature', mc: ModelContext):
5576 """Initialize a new feature with initial field values.
5578 Args:
5579 feature: The new feature.
5580 mc: The model context.
5582 Raises:
5583 gws.ForbiddenError: If the user cannot create features of this model.
5584 """
5586 def create_feature(self, feature: 'Feature', mc: ModelContext) -> FeatureUid:
5587 """Insert a new feature into the source.
5589 Args:
5590 feature: The feature.
5591 mc: The model context.
5593 Returns:
5594 The primary key of the inserted feature.
5596 Raises:
5597 gws.ForbiddenError: If the user cannot create features of this model.
5598 """
5600 def update_feature(self, feature: 'Feature', mc: ModelContext) -> FeatureUid:
5601 """Update an existing feature in the source.
5603 Args:
5604 feature: The feature.
5605 mc: The model context.
5607 Returns:
5608 The uid of the feature.
5610 Raises:
5611 gws.ForbiddenError: If the user cannot write to this model.
5612 """
5614 def delete_feature(self, feature: 'Feature', mc: ModelContext) -> FeatureUid:
5615 """Delete a feature from the source.
5617 Args:
5618 feature: The feature.
5619 mc: The model context.
5621 Returns:
5622 The uid of the feature.
5624 Raises:
5625 gws.ForbiddenError: If the user cannot delete features of this model.
5626 """
5628 def validate_feature(self, feature: 'Feature', mc: ModelContext) -> bool:
5629 """Validate a feature and store validation errors in ``feature.errors``.
5631 Args:
5632 feature: The feature.
5633 mc: The model context.
5635 Returns:
5636 True if the feature has no errors.
5637 """
5639 def feature_from_props(self, props: 'FeatureProps', mc: ModelContext) -> 'Feature':
5640 """Create a feature from client props.
5642 Args:
5643 props: The feature props.
5644 mc: The model context.
5646 Returns:
5647 A new feature.
5648 """
5650 def feature_to_props(self, feature: 'Feature', mc: ModelContext) -> 'FeatureProps':
5651 """Convert a feature to client props and store them in ``feature.props``.
5653 Args:
5654 feature: The feature.
5655 mc: The model context.
5657 Returns:
5658 The feature props.
5659 """
5661 def feature_to_view_props(self, feature: 'Feature', mc: ModelContext) -> 'FeatureProps':
5662 """Convert a feature to client props for viewing, with a reduced set of attributes.
5664 Args:
5665 feature: The feature.
5666 mc: The model context.
5668 Returns:
5669 The feature props.
5670 """
5672 def describe(self) -> Optional['DataSetDescription']:
5673 """Return the description of the model source.
5675 Returns:
5676 The dataset description, or None if the source cannot be described.
5677 """
5679 def field(self, name: str) -> Optional['ModelField']:
5680 """Return a field by name.
5682 Args:
5683 name: The field name.
5685 Returns:
5686 The field, or None if it is not found.
5687 """
5689 def related_models(self) -> list['Model']:
5690 """Return the models related to the fields of this model.
5692 Returns:
5693 A list of models without duplicates.
5694 """
5697class ModelManager(Node):
5698 """Model manager.
5700 Looks up models and provides the default model.
5701 """
5703 def get_model(self, uid: str, user: 'User' = None, access: Access = None) -> Optional['Model']:
5704 """Return a model by uid.
5706 Args:
5707 uid: The model uid.
5708 user: If given together with ``access``, the user must have this access to the model.
5709 access: The required access.
5711 Returns:
5712 The model, or None if it is not found or not accessible.
5713 """
5715 def find_model(self, *objects, user: 'User' = None, access: Access = None) -> Optional['Model']:
5716 """Return the first model of the given objects.
5718 Looks in the ``models`` attribute of each object in turn.
5720 Args:
5721 *objects: Objects with models, e.g. layers. None values are skipped.
5722 user: If given together with ``access``, the user must have this access to the model.
5723 access: The required access.
5725 Returns:
5726 The model, or None if none is found.
5727 """
5729 def editable_models(self, project: 'Project', user: 'User') -> list['Model']:
5730 """Return the models a user can edit in a project, together with their related models.
5732 Args:
5733 project: The project.
5734 user: The user.
5736 Returns:
5737 The models, sorted by title.
5738 """
5740 def default_model(self) -> 'Model':
5741 """Return the shared default model.
5743 Returns:
5744 The default model.
5745 """
5746################################################################################
5749################################################################################
5750# /base/database/types.pyinc
5753class DatabaseModel(Model):
5754 """Data model for a database table."""
5756 db: 'DatabaseProvider'
5757 """Database provider."""
5758 sqlFilter: str
5759 """Literal SQL condition applied when selecting rows."""
5760 tableName: str
5761 """Table name associated with this model."""
5763 def table(self) -> 'sqlalchemy.Table':
5764 """Return the SQLAlchemy ``Table`` object of the model table.
5766 Returns:
5767 The table object.
5769 Raises:
5770 ``sqlalchemy.exc.SQLAlchemyError``: If the table does not exist.
5771 """
5773 def column(self, column_name: str) -> 'sqlalchemy.Column':
5774 """Return the SQLAlchemy ``Column`` object of a column in the model table.
5776 Args:
5777 column_name: Column name.
5779 Returns:
5780 The column object.
5782 Raises:
5783 ``sqlalchemy.exc.SQLAlchemyError``: If the table or the column does not exist.
5784 """
5786 def uid_column(self) -> 'sqlalchemy.Column':
5787 """Return the SQLAlchemy ``Column`` object of the primary key column.
5789 Returns:
5790 The column object for ``uidName``.
5792 Raises:
5793 ``gws.Error``: If the model has no primary key or the key column does not exist.
5794 """
5796 def uid_equals(self, uid: FeatureUid | Iterable[FeatureUid]) -> 'sqlalchemy.ColumnElement[bool]':
5797 """Return a condition that matches features by uid.
5799 The values are bound with the type of the primary key column, so that
5800 string uids can be compared with columns of other types.
5802 Args:
5803 uid: A feature uid, or an iterable of uids.
5805 Returns:
5806 An ``=`` condition for a single uid, an ``IN`` condition for an iterable.
5808 Raises:
5809 ``gws.Error``: If the model has no primary key or the key column does not exist.
5810 """
5812 def fetch_features(self, select: 'sqlalchemy.Select') -> list['Feature']:
5813 """Run a SELECT statement and create a feature for each row.
5815 The row values become the attributes of the feature record.
5817 Args:
5818 select: SELECT statement.
5820 Returns:
5821 A list of features.
5822 """
5824 def build_select(self, mc: 'ModelContext') -> Optional['sqlalchemy.Select']:
5825 """Build a SELECT statement for a search.
5827 Combines the search query in ``mc.search``, the columns and conditions
5828 collected by the fields in ``mc.dbSelect`` and ``sqlFilter``.
5830 Args:
5831 mc: Model context with ``search`` and ``dbSelect`` set.
5833 Returns:
5834 The SELECT statement, or ``None`` if the search cannot match anything.
5835 """
5838class ColumnDescription(Data):
5839 """Description of a dataset column."""
5841 columnIndex: int
5842 """The index of the column within the table."""
5843 comment: str
5844 """Column comment or description provided in the database metadata."""
5845 geometrySrid: int
5846 """The Spatial Reference Identifier (SRID) for geometry columns."""
5847 geometryType: GeometryType
5848 """The type of geometry stored in the column (e.g., Point, Polygon)."""
5849 isAutoincrement: bool
5850 """Indicates if the column is auto-incremented."""
5851 isNullable: bool
5852 """Specifies if the column permits NULL values."""
5853 isPrimaryKey: bool
5854 """Specifies if the column is part of the primary key."""
5855 isUnique: bool
5856 """Indicates if the column has a unique constraint."""
5857 hasDefault: bool
5858 """Indicates if the column has a database-defined default value."""
5859 isIndexed: bool
5860 """Indicates if the column has an index."""
5861 name: str
5862 """The name of the column."""
5863 nativeType: str
5864 """The database-specific data type of the column."""
5865 options: dict
5866 """Additional options or configurations for the column, if any."""
5867 type: AttributeType
5868 """The abstract type of the column used in higher-level processing."""
5871class DataSetDescription(Data):
5872 """Description of a dataset, like a DB table or a GDAL data set."""
5874 columns: list[ColumnDescription]
5875 """A list of column descriptions."""
5876 columnMap: dict[str, ColumnDescription]
5877 """A dictionary mapping column names to their descriptions."""
5878 fullName: str
5879 """The full name of the dataset, including schema if applicable."""
5880 geometryName: str
5881 """The name of the geometry column, if any."""
5882 geometrySrid: int
5883 """The Spatial Reference Identifier (SRID) for the geometry."""
5884 geometryType: GeometryType
5885 """The type of geometry stored in the dataset."""
5886 name: str
5887 """The name of the dataset or table."""
5888 schema: str
5889 """The schema to which the dataset belongs."""
5892class DatabaseManager(Node):
5893 """Database manager."""
5895 providers: list['DatabaseProvider']
5896 """A list of database providers managed by this DatabaseManager."""
5898 def create_provider(self, cfg: Config, **kwargs) -> 'DatabaseProvider':
5899 """Create a database provider and add it to ``providers``.
5901 The provider is created as a shared object. A provider with the same uid
5902 that is already in ``providers`` is replaced.
5904 Args:
5905 cfg: Provider configuration.
5906 **kwargs: Extra configuration values.
5908 Returns:
5909 The provider.
5910 """
5912 def find_provider(self, uid: Optional[str] = None, ext_type: Optional[str] = None) -> Optional['DatabaseProvider']:
5913 """Find a database provider by uid or type.
5915 With ``uid``, returns the provider with this uid (and of type ``ext_type``,
5916 if given). With ``ext_type`` only, returns the first provider of this type.
5917 Without arguments, returns the first provider.
5919 Args:
5920 uid: Provider uid.
5921 ext_type: Provider type, e.g. ``postgres``.
5923 Returns:
5924 The provider, or ``None`` if none matches.
5925 """
5928DatabaseTableAlike: TypeAlias = Union['sqlalchemy.Table', str]
5929"""An SQLAlchemy ``Table`` object or a string table name."""
5932DatabaseStmt: TypeAlias = Union['sqlalchemy.Executable', str]
5933"""An Executable SQLAlchemy object or a string SQL statement."""
5936class DatabaseConnection:
5937 """Database connection.
5939 Wraps an SQLAlchemy ``Connection`` and provides some convenience methods.
5940 Returned by ``DatabaseProvider.begin``. The connection does not control
5941 the transaction: it is committed or rolled back by ``begin``.
5943 Statements can be SQLAlchemy objects or SQL strings with ``:name`` bind
5944 parameters.
5945 """
5947 saConn: 'sqlalchemy.Connection'
5948 """The underlying SQLAlchemy connection."""
5950 def execute(self, stmt: 'DatabaseStmt', params=None, execution_options: dict=None) -> 'sqlalchemy.CursorResult':
5951 """Execute a statement.
5953 Args:
5954 stmt: Statement or SQL string.
5955 params: Bind parameters, a dict or a list of dicts.
5956 execution_options: SQLAlchemy execution options.
5958 Returns:
5959 The result.
5960 """
5962 def fetch_all(self, stmt: 'DatabaseStmt', **params) -> list[dict]:
5963 """Execute a statement and return all rows.
5965 Args:
5966 stmt: Statement or SQL string.
5967 **params: Bind parameters.
5969 Returns:
5970 A list of rows as dicts.
5971 """
5973 def fetch_first(self, stmt: 'DatabaseStmt', **params) -> dict | None:
5974 """Execute a statement and return the first row.
5976 Args:
5977 stmt: Statement or SQL string.
5978 **params: Bind parameters.
5980 Returns:
5981 The first row as a dict, or ``None`` if there are no rows.
5982 """
5984 def fetch_scalars(self, stmt: 'DatabaseStmt', **params) -> list:
5985 """Execute a statement and return the first column of all rows.
5987 Args:
5988 stmt: Statement or SQL string.
5989 **params: Bind parameters.
5991 Returns:
5992 A list of values.
5993 """
5995 def fetch_strings(self, stmt: 'DatabaseStmt', **params) -> list[str]:
5996 """Execute a statement and return the first column of all rows as strings.
5998 Args:
5999 stmt: Statement or SQL string.
6000 **params: Bind parameters.
6002 Returns:
6003 A list of strings, with ``NULL`` values as empty strings.
6004 """
6006 def fetch_ints(self, stmt: 'DatabaseStmt', **params) -> list[int]:
6007 """Execute a statement and return the first column of all rows as integers.
6009 Args:
6010 stmt: Statement or SQL string.
6011 **params: Bind parameters.
6013 Returns:
6014 A list of integers.
6016 Raises:
6017 ``ValueError``: If a value is not an integer.
6018 """
6020 def fetch_scalar(self, stmt: 'DatabaseStmt', **params) -> Any:
6021 """Execute a statement and return the first column of the first row.
6023 Args:
6024 stmt: Statement or SQL string.
6025 **params: Bind parameters.
6027 Returns:
6028 The value, or ``None`` if there are no rows.
6029 """
6031 def fetch_string(self, stmt: 'DatabaseStmt', **params) -> str | None:
6032 """Execute a statement and return the first column of the first row as a string.
6034 Args:
6035 stmt: Statement or SQL string.
6036 **params: Bind parameters.
6038 Returns:
6039 The string, or ``None`` if there are no rows or the value is ``NULL``.
6040 """
6042 def fetch_int(self, stmt: 'DatabaseStmt', **params) -> int | None:
6043 """Execute a statement and return the first column of the first row as an integer.
6045 Args:
6046 stmt: Statement or SQL string.
6047 **params: Bind parameters.
6049 Returns:
6050 The integer, or ``None`` if there are no rows or the value is ``NULL``.
6052 Raises:
6053 ``ValueError``: If the value is not an integer.
6054 """
6056class DatabaseInspectOptions(Data):
6057 """Options for database inspection."""
6059 refresh: bool = False
6060 """Whether to force inspection even if cached information is available."""
6061 cacheLifeTime: int = 0
6062 """Schema cache lifetime in seconds."""
6065class DatabaseProvider(Node):
6066 """Database provider.
6068 Wraps an SQLAlchemy ``Engine`` and hands out connections. Also reflects
6069 table structures and describes tables and columns.
6070 """
6072 def begin(self, nested: bool = False) -> ContextManager['DatabaseConnection']:
6073 """Begin a transaction, to be used as a context manager.
6075 The outermost call opens a connection and begins a transaction, which
6076 is committed on normal exit and rolled back on an exception. Inner
6077 calls in the same thread join the open transaction, or create a
6078 savepoint if ``nested`` is set::
6080 with db.begin() as conn:
6081 conn.execute('INSERT ...')
6082 with db.begin() as conn2: # same connection and transaction
6083 rows = conn2.fetch_all('SELECT ...')
6084 with db.begin(nested=True) as conn3: # savepoint
6085 conn3.execute('UPDATE ...')
6086 # committed, connection closed
6088 Unlike SQLAlchemy ``Engine.begin``, an inner call does not open a new
6089 connection. Each provider keeps its own connection per thread.
6091 Args:
6092 nested: Create a savepoint when joining an open transaction. An
6093 exception inside the block then rolls back to the savepoint
6094 only. Has no effect on the outermost call.
6096 Returns:
6097 A context manager that yields the connection.
6098 """
6100 def connect(self) -> ContextManager['DatabaseConnection']:
6101 """Deprecated, same as ``begin``."""
6103 def autocommit_connection(self) -> ContextManager['DatabaseConnection']:
6104 """Open a separate connection in autocommit mode, to be used as a context manager.
6106 For statements that cannot run inside a transaction, like ``VACUUM``.
6107 The connection is not shared with ``begin``.
6109 Returns:
6110 A context manager that yields the connection.
6112 Raises:
6113 ``gws.Error``: If a transaction of this provider is open in the current thread.
6114 """
6116 def engine_options(self, **kwargs):
6117 """Add defaults to the SQLAlchemy engine options.
6119 Args:
6120 **kwargs: Engine options. Options passed here take precedence over the defaults.
6122 Returns:
6123 The options dict.
6124 """
6126 def url(self) -> str:
6127 """Return the connection URL.
6129 Returns:
6130 An SQLAlchemy connection URL.
6131 """
6133 def engine(self) -> 'sqlalchemy.Engine':
6134 """Return the SQLAlchemy ``Engine`` object for this provider, creating it if needed.
6136 Returns:
6137 The engine.
6138 """
6140 def create_engine(self, **kwargs) -> 'sqlalchemy.Engine':
6141 """Create a new SQLAlchemy ``Engine`` object for this provider.
6143 Args:
6144 **kwargs: Engine options, see ``engine_options``.
6146 Returns:
6147 The engine.
6148 """
6150 def describe(self, table: DatabaseTableAlike) -> 'DataSetDescription':
6151 """Describe a table.
6153 Args:
6154 table: Table object or table name.
6156 Returns:
6157 The table description. The first geometry column becomes the primary geometry.
6159 Raises:
6160 ``sqlalchemy.exc.SQLAlchemyError``: If the table does not exist.
6161 """
6163 def describe_column(self, table: DatabaseTableAlike, column_name: str) -> ColumnDescription:
6164 """Describe a column in a table.
6166 Args:
6167 table: Table object or table name.
6168 column_name: Column name.
6170 Returns:
6171 The column description.
6173 Raises:
6174 ``sqlalchemy.exc.SQLAlchemyError``: If the table or the column does not exist.
6175 """
6177 def table(self, table: 'DatabaseTableAlike', **kwargs) -> 'sqlalchemy.Table':
6178 """Return the SQLAlchemy ``Table`` object for a table.
6180 Args:
6181 table: Table object or table name.
6182 **kwargs: Not used by the base provider.
6184 Returns:
6185 The table object.
6187 Raises:
6188 ``sqlalchemy.exc.SQLAlchemyError``: If the table does not exist.
6189 """
6191 def column(self, table: DatabaseTableAlike, column_name: str) -> 'sqlalchemy.Column':
6192 """Return the SQLAlchemy ``Column`` object for a column.
6194 Args:
6195 table: Table object or table name.
6196 column_name: Column name.
6198 Returns:
6199 The column object.
6201 Raises:
6202 ``sqlalchemy.exc.SQLAlchemyError``: If the table or the column does not exist.
6203 """
6205 def count(self, table: DatabaseTableAlike) -> int:
6206 """Return the number of rows in a table.
6208 Args:
6209 table: Table object or table name.
6211 Returns:
6212 The row count, or 0 if the table does not exist.
6213 """
6215 def has_schema(self, schema_name: str) -> bool:
6216 """Check if a schema exists.
6218 Args:
6219 schema_name: Schema name.
6221 Returns:
6222 ``True`` if the schema exists.
6223 """
6225 def has_table(self, table_name: str) -> bool:
6226 """Check if a table exists.
6228 Args:
6229 table_name: Table name, optionally schema-qualified.
6231 Returns:
6232 ``True`` if the table exists.
6233 """
6235 def has_column(self, table: DatabaseTableAlike, column_name: str) -> bool:
6236 """Check if a column exists.
6238 Args:
6239 table: Table object or table name.
6240 column_name: Column name.
6242 Returns:
6243 ``True`` if the table and the column exist.
6244 """
6246 def join_table_name(self, schema: str, name: str) -> str:
6247 """Create a full table name from the schema and table names.
6249 Args:
6250 schema: Schema name. If empty, the default schema is used.
6251 name: Table name.
6253 Returns:
6254 The schema-qualified table name.
6255 """
6257 def split_table_name(self, table_name: str) -> tuple[str, str]:
6258 """Split a full table name into the schema and table names.
6260 Args:
6261 table_name: Table name, optionally schema-qualified.
6263 Returns:
6264 A tuple of the schema name (the default schema if none is given) and the table name.
6265 """
6267 def table_bounds(self, table: DatabaseTableAlike) -> Optional[Bounds]:
6268 """Compute the bounding box of the primary geometry of a table.
6270 Args:
6271 table: Table object or table name.
6273 Returns:
6274 The bounds, or ``None`` if the table has no geometry or no data.
6275 """
6277 def schema_names(self) -> list[str]:
6278 """Return the names of the schemas in the database.
6280 Returns:
6281 A list of schema names.
6282 """
6284 def inspect_schema(self, schema: str, options: Optional[DatabaseInspectOptions] = None):
6285 """Reflect the tables of a schema and keep the result.
6287 A schema that has already been reflected is not reflected again, unless
6288 ``options.refresh`` is set. The reflected metadata is cached for the
6289 configured schema cache lifetime. If ``options`` are given, their
6290 ``cacheLifeTime`` is used instead; 0 means no caching.
6292 Args:
6293 schema: Schema name.
6294 options: Inspection options.
6295 """
6296################################################################################
6300################################################################################
6301# /base/job/types.pyinc
6304class JobTerminated(Exception):
6305 """Raised in a worker when its job is no longer running, e.g. because it was cancelled."""
6307 pass
6310class JobState(Enum):
6311 """Background job state."""
6313 init = 'init'
6314 """The job is being created."""
6315 open = 'open'
6316 """The job is just created and waiting for start."""
6317 running = 'running'
6318 """The job is running."""
6319 complete = 'complete'
6320 """The job has been completed successfully."""
6321 error = 'error'
6322 """There was an error."""
6323 cancel = 'cancel'
6324 """The job was cancelled."""
6327class Job(Data):
6328 """Background job data."""
6330 uid: str
6331 """Job uid."""
6332 user: 'User'
6333 """User who created the job."""
6334 worker: str
6335 """Worker class, as ``<module path>:<class name>``."""
6336 state: JobState
6337 """Job state."""
6338 error: str
6339 """Error message, if the job failed."""
6340 numSteps: int
6341 """Total number of steps, for progress reporting."""
6342 step: int
6343 """Current step."""
6344 stepName: str
6345 """Name of the current step."""
6346 payload: dict
6347 """Input data for the worker."""
6348 result: dict
6349 """Result data from the worker."""
6350 timeCreated: datetime.datetime
6351 """Creation time."""
6352 timeUpdated: datetime.datetime
6353 """Time of the last update."""
6356class JobRequest(Request):
6357 """Request that refers to a job."""
6359 jobUid: str
6360 """Job uid."""
6363class JobStatusResponse(Response):
6364 """Job status."""
6366 jobUid: str
6367 """Job uid."""
6368 state: JobState
6369 """Job state."""
6370 progress: int
6371 """Progress in percent."""
6372 stepName: str
6373 """Name of the current step."""
6374 output: dict
6375 """Job-specific output, e.g. a download URL when the job is complete."""
6378class JobManager(Node):
6379 """Job manager."""
6381 def create_job(self, worker: type, user: User, payload: dict | Data = None) -> Job:
6382 """Create a job in the ``open`` state.
6384 Args:
6385 worker: Worker class. It must have a ``run(root, job)`` class method.
6386 user: User the job runs for.
6387 payload: Input data for the worker, must be JSON-serializable.
6389 Returns:
6390 The new job.
6391 """
6393 def get_job(self, job_uid: str, user: User = None, state: JobState = None) -> Optional[Job]:
6394 """Read a job.
6396 Args:
6397 job_uid: Job uid.
6398 user: If given, the job must belong to this user.
6399 state: If given, the job must be in this state.
6401 Returns:
6402 The job, or ``None`` if it does not exist or does not match. The reason is logged.
6403 """
6405 def update_job(self, job: Job, **kwargs) -> Optional[Job]:
6406 """Update fields of a job.
6408 Args:
6409 job: The job.
6410 **kwargs: Job fields to update.
6412 Returns:
6413 The updated job, or ``None`` if the job does not exist.
6414 """
6416 def run_job(self, job: Job) -> Optional[Job]:
6417 """Run an open job in the current process.
6419 Marks the job as running, so that it runs only once, and calls the
6420 ``run`` method of its worker. If the worker raises an exception, the
6421 job goes into the ``error`` state.
6423 Args:
6424 job: The job.
6426 Returns:
6427 The job after the run.
6429 Raises:
6430 ``gws.Error``: If the job is not open or is already taken by another process.
6431 """
6433 def cancel_job(self, job: Job) -> Optional[Job]:
6434 """Set a job to the ``cancel`` state.
6436 The worker notices the change on its next job update and stops.
6438 Args:
6439 job: The job.
6441 Returns:
6442 The updated job, or ``None`` if the job does not exist.
6443 """
6445 def remove_job(self, job: Job):
6446 """Delete a job record.
6448 Args:
6449 job: The job.
6450 """
6452 def schedule_job(self, job: Job) -> Job:
6453 """Start an open job.
6455 The job is passed to the uWSGI spooler if it is available, otherwise it
6456 runs at once in the current process.
6458 Args:
6459 job: The job.
6461 Returns:
6462 The job.
6464 Raises:
6465 ``gws.Error``: If the job is not open.
6466 """
6468 def require_job(self, req: 'WebRequester', p: JobRequest) -> Job:
6469 """Return the job of a request, if it belongs to the requesting user.
6471 Args:
6472 req: Web request.
6473 p: Job request.
6475 Returns:
6476 The job.
6478 Raises:
6479 ``gws.NotFoundError``: If the job does not exist or belongs to another user.
6480 """
6482 def require_result(self, req: 'WebRequester', p: JobRequest) -> dict:
6483 """Return the result of a completed job of the requesting user.
6485 Args:
6486 req: Web request.
6487 p: Job request.
6489 Returns:
6490 The job result.
6492 Raises:
6493 ``gws.NotFoundError``: If the job does not exist, belongs to another user,
6494 is not complete or has no result.
6495 """
6497 def handle_status_request(self, req: 'WebRequester', p: JobRequest) -> JobStatusResponse:
6498 """Return the status of a job of the requesting user.
6500 Args:
6501 req: Web request.
6502 p: Job request.
6504 Returns:
6505 The job status.
6507 Raises:
6508 ``gws.NotFoundError``: If the job does not exist or belongs to another user.
6509 """
6511 def handle_cancel_request(self, req: 'WebRequester', p: JobRequest) -> JobStatusResponse:
6512 """Cancel a job of the requesting user.
6514 Args:
6515 req: Web request.
6516 p: Job request.
6518 Returns:
6519 The job status after cancelling.
6521 Raises:
6522 ``gws.NotFoundError``: If the job does not exist or belongs to another user.
6523 """
6525 def job_status_response(self, job: Job, **kwargs) -> 'JobStatusResponse':
6526 """Create a status response for a job.
6528 Args:
6529 job: The job.
6530 **kwargs: Extra or overriding response fields.
6532 Returns:
6533 The status response.
6534 """
6535################################################################################
6538################################################################################
6539# /base/ows/types.pyinc
6542import gws
6545class OwsProtocol(Enum):
6546 """Supported OWS protocols."""
6548 WMS = 'WMS'
6549 WMTS = 'WMTS'
6550 WCS = 'WCS'
6551 WFS = 'WFS'
6552 CSW = 'CSW'
6555class OwsAuthorization(Data):
6556 """Credentials for accessing an OWS service."""
6558 type: str
6559 """Authorization type, ``basic`` or ``token``."""
6560 username: str
6561 """User name."""
6562 password: str
6563 """Password."""
6564 header: str
6565 """HTTP header that carries the token."""
6566 prefix: str
6567 """Prefix expected before the token in the header value."""
6568 token: str
6569 """Authorization token."""
6573class OwsVerb(Enum):
6574 """OWS request type."""
6576 CreateStoredQuery = 'CreateStoredQuery'
6577 DescribeCoverage = 'DescribeCoverage'
6578 DescribeFeatureType = 'DescribeFeatureType'
6579 DescribeLayer = 'DescribeLayer'
6580 DescribeRecord = 'DescribeRecord'
6581 DescribeStoredQueries = 'DescribeStoredQueries'
6582 DropStoredQuery = 'DropStoredQuery'
6583 GetCapabilities = 'GetCapabilities'
6584 GetFeature = 'GetFeature'
6585 GetFeatureInfo = 'GetFeatureInfo'
6586 GetFeatureWithLock = 'GetFeatureWithLock'
6587 GetLegendGraphic = 'GetLegendGraphic'
6588 GetMap = 'GetMap'
6589 GetPrint = 'GetPrint'
6590 GetPropertyValue = 'GetPropertyValue'
6591 GetRecordById = 'GetRecordById'
6592 GetRecords = 'GetRecords'
6593 GetTile = 'GetTile'
6594 ListStoredQueries = 'ListStoredQueries'
6595 LockFeature = 'LockFeature'
6596 Transaction = 'Transaction'
6599class OwsOperation(Data):
6600 """OWS operation, as offered by a remote service or by our own service."""
6602 allowedParameters: dict[str, list[str]]
6603 """Allowed values for parameters, keyed by the upper-cased parameter name."""
6604 constraints: dict[str, list[str]]
6605 """Operation constraints."""
6606 defaultMimeType: str
6607 """Output MIME type to use in requests that do not specify one (client side)."""
6608 handlerName: str
6609 """Name of the service method that handles this operation (server side)."""
6610 mimeTypeMap: dict[str, str]
6611 """Normalized MIME types mapped to the spelling of the remote service, if it differs (client side)."""
6612 mimeTypes: list[str]
6613 """Supported output MIME types, normalized."""
6614 params: dict[str, str]
6615 """Extra parameters for GET requests (client side)."""
6616 postUrl: Url
6617 """URL for POST requests."""
6618 url: Url
6619 """URL for GET requests."""
6620 verb: OwsVerb
6621 """Request type."""
6624class OwsCapabilities(Data):
6625 """Parsed capabilities of a remote OWS service."""
6627 metadata: 'Metadata'
6628 """Service metadata."""
6629 operations: list['OwsOperation']
6630 """Operations offered by the service."""
6631 sourceLayers: list['SourceLayer']
6632 """Layers or feature types of the service."""
6633 tileMatrixSets: list['TileMatrixSet']
6634 """Tile matrix sets (WMTS)."""
6635 version: str
6636 """Service version."""
6639class OwsService(Node):
6640 """OWS service provided by GBD WebSuite."""
6642 isRasterService: bool = False
6643 """Service provides raster services."""
6644 isVectorService: bool = False
6645 """Service provides vector services."""
6646 isOwsCommon: bool = False
6647 """Conforms to OGC Web Services Common Standard."""
6649 alwaysXY: bool
6650 """Force lon/lat order for geographic projections."""
6651 metadata: 'Metadata'
6652 """Service metadata."""
6653 name: str
6654 """Service name."""
6655 project: Optional['Project']
6656 """Project this service is configured for."""
6657 rootLayer: Optional['Layer']
6658 """Root layer of the service."""
6659 protocol: OwsProtocol
6660 """Supported protocol."""
6661 defaultFeatureCount: int
6662 """Default limit of features per page."""
6663 maxFeatureCount: int
6664 """Max limit of features per page."""
6665 searchTolerance: UomValue
6666 """Default tolerance for spatial search."""
6667 supportedBounds: list[Bounds]
6668 """Supported bounds."""
6669 supportedVersions: list[str]
6670 """Supported versions."""
6671 supportedOperations: list['OwsOperation']
6672 """Supported operations."""
6673 templates: list['Template']
6674 """Service templates."""
6675 imageFormats: list[ImageFormat]
6676 """Supported image formats."""
6677 updateSequence: str
6678 """Service update sequence."""
6679 withInspireMeta: bool
6680 """Include INSPIRE metadata."""
6681 withStrictParams: bool
6682 """Strict parameter checking."""
6684 def handle_request(self, req: 'WebRequester') -> ContentResponse:
6685 """Handle a service request.
6687 Errors are returned as OWS exception documents, not raised.
6689 Args:
6690 req: Web request.
6692 Returns:
6693 The service response.
6694 """
6696 def layer_is_compatible(self, layer: 'Layer') -> bool:
6697 """Check if a layer can be used in this service.
6699 Args:
6700 layer: Layer object.
6702 Returns:
6703 ``True`` if the layer can be published by this service.
6704 """
6707class OwsServiceProvider(Node):
6708 """Remote OWS service used as a data provider."""
6710 alwaysXY: bool
6711 """Force XY axis order for CRSs with lat/lon axis order."""
6712 authorization: Optional['OwsAuthorization']
6713 """Credentials for the service."""
6714 bounds: Optional[Bounds]
6715 """Service bounds, if known."""
6716 forceCrs: 'Crs'
6717 """CRS to use for requests, if configured."""
6718 maxRequests: int
6719 """Max. number of concurrent requests to the service."""
6720 metadata: 'Metadata'
6721 """Service metadata."""
6722 operations: list['OwsOperation']
6723 """Operations offered by the service."""
6724 protocol: 'OwsProtocol'
6725 """Service protocol."""
6726 sourceLayers: list['SourceLayer']
6727 """Layers or feature types of the service."""
6728 url: Url
6729 """Service URL."""
6730 version: str
6731 """Service version."""
6732 wgsExtent: Optional[Extent]
6733 """Service extent in WGS84, if known."""
6735 def get_operation(self, verb: 'OwsVerb', method: Optional['RequestMethod'] = None) -> Optional['OwsOperation']:
6736 """Find an operation by its verb.
6738 Args:
6739 verb: Request type.
6740 method: Request method. For ``POST``, the operation must have a POST URL,
6741 otherwise a GET URL.
6743 Returns:
6744 The operation, or ``None`` if the service does not support it.
6745 """
6747 def get_features(self, args: 'SearchQuery', source_layers: list['SourceLayer'], mime: MimeType = '') -> list['FeatureRecord']:
6748 """Search for features in the given source layers.
6750 Args:
6751 args: Search query.
6752 source_layers: Source layers to search.
6753 mime: Response MIME type to request, the default of the operation if empty.
6755 Returns:
6756 Found feature records.
6757 """
6758################################################################################
6761################################################################################
6762# /base/printer/types.pyinc
6765class PrintPlaneType(Enum):
6766 """Print plane type."""
6768 bitmap = 'bitmap'
6769 """Raw bitmap data."""
6770 url = 'url'
6771 """Image given as a data URL."""
6772 features = 'features'
6773 """Features sent by the client."""
6774 raster = 'raster'
6775 """Raster layer."""
6776 vector = 'vector'
6777 """Vector layer, rendered as SVG."""
6778 soup = 'soup'
6779 """SVG soup: points and SVG tags."""
6782class PrintPlane(Data):
6783 """Print plane, a single map layer in a print request."""
6785 type: PrintPlaneType
6786 """Plane type."""
6788 opacity: Optional[float]
6789 """Plane opacity, from 0 to 1."""
6790 cssSelector: Optional[str]
6791 """CSS selector of the style for vector layers and features."""
6793 bitmapData: Optional[bytes]
6794 """Raw pixel data, for bitmap planes."""
6795 bitmapMode: Optional[str]
6796 """Pixel mode of the bitmap, ``RGBA`` or ``RGB``."""
6797 bitmapWidth: Optional[int]
6798 """Bitmap width in pixels."""
6799 bitmapHeight: Optional[int]
6800 """Bitmap height in pixels."""
6802 url: Optional[str]
6803 """Data URL of the image, for url planes."""
6805 features: Optional[list['FeatureProps']]
6806 """Features, for features planes."""
6808 layerUid: Optional[str]
6809 """Layer uid, for raster and vector planes."""
6810 compositeLayerUids: Optional[list[str]]
6811 """Uids of the sub-layers to render, for composite raster layers."""
6813 soupPoints: Optional[list[Point]]
6814 """Points, for soup planes."""
6815 soupTags: Optional[list[Any]]
6816 """SVG tags, for soup planes."""
6819class PrintMap(Data):
6820 """Map properties for printing."""
6822 backgroundColor: Optional[int]
6823 """Background color."""
6824 bbox: Optional[Extent]
6825 """Map extent."""
6826 center: Optional[Point]
6827 """Map center."""
6828 planes: list[PrintPlane]
6829 """Map planes."""
6830 rotation: Optional[int]
6831 """Map rotation in degrees."""
6832 scale: int
6833 """Map scale denominator."""
6834 styles: Optional[list['StyleProps']]
6835 """Styles used by the planes."""
6836 visibleLayers: Optional[list[str]]
6837 """Uids of the visible layers."""
6840class PrintRequestType(Enum):
6841 """Type of the print request."""
6843 template = 'template'
6844 map = 'map'
6847class PrintRequest(Request):
6848 """Print request."""
6850 type: PrintRequestType
6851 """Request type."""
6853 args: Optional[dict]
6854 """Template arguments."""
6855 crs: Optional[CrsName]
6856 """CRS of the maps, the project CRS by default."""
6857 outputFormat: Optional[str]
6858 """Output format, ``pdf`` (default) or ``png``, or the mime type."""
6859 maps: Optional[list[PrintMap]]
6860 """Maps to print."""
6862 printerUid: Optional[str]
6863 """Printer uid, for template requests."""
6864 dpi: Optional[int]
6865 """Output resolution."""
6866 outputSize: Optional[Size]
6867 """Output size in screen pixels, for map requests."""
6870class PrintResult(Data):
6871 """Print result."""
6873 path: str
6874 """Path of the output file."""
6875 mimeType: str
6876 """Mime type of the output file."""
6879class Printer(Node):
6880 """Printer, a print template offered to users."""
6882 title: str
6883 """Printer title."""
6884 template: 'Template'
6885 """Template that renders the print output."""
6886 models: list['Model']
6887 """Models whose fields are shown as input fields in the print dialog."""
6888 qualityLevels: list['TemplateQualityLevel']
6889 """Quality levels users can choose from."""
6892class PrinterManager(Node):
6893 """Print manager."""
6895 def start_print_job(self, request: PrintRequest, user: 'User') -> 'JobStatusResponse':
6896 """Start a background print job.
6898 Args:
6899 request: Print request.
6900 user: User who requested the print.
6902 Returns:
6903 The status of the new job.
6904 """
6906 def exec_print(self, request: PrintRequest, out_path: str):
6907 """Execute a print request synchronously, as the system user.
6909 Args:
6910 request: Print request.
6911 out_path: Path to copy the output file to.
6912 """
6913################################################################################
6916################################################################################
6917# /base/project/types.pyinc
6920class Client(Node):
6921 """Settings for the browser client: UI elements and client options."""
6923 options: dict
6924 """Client options."""
6925 elements: list
6926 """Client UI elements."""
6929class Project(Node):
6930 """Project: a map application with its own map, actions, templates and services."""
6932 assetsRoot: Optional['WebDocumentRoot']
6933 """Project assets directory, checked before the global assets directory."""
6934 client: 'Client'
6935 """Project client settings, replacing the application client."""
6937 localeUids: list[str]
6938 """Locales of the project."""
6939 map: 'Map'
6940 """Main map of the project."""
6941 metadata: 'Metadata'
6942 """Project metadata."""
6943 title: str
6944 """Project title."""
6946 actions: list['Action']
6947 """Actions available only in this project."""
6948 finders: list['Finder']
6949 """Search providers of the project."""
6950 models: list['Model']
6951 """Data models of the project."""
6952 exporters: list['Exporter']
6953 """Exporters of the project."""
6954 printers: list['Printer']
6955 """Printers of the project."""
6956 templates: list['Template']
6957 """Templates of the project."""
6958 owsServices: list['OwsService']
6959 """OWS services published for the project."""
6961 vars: dict
6962 """Custom variables."""
6963################################################################################
6966################################################################################
6967# /base/search/types.pyinc
6970class SearchSort(Data):
6971 """Search sort specification."""
6973 fieldName: str
6974 """Field name to sort by."""
6975 reverse: bool
6976 """Sort in descending order."""
6979class SearchFilterOperator(Enum):
6980 """Search filter operator, as defined in OGC Filter Encoding 2.0."""
6982 And = 'And'
6983 """All sub-filters match."""
6984 Or = 'Or'
6985 """At least one sub-filter matches."""
6986 Not = 'Not'
6987 """The sub-filter does not match."""
6989 PropertyIsEqualTo = 'PropertyIsEqualTo'
6990 """Property is equal to the value."""
6991 PropertyIsNotEqualTo = 'PropertyIsNotEqualTo'
6992 """Property is not equal to the value."""
6993 PropertyIsLessThan = 'PropertyIsLessThan'
6994 """Property is less than the value."""
6995 PropertyIsGreaterThan = 'PropertyIsGreaterThan'
6996 """Property is greater than the value."""
6997 PropertyIsLessThanOrEqualTo = 'PropertyIsLessThanOrEqualTo'
6998 """Property is less than or equal to the value."""
6999 PropertyIsGreaterThanOrEqualTo = 'PropertyIsGreaterThanOrEqualTo'
7000 """Property is greater than or equal to the value."""
7001 PropertyIsLike = 'PropertyIsLike'
7002 """Property matches a pattern."""
7003 PropertyIsNull = 'PropertyIsNull'
7004 """Property is null."""
7005 PropertyIsNil = 'PropertyIsNil'
7006 """Property is nil."""
7007 PropertyIsBetween = 'PropertyIsBetween'
7008 """Property is between two values."""
7010 Equals = 'Equals'
7011 """Geometry is equal to the shape."""
7012 Disjoint = 'Disjoint'
7013 """Geometry does not intersect the shape."""
7014 Touches = 'Touches'
7015 """Geometry touches the shape."""
7016 Within = 'Within'
7017 """Geometry is within the shape."""
7018 Overlaps = 'Overlaps'
7019 """Geometry overlaps the shape."""
7020 Crosses = 'Crosses'
7021 """Geometry crosses the shape."""
7022 Intersects = 'Intersects'
7023 """Geometry intersects the shape."""
7024 Contains = 'Contains'
7025 """Geometry contains the shape."""
7026 DWithin = 'DWithin'
7027 """Geometry is within a distance of the shape."""
7028 Beyond = 'Beyond'
7029 """Geometry is beyond a distance of the shape."""
7030 BBOX = 'BBOX'
7031 """Geometry intersects the bounding box."""
7034class SearchFilterMatchAction(Enum):
7035 """How a filter is applied to a multi-valued property."""
7037 All = 'All'
7038 """All values must match."""
7039 Any = 'Any'
7040 """At least one value must match."""
7041 One = 'One'
7042 """Exactly one value must match."""
7045class SearchFilter(Data):
7046 """Search filter, a tree of filter operators."""
7048 operator: SearchFilterOperator
7049 """Filter operator."""
7050 property: str
7051 """Property name for comparison and spatial operators."""
7052 value: str
7053 """Value for comparison operators."""
7054 shape: 'Shape'
7055 """Shape for spatial operators."""
7056 subFilters: list['SearchFilter']
7057 """Operands of logical operators."""
7058 matchCase: bool
7059 """Compare strings case-sensitively."""
7060 matchAction: SearchFilterMatchAction
7061 """How to match multi-valued properties."""
7062 wildCard: str
7063 """Wildcard character for ``PropertyIsLike``."""
7064 singleChar: str
7065 """Single character placeholder for ``PropertyIsLike``."""
7066 escapeChar: str
7067 """Escape character for ``PropertyIsLike``."""
7070class SearchQuery(Data):
7071 """Search query."""
7073 bounds: Bounds
7074 """Search bounds."""
7075 extraArgs: dict
7076 """Extra arguments for custom searches."""
7077 extraColumns: list
7078 """Extra columns to select."""
7079 extraParams: dict
7080 """Extra parameters to pass to a provider."""
7081 extraWhere: list
7082 """Extra where clauses."""
7083 keyword: str
7084 """Keyword to search for."""
7085 layers: list['Layer']
7086 """Layers to search in."""
7087 limit: int
7088 """Limit the number of results."""
7089 filter: SearchFilter
7090 """Search filter."""
7091 project: 'Project'
7092 """Project to search in."""
7093 resolution: float
7094 """Pixel resolution for geometry search."""
7095 shape: 'Shape'
7096 """Shape to search in."""
7097 sort: list[SearchSort]
7098 """Sort options."""
7099 tolerance: 'UomValue'
7100 """Tolerance for geometry search."""
7101 uids: list[str]
7102 """UIDs to search for."""
7105class SearchResult(Data):
7106 """Search result."""
7108 feature: 'Feature'
7109 """Found feature."""
7110 layer: 'Layer'
7111 """Layer whose finder found the feature, or ``None`` for project and application finders."""
7112 finder: 'Finder'
7113 """Finder that found the feature."""
7116class TextSearchType(Enum):
7117 """Text search type."""
7119 exact = 'exact'
7120 """Match the whole string."""
7121 begin = 'begin'
7122 """Match the beginning of the string."""
7123 end = 'end'
7124 """Match the end of the string."""
7125 any = 'any'
7126 """Match any substring."""
7127 like = 'like'
7128 """Use the percent sign as a placeholder."""
7131class TextSearchOptions(Data):
7132 """How keywords are matched against a text field."""
7134 type: TextSearchType
7135 """Type of the search."""
7136 minLength: int = 0
7137 """Min. keyword length."""
7138 caseSensitive: bool = False
7139 """Use case-sensitive search."""
7142class SortOptions(Data):
7143 """Sort order for features."""
7145 fieldName: str
7146 """Field name to sort by."""
7147 reverse: bool = False
7148 """Sort in descending order."""
7151class SearchManager(Node):
7152 """Search manager, runs search queries through the finders."""
7154 def run_search(self, search: 'SearchQuery', user: 'User') -> list['SearchResult']:
7155 """Run a search query.
7157 Runs the finders of the query layers, the project finders and the application
7158 finders the user may use and which can run the query.
7160 Args:
7161 search: Search query.
7162 user: User running the search.
7164 Returns:
7165 Search results, at most ``search.limit`` if a limit is given.
7166 """
7169class Finder(Node):
7170 """Search provider, finds features for search queries."""
7172 title: str
7173 """Finder title."""
7174 category: str
7175 """Category assigned to the results."""
7177 supportsFilterSearch: bool = False
7178 """The finder supports filter searches."""
7179 supportsGeometrySearch: bool = False
7180 """The finder supports geometry searches."""
7181 supportsKeywordSearch: bool = False
7182 """The finder supports keyword searches."""
7184 withFilter: bool
7185 """Filter searches are enabled."""
7186 withGeometry: bool
7187 """Geometry searches are enabled."""
7188 withKeyword: bool
7189 """Keyword searches are enabled."""
7191 templates: list['Template']
7192 """Templates to format the found features."""
7193 models: list['Model']
7194 """Models used to read the features."""
7195 sourceLayers: list['SourceLayer']
7196 """Source layers to search in, for finders of OWS and QGIS sources."""
7198 tolerance: 'UomValue'
7199 """Tolerance for geometry searches."""
7201 def run(self, search: SearchQuery, user: 'User', layer: Optional['Layer'] = None) -> list['Feature']:
7202 """Run a search query.
7204 Args:
7205 search: Search query.
7206 user: User running the search.
7207 layer: Layer the finder belongs to, if any.
7209 Returns:
7210 Found features.
7211 """
7213 def can_run(self, search: SearchQuery, user: 'User') -> bool:
7214 """Check if the finder can run a search query.
7216 Args:
7217 search: Search query.
7218 user: User running the search.
7220 Returns:
7221 ``True`` if the finder can run the query.
7222 """
7223################################################################################
7226################################################################################
7227# /base/storage/types.pyinc
7230class StorageManager(Node):
7231 """Storage manager, holds the storage providers."""
7233 providers: list['StorageProvider']
7234 """Configured storage providers."""
7236 def create_provider(self, cfg: Config, **kwargs) -> 'StorageProvider':
7237 """Create a storage provider and add it to the manager.
7239 A provider with the same uid replaces the existing one.
7241 Args:
7242 cfg: Provider configuration.
7243 **kwargs: Extra configuration values.
7245 Returns:
7246 The new provider.
7247 """
7249 def find_provider(self, uid: Optional[str] = None) -> Optional['StorageProvider']:
7250 """Find a storage provider.
7252 Args:
7253 uid: Provider uid. If not given, the first provider is returned.
7255 Returns:
7256 The provider, or ``None`` if not found.
7257 """
7261class StorageRecord(Data):
7262 """Storage record."""
7264 name: str
7265 """Record name."""
7266 userUid: str
7267 """Uid of the user who last wrote the record."""
7268 data: str
7269 """Serialized record data."""
7270 created: 'datetime.datetime'
7271 """Record create time."""
7272 updated: 'datetime.datetime'
7273 """Record update time."""
7276class StorageProvider(Node):
7277 """Storage provider, stores named records grouped by category."""
7279 def list_names(self, category: str) -> list[str]:
7280 """List the record names in a category.
7282 Args:
7283 category: Category name.
7285 Returns:
7286 Record names.
7287 """
7289 def read(self, category: str, name: str) -> Optional['StorageRecord']:
7290 """Read a record.
7292 Args:
7293 category: Category name.
7294 name: Record name.
7296 Returns:
7297 The record, or ``None`` if not found.
7298 """
7300 def write(self, category: str, name: str, data: str, user_uid: str):
7301 """Create a record or update an existing one.
7303 Args:
7304 category: Category name.
7305 name: Record name.
7306 data: Serialized record data.
7307 user_uid: Uid of the user who writes the record.
7308 """
7310 def delete(self, category: str, name: str):
7311 """Delete a record.
7313 Args:
7314 category: Category name.
7315 name: Record name.
7316 """
7317################################################################################
7320################################################################################
7321# /base/template/types.pyinc
7324class TemplateArgs(Data):
7325 """Template arguments."""
7327 app: 'Application'
7328 """Application object."""
7329 locale: 'Locale'
7330 """Current locale."""
7331 date: 'DateFormatter'
7332 """Locale-aware date formatter."""
7333 time: 'TimeFormatter'
7334 """Locale-aware time formatter."""
7335 number: 'NumberFormatter'
7336 """Locale-aware number formatter."""
7339class TemplateRenderInput(Data):
7340 """Template render input."""
7342 args: dict | Data
7343 """Template arguments."""
7344 crs: 'Crs'
7345 """CRS for maps."""
7346 dpi: int
7347 """Output resolution in dots per inch."""
7348 locale: 'Locale'
7349 """Locale for the output."""
7350 maps: list[MapRenderInput]
7351 """Maps to render, for print templates."""
7352 mimeOut: str
7353 """Requested output MIME type."""
7354 notify: Callable
7355 """Callback for progress messages."""
7356 project: 'Project'
7357 """Current project."""
7358 user: 'User'
7359 """Current user."""
7362class TemplateQualityLevel(Config):
7363 """Print quality level users can choose."""
7365 name: str
7366 """Quality level name shown to users."""
7367 dpi: int
7368 """Print resolution in dots per inch."""
7371class Template(Node):
7372 """Template, generates content from data."""
7374 mapSize: UomSize
7375 """Default map size for the template."""
7376 mimeTypes: list[str]
7377 """MIME types the template can generate."""
7378 pageSize: UomSize
7379 """Default page size for printing."""
7380 pageMargin: UomExtent
7381 """Default page margin for printing."""
7382 subject: str
7383 """Template subject, the purpose the template serves, like ``feature.description``."""
7384 title: str
7385 """Template title."""
7387 def render(self, tri: TemplateRenderInput) -> ContentResponse:
7388 """Render the template.
7390 Args:
7391 tri: Render input.
7393 Returns:
7394 A response with the generated content.
7395 """
7398class TemplateManager(Node):
7399 """Template manager, finds templates by subject and creates them from files."""
7401 def find_templates(self, subjects: list[str], where: list[Node], user: 'User' = None, mime: MimeType = None) -> list['Template']:
7402 """Find templates for several subjects.
7404 Args:
7405 subjects: Template subjects.
7406 where: Objects whose templates are searched, in this order.
7407 user: If given, only templates this user can use.
7408 mime: If given, only templates which can produce this MIME type.
7410 Returns:
7411 Found templates, one per subject at most.
7412 """
7414 def find_template(self, subject: str, where: list[Node], user: 'User' = None, mime: MimeType = None) -> Optional['Template']:
7415 """Find a template for a subject.
7417 The templates of the objects in ``where`` are searched in the given order,
7418 then the application templates. A template without ``mimeTypes`` matches any
7419 MIME type.
7421 Args:
7422 subject: Template subject.
7423 where: Objects whose templates are searched, in this order.
7424 user: If given, only templates this user can use.
7425 mime: If given, only templates which can produce this MIME type.
7427 Returns:
7428 The first matching template, or ``None``.
7429 """
7431 def template_from_path(self, path: str) -> Optional['Template']:
7432 """Create a template from a file.
7434 The template type is derived from the file extension.
7436 Args:
7437 path: File path.
7439 Returns:
7440 A template, or ``None`` if the file is not a template.
7441 """
7442################################################################################
7445################################################################################
7446# /base/web/types.pyinc
7449class RequestMethod(Enum):
7450 """Web request method."""
7452 GET = 'GET'
7453 HEAD = 'HEAD'
7454 POST = 'POST'
7455 PUT = 'PUT'
7456 DELETE = 'DELETE'
7457 CONNECT = 'CONNECT'
7458 OPTIONS = 'OPTIONS'
7459 TRACE = 'TRACE'
7460 PATCH = 'PATCH'
7463class WebRequester:
7464 """Web requester, gives access to an incoming web request."""
7466 environ: dict
7467 """Request environment."""
7468 method: RequestMethod
7469 """Request method."""
7470 contentType: str
7471 """Request content type."""
7472 root: 'Root'
7473 """Object tree root."""
7474 site: 'WebSite'
7475 """Website the request is processed for."""
7477 session: 'AuthSession'
7478 """Current session."""
7479 user: 'User'
7480 """Current user."""
7482 isGet: bool
7483 """The request is a GET request."""
7484 isPost: bool
7485 """The request is a POST request."""
7486 isApi: bool
7487 """The request provides json data in the POST body."""
7488 isForm: bool
7489 """The request provides form data in the POST body."""
7490 isSecure: bool
7491 """The request is made over https."""
7493 scheme: str
7494 """Request scheme, http or https."""
7495 host: str
7496 """Request host name, without the port, empty if the host is invalid."""
7497 port: int
7498 """Request port, 0 if not given."""
7499 ip: str
7500 """Client address."""
7502 def parse(self):
7503 """Parse the request path, the parameters and the structured payload.
7505 Also determines the scheme, host, port and client address, taking proxy
7506 headers into account if the site has proxies.
7508 Raises:
7509 ``gws.base.web.error.HTTPException``: If the request path, the host or the payload is invalid.
7510 """
7512 def params(self) -> dict:
7513 """Return the GET parameters.
7515 Returns:
7516 Parameters from the query string and from the request path.
7517 """
7519 def query_params(self) -> dict:
7520 """Return the GET parameters from the query string.
7522 Returns:
7523 Query string parameters.
7524 """
7526 def path(self) -> str:
7527 """Return the request path after the command.
7529 Returns:
7530 The rest of the path after ``/_/<command>/``.
7531 """
7533 def struct(self) -> dict:
7534 """Return the structured payload of an API request.
7536 Returns:
7537 The decoded JSON or MessagePack payload.
7538 """
7540 def command(self) -> str:
7541 """Return the command name.
7543 Returns:
7544 The command from the path, or from the ``cmd`` parameter.
7545 """
7547 def data(self) -> bytes:
7548 """Return the raw POST data, unzipped if gzip-encoded.
7550 Returns:
7551 POST data, empty for non-POST requests.
7553 Raises:
7554 ``gws.base.web.error.HTTPException``: If the content length is invalid or too large, or the data cannot be unzipped.
7555 """
7557 def form(self) -> list[tuple[str, Any]]:
7558 """Return the POST form data.
7560 Returns:
7561 A list of ``(key, value)`` tuples, including uploaded files; empty if the request is not a form.
7563 Raises:
7564 ``gws.base.web.error.HTTPException``: If the form data cannot be decoded.
7565 """
7567 def text(self) -> str:
7568 """Return the POST data decoded to text, with the charset of the request.
7570 Returns:
7571 POST data as text.
7573 Raises:
7574 ``gws.base.web.error.HTTPException``: If the data cannot be decoded.
7575 """
7577 def cookie(self, key: str, default: str = '') -> str:
7578 """Get a cookie.
7580 Args:
7581 key: Cookie name.
7582 default: Default value.
7584 Returns:
7585 A cookie value.
7586 """
7588 def header(self, key: str, default: str = '') -> str:
7589 """Get a header.
7591 Args:
7592 key: Header name.
7593 default: Default value.
7595 Returns:
7596 A header value.
7597 """
7599 def has_param(self, key: str) -> bool:
7600 """Check if a GET parameter exists, ignoring case.
7602 Args:
7603 key: Parameter name.
7605 Returns:
7606 ``True`` if the parameter exists.
7607 """
7609 def param(self, key: str, default: str = '') -> str:
7610 """Get a GET parameter, ignoring case.
7612 Args:
7613 key: Parameter name.
7614 default: Default value.
7616 Returns:
7617 A parameter value.
7618 """
7620 def env(self, key: str, default: str = '') -> str:
7621 """Get a WSGI environment variable.
7623 Args:
7624 key: Variable name.
7625 default: Default value.
7627 Returns:
7628 A variable value.
7629 """
7631 def content_responder(self, response: ContentResponse) -> 'WebResponder':
7632 """Create a responder for a content response.
7634 Args:
7635 response: Response with literal content or a content path.
7637 Returns:
7638 A responder.
7639 """
7641 def redirect_responder(self, response: RedirectResponse) -> 'WebResponder':
7642 """Create a responder for a redirect response.
7644 Args:
7645 response: Redirect response.
7647 Returns:
7648 A responder.
7649 """
7651 def api_responder(self, response: Response) -> 'WebResponder':
7652 """Create a responder for an API (structured) response.
7654 The response is encoded as JSON or MessagePack, depending on the request.
7656 Args:
7657 response: Response object.
7659 Returns:
7660 A responder.
7661 """
7663 def error_responder(self, exc: Exception) -> 'WebResponder':
7664 """Create a responder for an exception.
7666 Args:
7667 exc: An exception; anything but an HTTP exception results in a 500 response.
7669 Returns:
7670 A responder.
7671 """
7673 def absolute_url_for(self, request_path: str, **params) -> str:
7674 """Create an absolute URL pointing to the requested host.
7676 Args:
7677 request_path: Request path.
7678 **params: Additional GET parameters.
7680 Returns:
7681 A URL.
7682 """
7684 def relative_url_for(self, request_path: str, **params) -> str:
7685 """Create a host-relative URL.
7687 Args:
7688 request_path: Request path.
7689 **params: Additional GET parameters.
7691 Returns:
7692 A URL.
7693 """
7695 def canonical_url_for(self, request_path: str, **params) -> str:
7696 """Create an absolute URL pointing to the canonical host.
7698 Args:
7699 request_path: Request path.
7700 **params: Additional GET parameters.
7702 Returns:
7703 A URL.
7704 """
7706 def set_session(self, session: 'AuthSession'):
7707 """Attach a session to the requester and set the user from it.
7709 Args:
7710 session: A session object.
7711 """
7714class WebResponder:
7715 """Web responder, builds and sends the response to a web request."""
7717 status: int
7718 """Response status."""
7720 def send_response(self, environ: dict, start_response: Callable):
7721 """Send the response to the client.
7723 Args:
7724 environ: WSGI environment.
7725 start_response: WSGI ``start_response`` function.
7727 Returns:
7728 The WSGI response iterable.
7729 """
7731 def set_cookie(self, key: str, value: str, **kwargs):
7732 """Set a cookie.
7734 Args:
7735 key: Cookie name.
7736 value: Cookie value.
7737 **kwargs: Cookie options.
7738 """
7740 def delete_cookie(self, key: str, **kwargs):
7741 """Delete a cookie.
7743 Args:
7744 key: Cookie name.
7745 **kwargs: Cookie options.
7746 """
7748 def set_status(self, status: int):
7749 """Set the response status.
7751 Args:
7752 status: HTTP status code.
7753 """
7755 def add_header(self, key: str, value: str):
7756 """Add a header.
7758 Args:
7759 key: Header name.
7760 value: Header value.
7761 """
7763 def set_body(self, body: str | bytes):
7764 """Set the response body.
7766 Args:
7767 body: New response body; strings are encoded as UTF-8.
7768 """
7771class WebDocumentRoot(Data):
7772 """Directory served over the web."""
7774 dir: DirPath
7775 """Local directory."""
7776 allowMime: list[str]
7777 """Allowed mime types."""
7778 denyMime: list[str]
7779 """Restricted mime types."""
7782class WebRewriteRule(Data):
7783 """URL rewrite rule."""
7785 pattern: Regex
7786 """URL matching pattern."""
7787 target: str
7788 """Rule target, with ``$1``, ``$2`` etc. placeholders for the pattern groups."""
7789 reversed: bool
7790 """The rule rewrites URLs generated by the server, not incoming URLs."""
7793class WebCors(Data):
7794 """CORS options."""
7796 allowCredentials: bool
7797 """Allow credentials in cross-origin requests."""
7798 allowHeaders: str
7799 """Headers allowed in cross-origin requests."""
7800 allowMethods: str
7801 """Methods allowed in cross-origin requests."""
7802 allowOrigin: str
7803 """Origins allowed to make cross-origin requests."""
7806class WebManager(Node):
7807 """Web manager, holds the web site."""
7809 site: 'WebSite'
7810 """Configured web site."""
7813class WebSite(Node):
7814 """Web site the server responds to."""
7816 assetsRoot: Optional[WebDocumentRoot]
7817 """Root directory for assets."""
7818 canonicalHost: str
7819 """Host name for absolute canonical URLs."""
7820 corsOptions: WebCors
7821 """CORS options."""
7822 hostnames: list[str]
7823 """Host names this site responds to."""
7824 rewriteRules: list[WebRewriteRule]
7825 """URL rewrite rules."""
7826 proxyCount: int
7827 """Number of proxies in front of the server."""
7828 ssl: bool
7829 """The site is served over https."""
7830 staticRoot: WebDocumentRoot
7831 """Root directory for static files."""
7833 def url_for(self, req: 'WebRequester', path: str, mode: str, **params) -> str:
7834 """Create a URL for a request path, applying the reversed rewrite rules.
7836 If the path, or the rewritten path, is an absolute URL, only the parameters
7837 are added. In the ``absolute`` and ``canonical`` modes, the URL gets the scheme
7838 of the request. The host is the canonical host in the ``canonical`` mode, and
7839 the request host and port otherwise or if there is no canonical host.
7841 Args:
7842 req: Web requester.
7843 path: Request path.
7844 mode: ``absolute``, ``relative`` or ``canonical``.
7845 **params: Extra GET parameters.
7847 Returns:
7848 A URL.
7850 Raises:
7851 ``gws.BadRequestError``: If an absolute URL is requested and there is no host.
7852 """
7853################################################################################
7856################################################################################
7857# /base/exporter/types.pyinc
7860class ExportArgs(Data):
7861 """Arguments passed to ``Exporter.run``."""
7863 exporter: 'Exporter'
7864 """The exporter."""
7865 features: Optional[list['Feature']]
7866 """Features to export."""
7867 shape: Optional['Shape']
7868 """Shape from the export request."""
7869 project: 'Project'
7870 """Project of the export request."""
7871 user: 'User'
7872 """User the export runs for."""
7873 notify: Callable
7874 """Progress callback, called with an event name."""
7875 maxErrors: int = 100
7876 """Maximum number of errors collected in the result."""
7879class ExportTarget(Enum):
7880 """Export target."""
7882 file = 'file'
7883 """Save the export result to a file on the server."""
7884 download = 'download'
7885 """Return the export result for download."""
7888class ExportResult(Data):
7889 """Export result."""
7891 path: str
7892 """Path of the result file, empty if nothing was exported."""
7893 mimeType: str
7894 """Mime type of the result file."""
7895 numFiles: int
7896 """Number of files written."""
7897 numFeaturesTotal: int
7898 """Number of requested features."""
7899 numFeaturesExported: int
7900 """Number of exported features."""
7901 errors: list[str]
7902 """Error messages for features that were not exported."""
7905class FeatureExportStrategy(Enum):
7906 """How exported features are obtained."""
7908 load = 'load'
7909 """Load features by ids from the source model."""
7910 client = 'client'
7911 """Export features using properties as received from the client."""
7914class ExportRequestType(Enum):
7915 """Kind of data to export."""
7917 vector = 'vector'
7918 """Vector features."""
7919 raster = 'raster'
7920 """Raster data."""
7923class ExportRequest(Request):
7924 """Export request from the client."""
7926 type: ExportRequestType
7927 """Kind of data to export."""
7928 exporterUid: str
7929 """Uid of the exporter."""
7930 features: Optional[list['FeatureProps']]
7931 """Features to export."""
7932 shape: Optional['ShapeProps']
7933 """Shape passed to the exporter."""
7936class ExportResponse(Response):
7937 """Export response with the content of the result file."""
7939 content: str | bytes
7940 """File content."""
7941 contentFilename: str
7942 """File name."""
7943 mimeType: str
7944 """Mime type."""
7947class ExporterManager(Node):
7948 """Exporter manager."""
7950 def start_export_job(self, request: ExportRequest, user: 'User') -> 'JobStatusResponse':
7951 """Create and schedule a background export job.
7953 Args:
7954 request: Export request.
7955 user: User the export runs for.
7957 Returns:
7958 The status of the new job.
7959 """
7961 def exec_export(self, request: ExportRequest, out_path: str):
7962 """Run an export directly, as the system user, and copy the result file.
7964 Args:
7965 request: Export request.
7966 out_path: Path to copy the result file to.
7968 Returns:
7969 The export result.
7971 Raises:
7972 ``gws.Error``: If no features were exported.
7973 """
7975 def list_exporters(self, where: list['Node'], user: 'User') -> list['Exporter']:
7976 """List the exporters of the given objects that the user can use.
7978 Of several exporters with the same title, only the first one is listed.
7980 Args:
7981 where: Objects with an ``exporters`` list, e.g. a project and the application.
7982 ``None`` entries are ignored.
7983 user: User.
7985 Returns:
7986 A list of exporters.
7987 """
7989 def get_exporter(self, where: list['Node'], uid: str, user: 'User') -> Optional['Exporter']:
7990 """Find an exporter by uid among the exporters the user can use.
7992 Args:
7993 where: Objects with an ``exporters`` list, e.g. a project and the application.
7994 uid: Exporter uid.
7995 user: User.
7997 Returns:
7998 The exporter, or ``None`` if it is not found.
7999 """
8002class Exporter(Node):
8003 """Exporter.
8005 Writes features to files in a specific format.
8006 """
8008 title: str
8009 """Exporter title, shown in the client."""
8010 options: dict
8011 """Format-specific options, passed to the GDAL driver."""
8013 supportsVector: bool
8014 """The exporter can export vector features."""
8015 supportsRaster: bool
8016 """The exporter can export raster data."""
8017 supportsMultiLayer: bool
8018 """The format can hold several layers in one file."""
8020 withNoGeometry: bool
8021 """Export features without geometry instead of skipping them."""
8022 withMixedGeometry: bool
8023 """Allow different geometry types in one layer instead of skipping features."""
8024 withMixedCrs: bool
8025 """Allow different CRS in one layer instead of skipping features."""
8026 withMultiLayer: bool
8027 """Write all layers to one file."""
8029 supportedAttributeTypes: Optional[list[gws.AttributeType]]
8030 """Attribute types the exporter can write. If empty, the types supported by GDAL are used."""
8032 def run(self, ea: ExportArgs, er: ExportResult):
8033 """Export the features.
8035 Writes the result file and sets its path, the mime type, the counts
8036 and errors in the export result.
8038 Args:
8039 ea: Export arguments.
8040 er: Export result, filled by the exporter.
8041 """
8042################################################################################
8046################################################################################
8047# /base/application/types.pyinc
8050class MiddlewareManager(Node):
8051 """Middleware manager.
8053 Middleware objects process every web request: the web server calls
8054 ``enter_middleware`` on each of them in dependency order before the action,
8055 and ``exit_middleware`` in reverse order after it.
8056 """
8058 def register(self, obj: Node, name: str, depends_on: Optional[list[str]] = None):
8059 """Register an object as a middleware.
8061 Args:
8062 obj: The middleware object.
8063 name: Middleware name, for example ``db`` or ``auth``.
8064 depends_on: Names of middleware that must run before this one.
8065 """
8067 def objects(self) -> list[Node]:
8068 """Return the registered middleware objects in dependency order.
8070 Returns:
8071 A list of middleware objects, dependencies first.
8073 Raises:
8074 Error: If the dependencies are cyclic or refer to an unknown name.
8075 """
8078class TemplateOptions(Data):
8079 """Options for the built-in application and project home pages."""
8081 withLogin: bool = True
8082 """Show the login form on the home page."""
8083 footerText: Optional[str]
8084 """HTML text for the home page footer."""
8085 withGws: bool = True
8086 """Show the GWS logo in the home page footer."""
8087 homeResources: Optional[list[str]]
8088 """Extra resource URLs for the home page."""
8089 projectResources: Optional[list[str]]
8090 """Extra resource URLs for the project page."""
8093class Application(Node):
8094 """Application object.
8096 The top-level node of the configuration tree. It holds the managers, the
8097 global objects and the projects, and is available as ``root.app``.
8098 """
8100 client: 'Client'
8101 """Default client, used by projects without their own client configuration."""
8103 localeUids: list[str]
8104 """Default locale uids for all projects."""
8106 metadata: 'Metadata'
8107 """Application metadata."""
8109 monitor: 'ServerMonitor'
8110 """Server monitor, watches configuration files and runs periodic tasks."""
8112 templateOptions: TemplateOptions
8113 """Options for the built-in home page templates."""
8115 title: str
8116 """Application title."""
8118 vars: dict
8119 """Custom variables from the configuration."""
8121 version: str
8122 """Application version, for example ``8.5.3``."""
8124 versionString: str
8125 """Version string for display, with the revision if known."""
8127 def supported_crs(self) -> list['Crs']:
8128 """Return all CRS supported by the application.
8130 These are the CRS of all maps and the CRS supported by OWS services,
8131 plus the registered ones. The list is computed on the first call.
8133 Returns:
8134 A list of CRS objects, sorted by srid.
8135 """
8137 def register_supported_crs(self, crs: 'Crs'):
8138 """Register an additional supported CRS.
8140 Must be called during configuration.
8142 Args:
8143 crs: The CRS object.
8144 """
8146 defaultPrinter: 'Printer'
8147 """Default printer, used when no printer is configured."""
8149 actionMgr: 'ActionManager'
8150 """Action manager."""
8152 authMgr: 'AuthManager'
8153 """Authorization manager."""
8155 databaseMgr: 'DatabaseManager'
8156 """Database manager."""
8158 exporterMgr: 'ExporterManager'
8159 """Exporter manager."""
8161 jobMgr: 'JobManager'
8162 """Job manager."""
8164 middlewareMgr: 'MiddlewareManager'
8165 """Middleware manager."""
8167 modelMgr: 'ModelManager'
8168 """Model manager."""
8170 printerMgr: 'PrinterManager'
8171 """Printer manager."""
8173 searchMgr: 'SearchManager'
8174 """Search manager."""
8176 serverMgr: 'ServerManager'
8177 """Server manager."""
8179 storageMgr: 'StorageManager'
8180 """Storage manager."""
8182 templateMgr: 'TemplateManager'
8183 """Template manager."""
8185 webMgr: 'WebManager'
8186 """Web manager."""
8188 actions: list['Action']
8189 """Actions available in all projects."""
8191 projects: list['Project']
8192 """Configured projects."""
8194 exporters: list['Exporter']
8195 """Global exporters."""
8197 finders: list['Finder']
8198 """Finders available in all projects."""
8200 templates: list['Template']
8201 """Global templates, including the built-in ones."""
8203 printers: list['Printer']
8204 """Global printers."""
8206 models: list['Model']
8207 """Global models."""
8209 owsServices: list['OwsService']
8210 """OWS services provided by the server."""
8212 def project(self, uid: str) -> Optional['Project']:
8213 """Find a project by its uid.
8215 Args:
8216 uid: Project uid.
8218 Returns:
8219 The project, or ``None`` if not found.
8220 """
8222 def helper(self, ext_type: str) -> Optional['Node']:
8223 """Return a helper object by its type.
8225 A helper that is not configured is created with default options on the first call.
8227 Args:
8228 ext_type: Helper type, for example ``upload``.
8230 Returns:
8231 The helper object.
8233 Raises:
8234 Error: If the helper type does not exist.
8235 """
8237 def developer_option(self, key: str):
8238 """Return the value of a developer option.
8240 Developer options are configured in the ``developer`` property of the
8241 application config and are meant for development and debugging only.
8243 Args:
8244 key: Option name, for example ``template.always_reload``.
8246 Returns:
8247 The option value, or ``None`` if it is not set.
8248 """
8249################################################################################