Base class to create an HTML response content.
Module whakerpy.httpd
Class BaseResponseRecipe
Description
Constructor
Create a new ResponseRecipe instance with a default response.
Parameters
- name: (str) Filename of the body main content or name of the page.
- tree: (HTMLTree|None)
Optional arguments: - title: (str) The title of the page - description: (str) The description of the page (160 characters max)
View Source
def __init__(self, name='Undefined', tree=None, **kwargs):
"""Create a new ResponseRecipe instance with a default response.
:param name: (str) Filename of the body main content or name of the page.
:param tree: (HTMLTree|None)
Optional arguments:
- title: (str) The title of the page
- description: (str) The description of the page (160 characters max)
"""
self._name = name
if name is not None:
self._page_name = os.path.basename(name)
else:
self._name = 'undefined'
self._page_name = ''
self._status = HTTPDStatus()
self._data = dict()
self._title = ''
self._description = ''
if 'title' in kwargs:
self._title = kwargs['title']
if 'description' in kwargs:
self._description = kwargs['description']
if tree is not None and isinstance(tree, HTMLTree):
self._htree = tree
else:
self._htree = HTMLTree(self._name.replace(' ', '_'))
self.create()
Public functions
page
Return the current HTML body->main filename or an empty string.
Parameters
- cls
View Source
@classmethod
def page(cls):
"""Return the current HTML body->main filename or an empty string."""
return cls._name
name
View Source
@property
def name(self) -> str:
return self._name
status
View Source
@property
def status(self) -> HTTPDStatus:
return self._status
get_data
Gets the current data to send to the client following this request.
Returns
- (str) The data in the string format or json depending on the type.
View Source
def get_data(self) -> str | bytes:
"""Gets the current data to send to the client following this request.
:return: (str) The data in the string format or json depending on the type.
"""
if isinstance(self._data, dict):
return json.dumps(self._data)
elif isinstance(self._data, bytes) or isinstance(self._data, bytearray) or isinstance(self._data, str):
return self._data
else:
raise ValueError(f'Unexpected data type to response to the client : {type(self._data)}')
reset_data
Clear json data of the response. This function has to be called after each response send to the client to avoid overflow problems.
View Source
def reset_data(self) -> None:
"""Clear json data of the response.
This function has to be called after each response send to the client to avoid overflow problems.
"""
self._data = dict()
get_pagename
Return the name of the HTML page as seen in the URL.
View Source
def get_pagename(self) -> str:
"""Return the name of the HTML page as seen in the URL."""
return self._page_name
set_pagename
Set the name of this page as seen in the url.
Parameters
- page_name: (str) Name of the HTML page.
View Source
def set_pagename(self, page_name: str):
"""Set the name of this page as seen in the url.
:param page_name: (str) Name of the HTML page.
"""
if type(page_name) is not str:
raise TypeError('Page name must be a string.')
self._page_name = page_name
comment
Add a comment to the body->main.
Parameters
- content: (str) The comment content
Returns
- (HTMLComment) the created node
View Source
def comment(self, content: str) -> HTMLComment:
"""Add a comment to the body->main.
:param content: (str) The comment content
:return: (HTMLComment) the created node
"""
return self._htree.comment(content)
element
Add an element node to the body->main.
Parameters
- tag: (str) HTML element name
- ident: (str) Identifier of the element
- class_name: (str) Value of the class attribute
Returns
- (HTMLNode) The created node
View Source
def element(self, tag: str='div', ident=None, class_name=None) -> HTMLNode:
"""Add an element node to the body->main.
:param tag: (str) HTML element name
:param ident: (str) Identifier of the element
:param class_name: (str) Value of the class attribute
:return: (HTMLNode) The created node
"""
return self._htree.element(tag, ident, class_name)
create
Create the fixed page content in HTML. Intended to be overridden.
This method is intended to be used to create the parts of the tree that won't be invalidated when baking.
View Source
def create(self) -> None:
"""Create the fixed page content in HTML. Intended to be overridden.
This method is intended to be used to create the parts of the tree
that won't be invalidated when baking.
"""
pass
bake
Return the HTML response after processing the events.
Processing the events may change the response status. This method is invoked by the HTTPD server to construct the response. Given events are the information the handler received (commonly with POST).
Parameters
- events: (dict) The requested events to be processed
- headers: (dict) The headers of the http request received
View Source
def bake(self, events: dict, headers: dict=None) -> str:
"""Return the HTML response after processing the events.
Processing the events may change the response status. This method is
invoked by the HTTPD server to construct the response. Given events
are the information the handler received (commonly with POST).
:param events: (dict) The requested events to be processed
:param headers: (dict) The headers of the http request received
"""
dirty = self._process_events(events, headers=headers)
if dirty is True:
self._invalidate()
self._bake()
return self._htree.serialize()
Private functions
_process_events
Process the given events.
The given event name must match a function of the event's manager.
Processing an event may change the content of the tree. In that case,
the dirty method must be turned into True: it will invalidate the
deprecated content (invalidate) and re-generate a new one (bake).
Parameters
- events (dict): key=eventname, value=eventvalue
Returns
- (bool)
View Source
def _process_events(self, events: dict, **kwargs) -> bool:
"""Process the given events.
The given event name must match a function of the event's manager.
Processing an event may change the content of the tree. In that case,
the `dirty` method must be turned into True: it will invalidate the
deprecated content (_invalidate) and re-generate a new one (_bake).
:param events (dict): key=event_name, value=event_value
:return: (bool)
"""
self._status.code = 200
return False
_invalidate
Remove children nodes of the tree. Intended to be overridden.
Remove the dynamic content of the tree, which will be re-introduced when baking.
If the tree has no dynamic content, this method is un-used.
View Source
def _invalidate(self):
"""Remove children nodes of the tree. Intended to be overridden.
Remove the dynamic content of the tree, which will be re-introduced
when baking.
If the tree has no dynamic content, this method is un-used.
"""
pass
_bake
Fill in the HTML page generator. Intended to be overridden.
If the tree has no dynamic content, this method is un-used.
This method is baking the "dynamic" content of the page, i.e. it should not change the content created by the method create().
View Source
def _bake(self) -> None:
"""Fill in the HTML page generator. Intended to be overridden.
If the tree has no dynamic content, this method is un-used.
This method is baking the "dynamic" content of the page, i.e. it
should not change the content created by the method create().
"""
pass
