code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def unsuppress(self, email): params = {"email": email} response = self._put(self.uri_for("unsuppress"), body=" ", params=params)
Unsuppresses an email address by removing it from the the client's suppression list
def set_payg_billing(self, currency, can_purchase_credits, client_pays, markup_percentage, markup_on_delivery=0, markup_per_recipient=0, markup_on_design_spam_test=0): body = { "Currency": currency, "CanPurchaseCredits": can_purchase_credits, ...
Sets the PAYG billing settings for this client.
def set_monthly_billing(self, currency, client_pays, markup_percentage, monthly_scheme=None): body = { "Currency": currency, "ClientPays": client_pays, "MarkupPercentage": markup_percentage} if monthly_scheme is not None: body["MonthlyScheme"] = ...
Sets the monthly billing settings for this client.
def transfer_credits(self, credits, can_use_my_credits_when_they_run_out): body = { "Credits": credits, "CanUseMyCreditsWhenTheyRunOut": can_use_my_credits_when_they_run_out} response = self._post(self.uri_for('credits'), json.dumps(body)) return json_to_py(respo...
Transfer credits to or from this client. :param credits: An Integer representing the number of credits to transfer. This value may be either positive if you want to allocate credits from your account to the client, or negative if you want to deduct credits from the client back int...
def set_primary_contact(self, email): params = {"email": email} response = self._put(self.uri_for('primarycontact'), params=params) return json_to_py(response)
assigns the primary contact for this client
def smart_email_list(self, status="all", client_id=None): if client_id is None: response = self._get( "/transactional/smartEmail?status=%s" % status) else: response = self._get( "/transactional/smartEmail?status=%s&clientID=%s" % (status, ...
Gets the smart email list.
def smart_email_send(self, smart_email_id, to, consent_to_track, cc=None, bcc=None, attachments=None, data=None, add_recipients_to_list=None): validate_consent_to_track(consent_to_track) body = { "To": to, "CC": cc, "BCC": bcc, "Attachments": atta...
Sends the smart email.
def classic_email_send(self, subject, from_address, to, consent_to_track, client_id=None, cc=None, bcc=None, html=None, text=None, attachments=None, track_opens=True, track_clicks=True, inline_css=True, group=None, add_recipients_to_list=None): validate_consent_to_track(consent_to_track) body =...
Sends a classic email.
def classic_email_groups(self, client_id=None): if client_id is None: response = self._get("/transactional/classicEmail/groups") else: response = self._get( "/transactional/classicEmail/groups?clientID=%s" % client_id) return json_to_py(response)
Gets the list of classic email groups.
def message_details(self, message_id, statistics=False): response = self._get( "/transactional/messages/%s?statistics=%s" % (message_id, statistics)) return json_to_py(response)
Gets the details of this message.
def create(self, list_id, title, rulegroups): body = { "Title": title, "RuleGroups": rulegroups} response = self._post("/segments/%s.json" % list_id, json.dumps(body)) self.segment_id = json_to_py(response) return self.segment_id
Creates a new segment.
def update(self, title, rulegroups): body = { "Title": title, "RuleGroups": rulegroups} response = self._put("/segments/%s.json" % self.segment_id, json.dumps(body))
Updates this segment.
def add_rulegroup(self, rulegroup): body = rulegroup response = self._post("/segments/%s/rules.json" % self.segment_id, json.dumps(body))
Adds a rulegroup to this segment.
def subscribers(self, date="", page=1, page_size=1000, order_field="email", order_direction="asc", include_tracking_information=False): params = { "date": date, "page": page, "pagesize": page_size, "orderfield": order_field, "orderdirection": ...
Gets the active subscribers in this segment.
def create(self, client_id, name, html_url, zip_url): body = { "Name": name, "HtmlPageURL": html_url, "ZipFileURL": zip_url} response = self._post("/templates/%s.json" % client_id, json.dumps(body)) self.template_id = jso...
Creates a new email template.
def update(self, name, html_url, zip_url): body = { "Name": name, "HtmlPageURL": html_url, "ZipFileURL": zip_url} response = self._put("/templates/%s.json" % self.template_id, json.dumps(body))
Updates this email template.
def add(self, email_address, name): body = { "EmailAddress": email_address, "Name": name} response = self._post("/admins.json", json.dumps(body)) return json_to_py(response)
Adds an administrator to an account.
def update(self, new_email_address, name): params = {"email": self.email_address} body = { "EmailAddress": new_email_address, "Name": name} response = self._put("/admins.json", body=json.dumps(body), params=params) # Update se...
Updates the details for an administrator.
def delete(self): params = {"email": self.email_address} response = self._delete("/admins.json", params=params)
Deletes the administrator from the account.
def match_hostname(cert, hostname): if not cert: raise ValueError("empty or no certificate") dnsnames = [] san = cert.get('subjectAltName', ()) for key, value in san: if key == 'DNS': if _dnsname_to_pat(value).match(hostname): return dnsnames....
This is a backport of the match_hostname() function from Python 3.2, essential when using SSL. Verifies that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules are mostly followed, but IP addresses are not accepted for *hostname*. CertificateEr...
def create(self, client_id, title, unsubscribe_page, confirmed_opt_in, confirmation_success_page, unsubscribe_setting="AllClientLists"): body = { "Title": title, "UnsubscribePage": unsubscribe_page, "ConfirmedOptIn": confirmed_opt_in, "Conf...
Creates a new list for a client.
def create_custom_field(self, field_name, data_type, options=[], visible_in_preference_center=True): body = { "FieldName": field_name, "DataType": data_type, "Options": options, "VisibleInPreferenceCenter": visible_in_preferenc...
Creates a new custom field for this list.
def update_custom_field(self, custom_field_key, field_name, visible_in_preference_center): custom_field_key = quote(custom_field_key, '') body = { "FieldName": field_name, "VisibleInPreferenceCenter": visible_in_preference_center} resp...
Updates a custom field belonging to this list.
def delete_custom_field(self, custom_field_key): custom_field_key = quote(custom_field_key, '') response = self._delete("/lists/%s/customfields/%s.json" % (self.list_id, custom_field_key))
Deletes a custom field associated with this list.
def update_custom_field_options(self, custom_field_key, new_options, keep_existing_options): custom_field_key = quote(custom_field_key, '') body = { "Options": new_options, "KeepExistingOptions": keep_existing_options} response...
Updates the options of a multi-optioned custom field on this list.
def active(self, date="", page=1, page_size=1000, order_field="email", order_direction="asc", include_tracking_preference=False): params = { "date": date, "page": page, "pagesize": page_size, "orderfield": order_field, "orderdirection": order_...
Gets the active subscribers for this list.
def update(self, title, unsubscribe_page, confirmed_opt_in, confirmation_success_page, unsubscribe_setting="AllClientLists", add_unsubscribes_to_supp_list=False, scrub_active_with_supp_list=False): body = { "Title": title, "UnsubscribePage": unsubsc...
Updates this list.
def create_webhook(self, events, url, payload_format): body = { "Events": events, "Url": url, "PayloadFormat": payload_format} response = self._post(self.uri_for("webhooks"), json.dumps(body)) return json_to_py(response)
Creates a new webhook for the specified events (an array of strings). Valid events are "Subscribe", "Deactivate", and "Update". Valid payload formats are "json", and "xml".
def get(self, list_id=None, email_address=None, include_tracking_preference=False): params = { "email": email_address or self.email_address, "includetrackingpreference": include_tracking_preference, } response = self._get("/subscribers/%s.json" % ...
Gets a subscriber by list ID and email address.
def add(self, list_id, email_address, name, custom_fields, resubscribe, consent_to_track, restart_subscription_based_autoresponders=False): validate_consent_to_track(consent_to_track) body = { "EmailAddress": email_address, "Name": name, "CustomFields": custo...
Adds a subscriber to a subscriber list.
def update(self, new_email_address, name, custom_fields, resubscribe, consent_to_track, restart_subscription_based_autoresponders=False): validate_consent_to_track(consent_to_track) params = {"email": self.email_address} body = { "EmailAddress": new_email_address, ...
Updates any aspect of a subscriber, including email address, name, and custom field data if supplied.
def import_subscribers(self, list_id, subscribers, resubscribe, queue_subscription_based_autoresponders=False, restart_subscription_based_autoresponders=False): body = { "Subscribers": subscribers, "Resubscribe": resubscribe, "QueueSubscriptionBasedAutoresponders": q...
Imports subscribers into a subscriber list.
def unsubscribe(self): body = { "EmailAddress": self.email_address} response = self._post("/subscribers/%s/unsubscribe.json" % self.list_id, json.dumps(body))
Unsubscribes this subscriber from the associated list.
def history(self): params = {"email": self.email_address} response = self._get("/subscribers/%s/history.json" % self.list_id, params=params) return json_to_py(response)
Gets the historical record of this subscriber's trackable actions.
def mask(n, start, end): columns = [] value = 1 for i in range(n): if start <= end: columns.append(value if (start <= i < end) else 0) else: columns.append(value if (start <= i or i < end) else 0) value <<= 1 re...
Make a BitColumnMatrix that represents a mask. BitColumnMatrix size of n*n, to manipulate n binary bits. If start <= end, then bits in half-open range [start, end) are set. If end < start, then bits in ranges [0, end) and [start, n) are set, i.e. bits in range [end, start) are clear; oth...
def render_form(form, exclude=None, **kwargs): if hasattr(form, "Meta") and hasattr(form.Meta, "layout"): return render_layout_form(form, getattr(form.Meta, "layout"), **kwargs) if exclude: exclude = exclude.split(",") for field in exclude: form.fields.pop(field) return mark_safe("".join([ ...
Render an entire form with Semantic UI wrappers for each field Args: form (form): Django Form exclude (string): exclude fields by name, separated by commas kwargs (dict): other attributes will be passed to fields Returns: string: HTML of Django Form fields with Semantic UI wrappers
def render_layout_form(form, layout=None, **kwargs): def make_component(type_, *args): """Loop through tuples to make field wrappers for fields. """ if type_ == "Text": return "".join(args) elif type_ == "Field": result = "" for c in args: if isinstance(c, tuple): result += mak...
Render an entire form with Semantic UI wrappers for each field with a layout provided in the template or in the form class Args: form (form): Django Form layout (tuple): layout design kwargs (dict): other attributes will be passed to fields Returns: string: HTML of Django Form fields with Semant...
def set_input(self): name = self.attrs.get("_override", self.widget.__class__.__name__) self.values["field"] = str(FIELDS.get(name, FIELDS.get(None))(self.field, self.attrs))
Returns form input field of Field.
def set_label(self): if not self.field.label or self.attrs.get("_no_label"): return self.values["label"] = format_html( LABEL_TEMPLATE, self.field.html_name, mark_safe(self.field.label) )
Set label markup.
def set_help(self): if not (self.field.help_text and self.attrs.get("_help")): return self.values["help"] = HELP_TEMPLATE.format(self.field.help_text)
Set help text markup.
def set_errors(self): if not self.field.errors or self.attrs.get("_no_errors"): return self.values["class"].append("error") for error in self.field.errors: self.values["errors"] += ERROR_WRAPPER % {"message": error}
Set errors markup.
def set_icon(self): if not self.attrs.get("_icon"): return if "Date" in self.field.field.__class__.__name__: return self.values["field"] = INPUT_WRAPPER % { "field": self.values["field"], "help": self.values["help"], "style": "%sicon " % escape(pad(self.attrs.get("_align", ""))), ...
Wrap current field with icon wrapper. This setter must be the last setter called.
def set_classes(self): # Custom field classes on field wrapper if self.attrs.get("_field_class"): self.values["class"].append(escape(self.attrs.get("_field_class"))) # Inline class if self.attrs.get("_inline"): self.values["class"].append("inline") # Disabled class if self.field.field....
Set field properties and custom classes.
def render(self): self.widget.attrs = { k: v for k, v in self.attrs.items() if k[0] != "_" } self.set_input() if not self.attrs.get("_no_wrapper"): self.set_label() self.set_help() self.set_errors() self.set_classes() self.set_icon() # Must be the bottom-most setter self....
Render field as HTML.
def ready(self): from .models import Friend # Requires migrations, not necessary try: Friend.objects.get_or_create(first_name="Michael", last_name="1", age=22) Friend.objects.get_or_create(first_name="Joe", last_name="2", age=21) Friend.objects.get_or_create(first_name="Bill", last_name="3", age=20) ...
Create test friends for displaying.
def render_booleanfield(field, attrs): attrs.setdefault("_no_label", True) # No normal label for booleanfields attrs.setdefault("_inline", True) # Checkbox should be inline field.field.widget.attrs["style"] = "display:hidden" # Hidden field return wrappers.CHECKBOX_WRAPPER % { "style": pad(attrs.get("_style...
Render BooleanField with label next to instead of above.
def render_choicefield(field, attrs, choices=None): # Allow custom choice list, but if no custom choice list then wrap all # choices into the `wrappers.CHOICE_TEMPLATE` if not choices: choices = format_html_join("", wrappers.CHOICE_TEMPLATE, get_choices(field)) # Accessing the widget attrs directly saves them ...
Render ChoiceField as 'div' dropdown rather than select for more customization.
def render_iconchoicefield(field, attrs): choices = "" # Loop over every choice to manipulate for choice in field.field._choices: value = choice[1].split("|") # Value|Icon # Each choice is formatted with the choice value being split with # the "|" as the delimeter. First element is the value, the second ...
Render a ChoiceField with icon support; where the value is split by a pipe (|): first element being the value, last element is the icon.
def render_countryfield(field, attrs): choices = ((k, k.lower(), v) for k, v in field.field._choices[1:]) # Render a `ChoiceField` with all countries return render_choicefield( field, attrs, format_html_join("", wrappers.COUNTRY_TEMPLATE, choices) )
Render a custom ChoiceField specific for CountryFields.
def render_multiplechoicefield(field, attrs, choices=None): choices = format_html_join("", wrappers.CHOICE_TEMPLATE, get_choices(field)) return wrappers.MULTIPLE_DROPDOWN_WRAPPER % { "name": field.html_name, "field": field, "choices": choices, "placeholder": attrs.get("placeholder") or get_placeholder_text(...
MultipleChoiceField uses its own field, but also uses a queryset.
def render_datefield(field, attrs, style="date"): return wrappers.CALENDAR_WRAPPER % { "field": field, "style": pad(style), "align": pad(attrs.get("_align", "")), "icon": format_html(wrappers.ICON_TEMPLATE, attrs.get("_icon")), }
DateField that uses wrappers.CALENDAR_WRAPPER.
def render_filefield(field, attrs): field.field.widget.attrs["style"] = "display:none" if not "_no_label" in attrs: attrs["_no_label"] = True return wrappers.FILE_WRAPPER % { "field": field, "id": "id_" + field.name, "style": pad(attrs.get("_style", "")), "text": escape(attrs.get("_text", "Select File"...
Render a typical File Field.
def _traverse_iter(o, tree_types=(list, tuple)): SIMPLERANDOM_BITS = 32 SIMPLERANDOM_MOD = 2**SIMPLERANDOM_BITS SIMPLERANDOM_MASK = SIMPLERANDOM_MOD - 1 if isinstance(o, tree_types) or getattr(o, '__iter__', False): for value in o: for subvalue in _traverse_iter(value): ...
Iterate over nested containers and/or iterators. This allows generator __init__() functions to be passed seeds either as a series of arguments, or as a list/tuple.
def _repeat_iter(input_iter): last_value = None for value in input_iter: last_value = value yield value if last_value is not None: while True: yield last_value
Iterate over the input iter values. Then repeat the last value indefinitely. This is useful to repeat seed values when an insufficient number of seeds are provided. E.g. KISS(1) effectively becomes KISS(1, 1, 1, 1), rather than (if we just used default values) KISS(1, default-value, default-value, defa...
def _geom_series_uint32(r, n): if n == 0: return 0 if n == 1 or r == 0: return 1 m = 2**32 # Split (r - 1) into common factors with the modulo 2**32 -- i.e. all # factors of 2; and other factors which are coprime with the modulo 2**32. other_factors = r - 1 common_factor...
Unsigned integer calculation of sum of geometric series: 1 + r + r^2 + r^3 + ... r^(n-1) summed to n terms. Calculated modulo 2**32. Use the formula (r**n - 1) / (r - 1)
def lfsr_next_one_seed(seed_iter, min_value_shift): try: seed = seed_iter.next() except StopIteration: return 0xFFFFFFFF else: if seed is None: return 0xFFFFFFFF else: seed = int(seed) & 0xFFFFFFFF working_seed = (seed ^ (seed << 16)) ...
High-quality seeding for LFSR generators. The LFSR generator components discard a certain number of their lower bits when generating each output. The significant bits of their state must not all be zero. We must ensure that when seeding the generator. In case generators are seeded from an incr...
def seed(self, x=None, *args): if x is None: # Use same random seed code copied from Python's random.Random try: x = long(_hexlify(_urandom(16)), 16) except NotImplementedError: import time x = long(time.time() * 256) #...
For consistent cross-platform seeding, provide an integer seed.
def setbpf(self, bpf): self._bpf = min(bpf, self.BPF) self._rng_n = int((self._bpf + self.RNG_RANGE_BITS - 1) / self.RNG_RANGE_BITS)
Set number of bits per float output
def get_info(cls): mod = try_import(cls.mod_name) if not mod: return None version = getattr(mod, '__version__', None) or getattr(mod, 'version', None) return BackendInfo(version or 'deprecated', '')
Return information about backend and its availability. :return: A BackendInfo tuple if the import worked, none otherwise.
def get_choices(field): empty_label = getattr(field.field, "empty_label", False) needs_empty_value = False choices = [] # Data is the choices if hasattr(field.field, "_choices"): choices = field.field._choices # Data is a queryset elif hasattr(field.field, "_queryset"): queryset = field.field._queryset ...
Find choices of a field, whether it has choices or has a queryset. Args: field (BoundField): Django form boundfield Returns: list: List of choices
def _raise_for_status(self, response, explanation=None): try: response.raise_for_status() except requests.exceptions.HTTPError as e: if e.response.status_code == 404: raise errors.NotFound(e, response, explanation=explanation) raise errors.API...
Raises stored :class:`APIError`, if one occurred.
def get_class_list(cls) -> DOMTokenList: cl = [] cl.append(DOMTokenList(cls, cls.class_)) if cls.inherit_class: for base_cls in cls.__bases__: if issubclass(base_cls, WdomElement): cl.append(base_cls.get_class_list()) # Reverse ord...
Get class-level class list, including all super class's.
def removeClass(self, *classes: str) -> None: _remove_cl = [] for class_ in classes: if class_ not in self.classList: if class_ in self.get_class_list(): logger.warning( 'tried to remove class-level class: ' ...
[Not Standard] Remove classes from this node.
def appendChild(self, child: 'WdomElement') -> Node: if self.connected: self._append_child_web(child) return self._append_child(child)
Append child node at the last of child nodes. If this instance is connected to the node on browser, the child node is also added to it.
def insertBefore(self, child: Node, ref_node: Node) -> Node: if self.connected: self._insert_before_web(child, ref_node) return self._insert_before(child, ref_node)
Insert new child node before the reference child node. If the reference node is not a child of this node, raise ValueError. If this instance is connected to the node on browser, the child node is also added to it.
def removeChild(self, child: Node) -> Node: if self.connected: self._remove_child_web(child) return self._remove_child(child)
Remove the child node from this node. If the node is not a child of this node, raise ValueError.
def replaceChild(self, new_child: 'WdomElement', old_child: 'WdomElement' ) -> Node: if self.connected: self._replace_child_web(new_child, old_child) return self._replace_child(new_child, old_child)
Replace child nodes.
def textContent(self, text: str) -> None: # type: ignore self._set_text_content(text) if self.connected: self._set_text_content_web(text)
Set textContent both on this node and related browser node.
def innerHTML(self, html: str) -> None: # type: ignore df = self._parse_html(html) if self.connected: self._set_inner_html_web(df.html) self._empty() self._append_child(df)
Set innerHTML both on this node and related browser node.
def click(self) -> None: if self.connected: self.js_exec('click') else: # Web上に表示されてれば勝手にブラウザ側からクリックイベント発生する # のでローカルのクリックイベント不要 msg = {'proto': '', 'type': 'click', 'currentTarget': {'id': self.wdom_id}, 'tar...
Send click event.
def getElementById(id: str) -> Optional[Node]: elm = Element._elements_with_id.get(id) return elm
Get element with ``id``.
def getElementByWdomId(id: str) -> Optional[WebEventTarget]: if not id: return None elif id == 'document': return get_document() elif id == 'window': return get_document().defaultView elm = WdomElement._elements_with_wdom_id.get(id) return elm
Get element with ``wdom_id``.
def _cleanup(path: str) -> None: if os.path.isdir(path): shutil.rmtree(path)
Cleanup temporary directory.
def create_element(tag: str, name: str = None, base: type = None, attr: dict = None) -> Node: from wdom.web_node import WdomElement from wdom.tag import Tag from wdom.window import customElements if attr is None: attr = {} if name: base_class = customElements....
Create element with a tag of ``name``. :arg str name: html tag. :arg type base: Base class of the created element (defatlt: ``WdomElement``) :arg dict attr: Attributes (key-value pairs dict) of the new element.
def characterSet(self, charset: str) -> None: charset_node = self._find_charset_node() or Meta(parent=self.head) charset_node.setAttribute('charset', charset)
Set character set of this document.
def title(self) -> str: title_element = _find_tag(self.head, 'title') if title_element: return title_element.textContent return ''
Get/Set title string of this document.
def getElementsBy(self, cond: Callable[[Element], bool]) -> NodeList: return getElementsBy(self, cond)
Get elements in this document which matches condition.
def getElementById(self, id: str) -> Optional[Node]: elm = getElementById(id) if elm and elm.ownerDocument is self: return elm return None
Get element by ``id``. If this document does not have the element with the id, return None.
def createElement(self, tag: str) -> Node: return create_element(tag, base=self._default_class)
Create new element whose tag name is ``tag``.
def getElementByWdomId(self, id: Union[str]) -> Optional[WebEventTarget]: elm = getElementByWdomId(id) if elm and elm.ownerDocument is self: return elm return None
Get an element node with ``wdom_id``. If this document does not have the element with the id, return None.
def add_jsfile(self, src: str) -> None: self.body.appendChild(Script(src=src))
Add JS file to load at this document's bottom of the body.
def add_jsfile_head(self, src: str) -> None: self.head.appendChild(Script(src=src))
Add JS file to load at this document's header.
def add_cssfile(self, src: str) -> None: self.head.appendChild(Link(rel='stylesheet', href=src))
Add CSS file to load at this document's header.
def register_theme(self, theme: ModuleType) -> None: if not hasattr(theme, 'css_files'): raise ValueError('theme module must include `css_files`.') for css in getattr(theme, 'css_files', []): self.add_cssfile(css) for js in getattr(theme, 'js_files', []): ...
Set theme for this docuemnt. This method sets theme's js/css files and headers on this document. :arg ModuleType theme: a module which has ``js_files``, ``css_files``, ``headers``, and ``extended_classes``. see ``wdom.themes`` directory actual theme module structures.
def build(self) -> str: self._set_autoreload() return ''.join(child.html for child in self.childNodes)
Return HTML representation of this document.
def block_get(self, block): res = self._get(self._url("/chain/blocks/{0}", block)) return self._result(res, True)
GET /chain/blocks/{Block} Use the Block API to retrieve the contents of various blocks from the blockchain. The returned Block message structure is defined inside fabric.proto. ```golang message Block { uint32 version = 1; google.protobuf.Timestamp Times...
def send_message() -> None: if not _msg_queue: return msg = json.dumps(_msg_queue) _msg_queue.clear() for conn in module.connections: conn.write_message(msg)
Send message via WS to all client connections.
def add_static_path(prefix: str, path: str, no_watch: bool = False) -> None: app = get_app() app.add_static_path(prefix, path) if not no_watch: watch_dir(path)
Add directory to serve static files. First argument ``prefix`` is a URL prefix for the ``path``. ``path`` must be a directory. If ``no_watch`` is True, any change of the files in the path do not trigger restart if ``--autoreload`` is enabled.
def start_server(address: str = None, port: int = None, check_time: int = 500, **kwargs: Any) -> module.HTTPServer: # Add application's static files directory from wdom.document import get_document add_static_path('_static', STATIC_DIR) doc = get_document() if os.path.exists(do...
Start web server on ``address:port``. Use wrapper function :func:`start` instead. :arg str address: address of the server [default: localhost]. :arg int port: tcp port of the server [default: 8888]. :arg int check_time: millisecondes to wait until reload browser when autoreload is enabled [def...
def start(**kwargs: Any) -> None: start_server(**kwargs) try: asyncio.get_event_loop().run_forever() except KeyboardInterrupt: stop_server()
Start web server. Run until ``Ctrl-c`` pressed, or if auto-shutdown is enabled, until when all browser windows are closed. This function accepts keyword areguments same as :func:`start_server` and all arguments passed to it.
def define(self, *args: Any, **kwargs: Any) -> None: if isinstance(args[0], str): self._define_orig(*args, **kwargs) elif isinstance(args[0], type): self._define_class(*args, **kwargs) else: raise TypeError( 'Invalid argument for defin...
Add new custom element.
def log_handler(level: str, message: str) -> None: message = 'JS: ' + str(message) if level == 'error': logger.error(message) elif level == 'warn': logger.warning(message) elif level == 'info': logger.info(message) elif level == 'debug': logger.debug(message)
Handle logs from client (browser).
def event_handler(msg: EventMsgDict) -> Event: e = create_event_from_msg(msg) if e.currentTarget is None: if e.type not in ['mount', 'unmount']: id = msg['currentTarget']['id'] logger.warning('No such element: wdom_id={}'.format(id)) return e e.currentTarget.on_e...
Handle events emitted on browser.
def response_handler(msg: Dict[str, str]) -> None: from wdom.document import getElementByWdomId id = msg['id'] elm = getElementByWdomId(id) if elm: elm.on_response(msg) else: logger.warning('No such element: wdom_id={}'.format(id))
Handle response sent by browser.
def on_websocket_message(message: str) -> None: msgs = json.loads(message) for msg in msgs: if not isinstance(msg, dict): logger.error('Invalid WS message format: {}'.format(message)) continue _type = msg.get('type') if _type == 'log': log_handler...
Handle messages from browser.
def parse_html(html: str, parser: FragmentParser = None) -> Node: parser = parser or FragmentParser() parser.feed(html) return parser.root
Parse HTML fragment and return DocumentFragment object. DocumentFragment object has parsed Node objects as its child nodes.
def getElementsBy(start_node: ParentNode, cond: Callable[['Element'], bool]) -> NodeList: elements = [] for child in start_node.children: if cond(child): elements.append(child) elements.extend(child.getElementsBy(cond)) return NodeList(elements)
Return list of child elements of start_node which matches ``cond``. ``cond`` must be a function which gets a single argument ``Element``, and returns boolean. If the node matches requested condition, ``cond`` should return True. This searches all child elements recursively. :arg ParentNode start_n...
def getElementsByTagName(start_node: ParentNode, tag: str) -> NodeList: _tag = tag.upper() return getElementsBy(start_node, lambda node: node.tagName == _tag)
Get child nodes which tag name is ``tag``.
def getElementsByClassName(start_node: ParentNode, class_name: str ) -> NodeList: classes = set(class_name.split(' ')) return getElementsBy( start_node, lambda node: classes.issubset(set(node.classList)) )
Get child nodes which has ``class_name`` class attribute.
def add(self, *tokens: str) -> None: from wdom.web_node import WdomElement _new_tokens = [] for token in tokens: self._validate_token(token) if token and token not in self: self._list.append(token) _new_tokens.append(token) ...
Add new tokens to list.