liara package#

liara.actions module#

class liara.actions.LinkType(value, names=None, *values, module=None, qualname=None, type=None, start=1, boundary=None)#

Bases: Enum

External = 2#
Internal = 1#

Gather links across documents.

Returns:

A dictionary containing a link, and the list of document paths in which this link was found.

Validate external links.

This issues a request for each link, and checks if it connects correctly. If not, an error is printed indicating the link and the documents referencing it.

Validate internal links.

For each link, check if it exists inside the provided site. If not, an error is printed indicating the link and the documents referencing it.

liara.cache module#

class liara.cache.Cache#

Bases: ABC

Interface for key-value caches.

abstract clear() None#

Clear the contents of the cache.

New in version 2.5.

abstract get(key: bytes) object | None#

Get a stored object.

Parameters:

key – The object key.

Returns:

An object if one exists. Otherwise, return None.

abstract inspect() CacheInfo#

Get an overview of the cached data.

New in version 2.5.

persist() None#

Persists this cache to disk/persistent storage.

This function should be called after the cache has been populated. On the next run, the constructor will then pick up the index and return cached data.

abstract put(key: bytes, value: object) bool#

Put a value into the cache using the provided key.

Parameters:
  • key – The key under which value will be stored.

  • value – A pickable Python object to be stored.

Returns:

True if the value was added to the cache, False if it was already cached.

class liara.cache.CacheInfo(size: int = 0, entry_count: int = 0, name: str = '')#

Bases: object

Information about a cache. Note that the information can be approximated as getting the exact numbers may be costly.

entry_count: int = 0#

Approximate number of objects stored in the cache.

name: str = ''#

A human-friendly name for this cache.

size: int = 0#

Approximate number of bytes stored in the cache.

class liara.cache.FilesystemCache(path: Path)#

Bases: Cache

A Cache implementation which uses the filesystem to cache data.

This cache tries to load a previously generated index. Use persist() to write the cache index to disk.

clear() None#

Clear the contents of the cache.

New in version 2.5.

get(key: bytes) object | None#

Get a stored object.

Parameters:

key – The object key.

Returns:

An object if one exists. Otherwise, return None.

inspect()#

Get an overview of the cached data.

New in version 2.5.

persist()#

Persists this cache to disk/persistent storage.

This function should be called after the cache has been populated. On the next run, the constructor will then pick up the index and return cached data.

put(key: bytes, value: object) bool#

Put a value into the cache using the provided key.

Parameters:
  • key – The key under which value will be stored.

  • value – A pickable Python object to be stored.

Returns:

True if the value was added to the cache, False if it was already cached.

class liara.cache.MemoryCache#

Bases: Cache

An in-memory Cache implementation.

This cache stores all objects in-memory.

clear()#

Clear the contents of the cache.

New in version 2.5.

get(key: bytes) object | None#

Get a stored object.

Parameters:

key – The object key.

Returns:

An object if one exists. Otherwise, return None.

inspect()#

Get an overview of the cached data.

New in version 2.5.

put(key: bytes, value: object) bool#

Put a value into the cache using the provided key.

Parameters:
  • key – The key under which value will be stored.

  • value – A pickable Python object to be stored.

Returns:

True if the value was added to the cache, False if it was already cached.

class liara.cache.NullCache#

Bases: Cache

The null cache drops all requests and does not cache any data.

This is mostly useful to disable caching in APIs which require a cache instance.

clear() None#

Clear the contents of the cache.

New in version 2.5.

get(key: bytes) object | None#

Get a stored object.

Parameters:

key – The object key.

Returns:

An object if one exists. Otherwise, return None.

inspect() CacheInfo#

Get an overview of the cached data.

New in version 2.5.

put(key: bytes, value: object) bool#

Put a value into the cache using the provided key.

Parameters:
  • key – The key under which value will be stored.

  • value – A pickable Python object to be stored.

Returns:

True if the value was added to the cache, False if it was already cached.

class liara.cache.RedisCache(host: str, port: int, db: int, expiration_time=datetime.timedelta(seconds=3600))#

Bases: Cache

A cache using Redis as the storage backend.

clear()#

Clear the contents of the cache.

New in version 2.5.

get(key) object | None#

Get a stored object.

Parameters:

key – The object key.

Returns:

An object if one exists. Otherwise, return None.

inspect()#

Get an overview of the cached data.

New in version 2.5.

put(key: bytes, value: object) bool#

Put a value into the cache using the provided key.

Parameters:
  • key – The key under which value will be stored.

  • value – A pickable Python object to be stored.

Returns:

True if the value was added to the cache, False if it was already cached.

class liara.cache.Sqlite3Cache(path: Path)#

Bases: Cache

A Cache implementation which uses SQLite to store the data. This is mostly useful if creating many files is slow, for instance due to anti-virus software.

This cache tries to load a previously generated index. Use persist() to write the cache index to disk.

clear() None#

Clear the contents of the cache.

New in version 2.5.

get(key: bytes) object | None#

Get a stored object.

Parameters:

key – The object key.

Returns:

An object if one exists. Otherwise, return None.

inspect()#

Get an overview of the cached data.

New in version 2.5.

persist()#

Persists this cache to disk/persistent storage.

This function should be called after the cache has been populated. On the next run, the constructor will then pick up the index and return cached data.

put(key: bytes, value: object) bool#

Put a value into the cache using the provided key.

Parameters:
  • key – The key under which value will be stored.

  • value – A pickable Python object to be stored.

Returns:

True if the value was added to the cache, False if it was already cached.

liara.cmdline module#

class liara.cmdline.Environment#

Bases: object

The command line environment.

This provides access to global variables that are useful for command line commands, as well as a global liara instance.

property liara: Liara#
liara.cmdline.main()#

liara.config module#

liara.config.create_default_configuration() Dict[str, Any]#

Creates a dictionary with the default configuration.

liara.config.create_default_metadata() Dict[str, Any]#

Creates a dictionary with the default metadata.

liara.config.create_default_template_configuration() Dict[str, Any]#

Creates the default template configuration.

liara.feeds module#

class liara.feeds.FeedNode(path)#

Bases: GeneratedNode

class liara.feeds.JsonFeedNode(path, site: Site, *, collection='', limit=10)#

Bases: FeedNode

A JSONFeed based feed.

generate()#

Generate the content of this node.

After this function has finished, self.content must be populated with the generated content.

class liara.feeds.RSSFeedNode(path, site: Site, *, collection='', limit=10)#

Bases: FeedNode

A RSS 2.0 based feed.

generate()#

Generate the content of this node.

After this function has finished, self.content must be populated with the generated content.

class liara.feeds.SitemapXmlFeedNode(path, site: Site)#

Bases: FeedNode

A Sitemap 0.90 based feed.

generate()#

Generate the content of this node.

After this function has finished, self.content must be populated with the generated content.

liara.md module#

class liara.md.HeadingLevelFixupProcessor(md: Markdown | None = None)#

Bases: Treeprocessor

This processor demotes headings by one level.

By default, Markdown starts headings with <h1>, but in general the title will be provided by a template. This processor replaces each heading with the next-lower heading, and adds a demoted class.

run(root)#

Subclasses of Treeprocessor should implement a run method, which takes a root Element. This method can return another Element object, and the existing root Element will be replaced, or it can modify the current tree and return None.

class liara.md.LiaraMarkdownExtensions(node=None)#

Bases: Extension

Register various markdown extensions.

extendMarkdown(md)#

Add the various processors and patterns to the Markdown Instance.

This method must be overridden by every extension.

Arguments:

md: The Markdown instance.

exception liara.md.ShortcodeException(error_message, line_number, line_offset: int | None = None)#

Bases: Exception

with_line_offset(offset)#
class liara.md.ShortcodePreprocessor(md=None, node=None)#

Bases: Preprocessor

A Wordpress-inspired “shortcode” preprocessor which allows calling functions before the markup processing starts.

Shortcodes are delimited by <% and /%>. The content must start with the function name, followed by key=value pairs. The values are passed as strings, the calling function must do the type conversion.

Values without quotation marks must consist of alphanumeric characters and -, _ only.

Note

Freestanding keys are not supported as it’s ambiguous whether this should be a considered a plain argument (i.e. passed as a non-named argument) or a defaulted argument (i.e. named, but set to True or some other value.) For example, you can’t write a shortcode like this:

<% alert message="This is important" blink /%>

Instead, you’ll have to use something like:

<% alert message="This is important" blink=yes /%>
register(name: str, function)#

Register a new Markdown shortcode function.

Shortcode function calls must accept all arguments as named arguments. Names (both function names and argument names) starting with $ are reserved for built-in functions.

Shortcode handlers must accept a final **kwargs argument to handle any context Liara may pass in. Liara context variables will be prefixed with $ which is disallowed as an parameter name otherwise.

run(lines: list[str])#

Each subclass of Preprocessor should override the run method, which takes the document as a list of strings split by newlines and returns the (possibly modified) list of lines.

liara.nodes module#

class liara.nodes.DataNode(src: Path, path: PurePosixPath)#

Bases: Node

A data node.

Data nodes consist of a dictionary. This can be used to store arbitrary data as part of a liara.site.Site, and make it available to templates (for instance, a menu structure could go into a data node.)

class liara.nodes.DocumentNode(src, path: PurePosixPath, metadata_path: Path | None = None)#

Bases: Node

content: str | None#
load()#

Load the content of this node.

publish(publisher: Publisher) Path#

Publish this node using the provided publisher.

reload()#

Reload this node from disk.

By default, this just forwards to _load().

set_fixups(*, load_fixups, process_fixups) None#

Set the fixups that should be applied to this document node. The fixups should be set before calling load().

Parameters:
  • load_fixups – These functions will be executed before load() returns.

  • process_fixups – These functions will be executed before process() returns.

validate_metadata()#
class liara.nodes.DocumentNodeFactory(configuration)#

Bases: NodeFactory[DocumentNode]

A factory for document nodes.

class liara.nodes.FixupDateTimezone#

Bases: object

Set the timezone of the metadata['date'] field to the local timezone if no timezone has been set.

class liara.nodes.GeneratedNode(path: PurePosixPath, metadata: Dict | None = None)#

Bases: Node

generate() None#

Generate the content of this node.

After this function has finished, self.content must be populated with the generated content.

publish(publisher: Publisher)#

Publish this node using the provided publisher.

class liara.nodes.HtmlDocumentNode(src, path: PurePosixPath, metadata_path: Path | None = None)#

Bases: DocumentNode

A node representing a Html document.

process(cache: Cache)#

Some nodes – resources, documents, etc. need to be processed. As this can be a resource-intense process (for instance, it may require generating images), processing can cache results and has to be called separately instead of being executed as part of some other operation.

By convention this method should populate self.content if executed synchronously. If asynchronous execution is supported, this method must return an _AsyncTask which is then executed later. In this case, self.content will be populated by the task runner.

class liara.nodes.IndexNode(path: PurePosixPath, metadata: Dict | None = None)#

Bases: Node

An index node.

Index nodes are created for every folder if there is no _index node present, and from indices. An index node can optionally contain a list of references, in case the referenced nodes by this index are not direct children of this node.

add_reference(node)#

Add a reference to an arbitrary node in the site.

publish(publisher) Path#

Publish this node using the provided publisher.

references: List[Node]#

Nodes referenced by this index node.

An index can not rely on using children as those have to be below the path of the parent node. The references list allows to reference nodes elsewhere in the site.

class liara.nodes.MarkdownDocumentNode(configuration, **kwargs)#

Bases: DocumentNode

A node representing a Markdown document.

process(cache: Cache)#

Some nodes – resources, documents, etc. need to be processed. As this can be a resource-intense process (for instance, it may require generating images), processing can cache results and has to be called separately instead of being executed as part of some other operation.

By convention this method should populate self.content if executed synchronously. If asynchronous execution is supported, this method must return an _AsyncTask which is then executed later. In this case, self.content will be populated by the task runner.

class liara.nodes.MetadataKind(value, names=None, *values, module=None, qualname=None, type=None, start=1, boundary=None)#

Bases: Enum

Toml = 3#
Unknown = 1#
Yaml = 2#
class liara.nodes.Node#

Bases: object

add_child(child: Node) None#

Add a new child to this node.

The path of the child node must be a sub-path of the current node path, with exactly one more component. I.e. if the current node path is /foo/bar, a node with path /foo/bar/baz can be added as a child, but /baz/ or /foo/bar/boo/baz would be invalid.

property children#

A list containing all direct children of this node.

get_child(name) Node | None#

Get a child of this node.

Returns:

The child node or None if no such child exists.

get_children(*, recursive=False) Iterable[Node]#

Get all children of this node.

This function differs from select_children() in two important ways:

  • It returns a list of Node instances and does not wrap it in a Query

  • It can enumerate all children recursively.

kind: NodeKind#

The node kind, must be set in the constructor.

metadata: Dict[str, Any]#

Metadata associated with this node.

parent: Node | None#

The parent node, if any.

path: PurePosixPath#

The output path, relative to the page root.

All paths must start with /.

process(cache: Cache) _AsyncTask | None#

Some nodes – resources, documents, etc. need to be processed. As this can be a resource-intense process (for instance, it may require generating images), processing can cache results and has to be called separately instead of being executed as part of some other operation.

By convention this method should populate self.content if executed synchronously. If asynchronous execution is supported, this method must return an _AsyncTask which is then executed later. In this case, self.content will be populated by the task runner.

select_children() Query#

Select all children of this node and return them as a Query.

src: Path | None#

The full path to the source file.

This is an OS specific path object.

class liara.nodes.NodeFactory#

Bases: Generic[NT]

A generic factory for nodes, which builds nodes based on the file type.

create_node(suffix: str, src: Path, path: PurePosixPath, metadata_path: Path | None = None) NT#

Create a node using the provided parameters.

property known_types#
register_type(suffixes: str | Iterable[str], node_type: type, *, extra_args: Dict[str, Any] = {}) None#

Register a new node type.

Parameters:
  • suffixes – Either one suffix, or a list of suffixes to be registered for this type. For instance, a node representing an image could be registered to [.jpg, .png, .webp].

  • node_type – The type of the node to be created.

  • extra_args – A dictionary of additional arguments for the node constructor. This dictionary gets passed as **kwargs into the node constructor.

class liara.nodes.NodeKind(value, names=None, *values, module=None, qualname=None, type=None, start=1, boundary=None)#

Bases: Enum

Data = 4#
Document = 3#
Generated = 6#
Index = 2#
Resource = 1#
Static = 5#
class liara.nodes.Publisher#

Bases: object

A publisher produces the final output files, applying templates etc. as needed.

publish_document(document: DocumentNode) Path#

Publish a document node.

Returns:

The path of the generated file.

publish_generated(generated: GeneratedNode) Path#

Publish a generated node.

Returns:

The path of the generated file.

publish_index(index: IndexNode) Path#

Publish an index node.

Returns:

The path of the generated file.

publish_resource(resource: ResourceNode) Path#

Publish a resource node.

Returns:

The path of the generated file.

publish_static(static: StaticNode) Path#

Publish a static node.

Returns:

The path of the generated file.

class liara.nodes.RedirectionNode(path: PurePosixPath, dst: PurePosixPath, *, base_url='')#

Bases: GeneratedNode

A redirection node triggers a redirection to another page.

This node gets processed into a simple web site which tries to redirect using both <meta http-equiv="refresh"> and Javascript code setting window.location.

generate()#

Generate the content of this node.

After this function has finished, self.content must be populated with the generated content.

class liara.nodes.ResourceNode(src, path: PurePosixPath, metadata_path=None)#

Bases: Node

A resource node applies some process when creating the output.

This is useful if you have content where the source cannot be interpreted, and requires some process first before it becomes usable – for instance, SASS to CSS compilation.

publish(publisher: Publisher) Path#

Publish this node using the provided publisher.

reload() None#
class liara.nodes.ResourceNodeFactory(configuration)#

Bases: NodeFactory[ResourceNode]

A factory for resource nodes.

class liara.nodes.SassResourceNode(src, path: PurePosixPath, metadata_path=None)#

Bases: ResourceNode

This resource node compiles .sass and .scss files to CSS when built.

process(cache: Cache)#

Some nodes – resources, documents, etc. need to be processed. As this can be a resource-intense process (for instance, it may require generating images), processing can cache results and has to be called separately instead of being executed as part of some other operation.

By convention this method should populate self.content if executed synchronously. If asynchronous execution is supported, this method must return an _AsyncTask which is then executed later. In this case, self.content will be populated by the task runner.

reload() None#
set_compiler(compiler: Literal['cli', 'libsass'])#
class liara.nodes.StaticNode(src: Path, path: PurePosixPath, metadata_path=None)#

Bases: Node

A static data node.

Static nodes are suitable for large static data which never changes, for instance, binary files, videos, images etc.

property is_image#

Return True if this static file is pointing to an image.

publish(publisher: Publisher) Path#

Publish this node using the provided publisher.

src: Path#

The full path to the source file.

This is an OS specific path object.

update_metadata() None#

Update metadata by deriving some metadata from the source file, if possible.

For static nodes pointing to images, this will create a new metadata field image_size and populate it with the image resolution.

class liara.nodes.ThumbnailNode(src, path: PurePosixPath, size: Dict[str, int], format: str | None = 'original')#

Bases: ResourceNode

process(cache: Cache) _AsyncThumbnailTask | None#

Some nodes – resources, documents, etc. need to be processed. As this can be a resource-intense process (for instance, it may require generating images), processing can cache results and has to be called separately instead of being executed as part of some other operation.

By convention this method should populate self.content if executed synchronously. If asynchronous execution is supported, this method must return an _AsyncTask which is then executed later. In this case, self.content will be populated by the task runner.

liara.nodes.extract_metadata_content(text: str)#

Extract metadata and content.

Metadata is stored at the beginning of the file, separated using a metadata separation marker, for instance:

+++
this_is_toml = True
+++

content

This function splits the provided text into metadata and actual content.

liara.nodes.fixup_date(document: DocumentNode)#

If the date in the document is a string, try to parse it to produce a datetime object.

Replace relative links in the document with links relative to the site root.

liara.publish module#

class liara.publish.BuildContext(node: DocumentNode | IndexNode)#

Bases: object

Provides information about the current build.

property last_modified_time#

Get the last modified time of the source file (if present) as a datetime instance. If there’s no source file (for example, for indices), this returns the timestamp of the build itself.

timestamp: datetime#

The current time when this node was processed

version: str#

The Liara version string (i.e. a.b.c)

class liara.publish.DefaultPublisher(output_path: Path, site: Site)#

Bases: Publisher

publish_generated(generated: GeneratedNode)#

Publish a generated node.

Returns:

The path of the generated file.

publish_resource(resource: ResourceNode)#

Publish a resource node.

Returns:

The path of the generated file.

publish_static(static: StaticNode)#

Publish a static node.

Returns:

The path of the generated file.

class liara.publish.TemplatePublisher(output_path: Path, site: Site, template_repository: TemplateRepository)#

Bases: DefaultPublisher

publish_document(document)#

Publish a document node.

Returns:

The path of the generated file.

publish_index(index: IndexNode)#

Publish an index node.

Returns:

The path of the generated file.

liara.query module#

class liara.query.ExcludeFilter(pattern)#

Bases: SelectionFilter

Filter items by a provided pattern. The pattern is matched against the path. If it matches, the item will be ignored.

match(node: Node) bool#

Return True if the node should be kept, else False.

class liara.query.MetadataFilter(name, value=None)#

Bases: SelectionFilter

Filter items which contain a specific metadata field and optionally check if that field matches the provided value.

match(node: Node) bool#

Return True if the node should be kept, else False.

class liara.query.MetadataSorter(item: str, reverse=False, case_sensitive=False)#

Bases: Sorter

Sort nodes by metadata.

get_key(item: Node)#

Return the key to be used for sorting.

class liara.query.NodeKindFilter(kinds, *, exclude=False)#

Bases: SelectionFilter

Filter items based on the node kind. Use exclude to invert.

New in version 2.4.

match(node: Node) bool#

Return True if the node should be kept, else False.

class liara.query.Query(nodes: Iterable[Node])#

Bases: Iterable[Union[Node, Page]]

A query modifies a list of nodes, by sorting and filtering entries.

Sorting requires the sort key to be present on all nodes that are to be sorted, otherwise an error is raised. Nodes without a particular key can be filtered out using with_metadata().

Index and document nodes will be wrapped in a Page instance. Everything else will be returned as a Node.

exclude(pattern) Query#

Exclude nodes matching the provided regex pattern. The pattern will be applied to the full path.

limit(limit: int) Query#

Limit this query to return at most limit results.

reversed() Query#

Return the results of this query in reversed order.

sorted_by_date(*, reverse=False) Query#

Sort the entries in this query by the metadata field date.

sorted_by_metadata(tag: str, *, reverse=False, case_sensitive=False) Query#

Sort the entries in this query by the specified metadata field.

sorted_by_title(*, reverse=False) Query#

Sort the entries in this query by the metadata field title.

with_metadata(name, value=None) Query#

Limit this query to only include nodes which contain the specific metadata field.

Parameters:

value – If value is provided, the field must exist and match the provided value.

with_node_kinds(*args) Query#

Includes nodes of a specific type. Multiple kinds can be passed in.

New in version 2.4.

with_tag(name) Query#

Limit this query to only include nodes with a metadata field named tags which contains the specified tag name.

without_node_kinds(*args) Query#

Excludes nodes of a specific type. Multiple kinds can be passed in.

New in version 2.4.

class liara.query.SelectionFilter#

Bases: object

Base class for query selection filters.

match(node: Node) bool#

Return True if the node should be kept, else False.

class liara.query.Sorter(reverse=False)#

Bases: object

Base class for query sorters.

get_key(item)#

Return the key to be used for sorting.

property reverse#

Returns True if the sort order should be reversed.

class liara.query.TagFilter(name)#

Bases: SelectionFilter

Filter items by a specific tag, this expects a metadata field named tags to be present, and that field must support checks for containment using in.

match(node: Node) bool#

Return True if the node should be kept, else False.

liara.quickstart module#

liara.quickstart.generate(template_backend)#
liara.quickstart.generate_configs()#
liara.quickstart.generate_content()#
liara.quickstart.generate_css()#
liara.quickstart.generate_generator()#
liara.quickstart.generate_templates(backend)#
liara.quickstart.generate_theme(backend)#

liara.server module#

class liara.server.HttpServer(*, open_browser=True, port=8080)#

Bases: object

get_url()#
serve(site: Site, template_repository: TemplateRepository, configuration, cache: Cache)#

Serve the site with just-in-time processing.

This does not build the whole site up-front, but rather builds nodes on demand. Nodes requiring templates are rebuilt from scratch every time to ensure they’re up-to-date. Adding/removing nodes while serving will break the server, as it will not get notified and re-discover content.

liara.signals module#

See Processing order for an overview of the processing stages.

liara.signals.content_filtered#

Raised when content has been removed due to a filter.

This signal is raised during the content discovery stage.

Parameters:
liara.signals.content_added#

Raised when a content node was successfully added.

This signal is raised during the content discovery stage. It is not raised for nodes that have been filtered.

Parameters:

node (liara.nodes.Node) – the node that was created

liara.signals.commandline_prepared#

Raised when the command line parsing environment was prepared.

Parameters:

cli (click.group) – The command line group to add commands to.

liara.signals.content_discovered#

Raised after all content has been discovered.

Parameters:

site (liara.site.Site) – the site instance

liara.signals.documents_processed#

Raised after all documents have been processed.

Parameters:

site (liara.site.Site) – the site instance

Processing includes the conversion from Markdown to HTML.

liara.signals.document_loaded#

Raised after a document has been loaded.

This signal is raised during the content discovery stage.

Parameters:

When this signal is raised, the content has been loaded, but no templates etc. have been applied to the document yet.

liara.signals.register_markdown_shortcodes#

Raised while initializing the Markdown processor.

Parameters:

preprocessor (liara.md.ShortcodePreprocessor) – The shortcode preprocessor

When this signal is raised, you can register shortcode function calls by calling liara.md.ShortcodePreprocessor.register().

liara.site module#

class liara.site.Collection(site: Site, name: str, pattern: str, *, exclude_without: List[str | Tuple[str, Any]] | None = None, order_by: str | List[str] | None = None, node_kinds: List[str | NodeKind] | None = None)#

Bases: object

A collection is a set of nodes. Collections can be ordered, which allows for next/previous queries.

__init__(site: Site, name: str, pattern: str, *, exclude_without: List[str | Tuple[str, Any]] | None = None, order_by: str | List[str] | None = None, node_kinds: List[str | NodeKind] | None = None)#

Create a new collection.

Parameters:
  • pattern – The pattern to select nodes which belong to this collection.

  • exclude_without – Exclude items without the specified metadata fields. If a tuple is provided, the metadata field’s value must match the requested value.

  • order_by – A list of accessors for fields to order by. If multiple entries are provided, the result will be sorted by each in order using a stable sort. To reverse the order, use a leading -, for example: -date.

  • node_kinds – Only include nodes of that kinds. If not specified, NodeKind.Document will be used as the default.

If an ordering is specified, and a particular node cannot support that ordering (for instance, as it’s missing the field that is used to order by), an error will be raised.

get_next(node: Node) Node#

Get the next node in this collection with regard to the specified order, or None if this is the last node.

get_previous(node: Node) Node#

Get the previous node in this collection with regard to the specified order, or None if this is the first node.

property nodes: Iterable[Node]#

Get the (sorted) nodes in this collection.

class liara.site.ContentFilter#

Bases: object

Content filters can filter out nodes based on various criteria.

apply(node: Node) bool#

Return True if the node should be kept, and False otherwise.

property name: str#
property reason: str#

Return a reason why this filter applied.

class liara.site.ContentFilterFactory#

Bases: object

__init__()#
create_filter(name: str) ContentFilter#
class liara.site.DateFilter#

Bases: ContentFilter

Filter content based on the metadata field date.

If the date is in the future, the node will be filtered.

__init__()#
apply(node: Node) bool#

Return True if the node should be kept, and False otherwise.

property name#
property reason#

Return a reason why this filter applied.

class liara.site.Index(collection: Collection, path: str, group_by: List[str], *, exclude_without: List[str | Tuple[str, Any]] | None = None, create_top_level_index=False)#

Bases: object

An index into a collection, which provides an index structure.

The index structure requires a grouping schema – for instance, all nodes containing some tag can get grouped under one index node.

__init__(collection: Collection, path: str, group_by: List[str], *, exclude_without: List[str | Tuple[str, Any]] | None = None, create_top_level_index=False)#

Create a new index.

Parameters:
  • collection – The collection to use for this index.

  • path – The path pattern to create index entries at. This must contain one numbered placeholder (%1, etc.) per entry in group_by

  • group_by – The grouping statements. The nodes are grouped by each entry in this array in-order.

  • exclude_without – Exclude items without the specified metadata field. If a tuple is provided, the metadata field’s value must match the requested value.

  • create_top_level_index – Create a node at the top-level path as well instead of only creating nodes per grouping statement.

create_nodes(site: Site)#

Create the index nodes inside the specified site.

class liara.site.Site#

Bases: object

This class manages to all site content.

__init__()#
add_data(node: DataNode) None#

Add a data node to this site.

add_document(node: DocumentNode) None#

Add a document to this site.

add_generated(node: GeneratedNode) None#

Add a generated node to this site.

add_index(node: IndexNode) None#

Add an index node to this site.

add_resource(node: ResourceNode) None#

Add a resource to this site.

add_static(node: StaticNode) None#

Add a static node to this site.

create_collections(collections)#

Create collections.

create_indices(indices)#

Create indices.

This creates links between parents/children.

This is a separate step so it can be executed after merging nodes from multiple sources, for instance themes. It is safe to call this function multiple times to create new links; nodes which already have a parent are automatically skipped.

create_thumbnails(thumbnail_definition)#

Create thumbnails.

Based on the thumbnail definition – which is assumed to be a dictionary containing the suffix, the desired size and the target formats – this function iterates over all static nodes that contain images, and creates new thumbnail nodes as required.

data: List[DataNode]#

The list of all data nodes in this site.

documents: List[DocumentNode]#

The list of all document nodes in this site.

property filtered_content: Dict[PurePosixPath, str]#

Return which node paths got filtered and due to which filter.

generated: List[GeneratedNode]#

The list of all generated nodes in this site.

get_collection(collection: str) Collection#

Get a collection.

get_next_in_collection(collection: str, node: Node) Node | None#

Get the next node in a collection.

get_node(path: str | PurePosixPath) Node | None#

Get a node based on the URL, or None if no such node exists.

get_previous_in_collection(collection: str, node: Node) Node | None#

Get the previous node in a collection.

indices: List[IndexNode]#

The list of all index nodes in this site.

metadata: Dict[str, Any]#

Metadata describing this site.

property nodes: ValuesView[Node]#

The list of all nodes in this site.

register_content_filter(content_filter: ContentFilter)#

Register a new content filter.

resources: List[ResourceNode]#

The list of all resources nodes in this site.

select(query: str) Iterable[Node]#

Select nodes from this site.

The query string may contain * to list all direct children of a node, and ** to recursively enumerate nodes. Partial matches using *foo are not supported. See URL patterns for details.

set_metadata(metadata: Dict[str, Any]) None#

Set the metadata for this site.

This overrides any previously set metadata. Metadata is accessible via the metadata attribute.

set_metadata_item(key: str, value: Any) None#

Set a single entry in the metadata for this site.

This can be used to override individual metadata items.

static: List[StaticNode]#

The list of all static nodes in this site.

property urls: KeysView[PurePosixPath]#

The list of all registered URLs.

class liara.site.StatusFilter#

Bases: ContentFilter

Filter content based on the metadata field status.

If status is set to private, the node will be filtered. The comparison is case-insensitive.

apply(node: Node) bool#

Return True if the node should be kept, and False otherwise.

property name#
property reason#

Return a reason why this filter applied.

liara.template module#

class liara.template.Jinja2Template(template, template_path)#

Bases: Template

render(**kwargs) str#
class liara.template.Jinja2TemplateRepository(paths: Dict[str, str], path: Path, cache: Cache | None = None, *, options: Dict[str, Any] | None = None)#

Bases: TemplateRepository

Jinja2 based template repository.

find_template(url: PurePosixPath, site: Site) Template#
class liara.template.MakoTemplate(template, template_path)#

Bases: Template

render(**kwargs) str#
class liara.template.MakoTemplateRepository(paths: Dict[str, str], path: Path)#

Bases: TemplateRepository

find_template(url: PurePosixPath, site: Site) Template#
class liara.template.Page(node)#

Bases: object

A wrapper around DocumentNode and IndexNode for use inside templates.

Templates only get applied to those node types, and the Page class provides convenience accessors while hiding the underlying node from template code.

property children: Query#

Return all child pages of this page, i.e. document and index nodes.

New in version 2.4.

property content: str#

Provides the content of this page.

property meta: Dict[str, Any]#

Provides the metadata associated with this page.

Deprecated since version 2.1.2: Use metadata instead.

property metadata: Dict[str, Any]#

Provides the metadata associated with this page.

New in version 2.1.2.

property references: Query#

Provides the list of referenced nodes by this page.

This can be only used if the current page is an IndexNode, in all other cases this will fail. For index nodes, this will return the list of references as a Query instance.

property url: str#

Provides the current path of this page.

class liara.template.SiteTemplateProxy(site: Site)#

Bases: object

A wrapper around Site for use inside templates.

property data: Dict[str, Any]#

Get the union of all liara.nodes.DataNode instances in this site.

get_collection(collection: str) Query#

Get a collection in form of a liara.query.Query for further filtering/sorting.

get_next_in_collection(collection: str, page: Page) Page | None#

Given a collection and a page, return the next page in this collection or None if this is the last page.

get_page_by_url(url) Page | None#

Return a page by URL. If the page cannot be found, return None.

get_previous_in_collection(collection: str, page: Page) Page | None#

Given a collection and a page, return the previous page in this collection or None if this is the first page.

property metadata: Dict[str, Any]#

Provide access to the metadata of this site.

select(query) Query#

Run a query on this site. Returns any node matching the query.

select_pages(query) Query#

Run a query on this site and return only matching pages, i.e. document and index nodes.

New in version 2.4.

class liara.template.Template(template_path='<unknown>')#

Bases: object

property path#
render(**kwargs)#
class liara.template.TemplateRepository(paths: Dict[str, str])#

Bases: object

find_template(url: PurePosixPath, site: Site) Template#
update_paths(paths: Dict[str, str])#

liara.util module#

class liara.util.FilesystemWalker(ignore_files: List[str] | None = None)#

Bases: object

walk(path: Path)#

Walk a directory recursively.

This is quite similar to os.walk, but with two major differences:

  • Files matching the ignore_files pattern are ignored.

  • The dirnames part of the tuple is omitted

liara.util.add_suffix(path: Path, suffix)#

Add a suffix to a path.

This differs from with_suffix by adding a suffix without changing the extension, i.e. adding en to foo.baz will produce foo.en.baz.

liara.util.create_slug(s: str) str#

Convert a plain string into a slug.

A slug is suitable for use as a URL. For instance, passing A new world to this function will return a-new-world.

liara.util.flatten_dictionary(d, sep='.', parent_key=None, *, ignore_keys: set | None = None)#

Flatten a nested dictionary. This uses the separator to combine keys together, so a dictionary access like ['a']['b'] with a separator '.' turns into 'a.b'.

If ignore_keys is set, it must be a list of fully flattened key names at which the flattening should stop. For instance, if a dictionary {'a': {'b': {'c': 1}}} is provided, and ignore_keys is {'a.b'}, then a.b will not get flattened further, so a.b will contain a dictionary with {'c': 1}.

liara.util.local_now() datetime#

Get the current date/time in the local time zone.

This is equivalent to datetime.datetime.now(), except it returns a timestamp which has tzinfo set to the local timezone.

This can be overridden using set_local_now to build the page at a different point in time.

liara.util.pairwise(iterable)#

For a list s, return pairs for consecutive entries. For example, a list s0, s1, etc. will produce (s0,s1), (s1,s2), ... and so on.

See: https://docs.python.org/3/library/itertools.html#recipes.

liara.util.readtime(wordcount: int, words_per_minute=300)#

Given a number of words, estimate the time it would take to read them.

Returns:

The time in minutes if it’s more than 1, otherwise 1.

liara.util.set_local_now(dt: datetime)#

Override “now” to allow previewing the page at a different point in time.

liara.yaml module#

liara.yaml.dump_yaml(data, stream: IO | None = None)#

Dump an object to Yaml.

This is a helper function which tries to use the fast CDumper implementation and falls back to the native Python version on failure.

liara.yaml.load_yaml(s: bytes | IO | IO[bytes] | str | IO[str])#

Load a Yaml document.

This is a helper function which tries to use the fast CLoader implementation and falls back to the native Python version on failure.

Module contents#

class liara.Liara(configuration: str | IO | IO[bytes] | IO[str] | None = None, *, configuration_overrides: Dict | None = None)#

Main entry point for Liara. This class handles all the state required to process and build a site.

build(discover_content=True, *, disable_cache=False, parallel_build=True)#

Build the site.

Parameters:

discover_content (bool) – If True, discover_content() will be called first.

create_document(t)#

Create a new document using a generator.

discover_content() Site#

Discover all content and build the liara.site.Site instance.

serve(*, open_browser=True, port=8080, disable_cache=True)#

Serve the current site using a local webserver.