def field_group(cls="form-group"): html = HTMLDoc() div = html.create_element('div') div.set_attribute('class', cls) return div
def __init__(self, css_menu='menu menu-vertical menu-theme'): self._html_object = HTMLDoc() self._ol = self._html_object.create_element('ol') if css_menu is not None: self._ol.set_attribute('class', css_menu) self.submenus = {}
def field_label(field, label=None, cls=None): html = HTMLDoc() html_label = html.create_element('label') html_label.set_attribute('for', field) if cls: html_label.set_attribute('class', cls) html_label.append(label) return html
def error_page(title, description): dom = HTMLDoc() html = dom.create_element('html') head = html.create_element('head') t = head.create_element('title') t.append(title) body = html.create_element('body') h1 = body.create_element('h1') h1.append(title) if description: h2 = body.create_element('h2') h2.append(description) return dom.get()
def __init__(self, name='Site', logo=None, url='#', style=None, css="navbar-expand-lg navbar-light bg-light"): self._html_object = HTMLDoc() nav = self._html_object.create_element('nav') nav.set_attribute('class', 'navbar ' + css) if style is not None: nav.set_attribute('style', style) navbar_brand = nav.create_element('a') navbar_brand.set_attribute('class', 'navbar-brand') navbar_brand.set_attribute('href', url) if logo is not None: img = navbar_brand.create_element('img') img.set_attribute('src', logo) img.set_attribute('alt', 'Logo') img.set_attribute('height', '30') if logo and name: img.set_attribute('class', 'mr-2') if name is not None: navbar_brand.append(name) toggle = nav.create_element('button') toggle.set_attribute('class', 'navbar-toggler') toggle.set_attribute('type', 'button') toggle.set_attribute('data-toggle', 'collapse') toggle.set_attribute('data-target', '#navbarSupportedContent') toggle.set_attribute('aria-controls', 'navbarSupportedContent') toggle.set_attribute('aria-expanded', 'false') toggle.set_attribute('aria-label', 'Toggle navigation') toggle_span = toggle.create_element('span') toggle_span.set_attribute('class', 'navbar-toggler-icon') div = nav.create_element('div') div.set_attribute('class', 'collapse navbar-collapse') div.set_attribute('id', 'navbarSupportedContent') ul = div.create_element('ul') ul.set_attribute('class', 'navbar-nav mr-auto') self._ul = ul self.submenus = OrderedDict()
def __init__(self, name='Site', logo=None, url='#', style=None, css="navbar-expand-lg navbar-light bg-light"): self._html_object = HTMLDoc() nav = self._html_object.create_element('nav') div = nav.create_element('div') div.set_attribute('class', 'navmenu') ul = div.create_element('ul') self._ul = ul self.submenus = OrderedDict()
def error_ajax(title, description): dom = HTMLDoc() title = dom.create_element('B') title.append(title) if description: dom.create_element('<BR>') dom.append(description) return dom.get()
def static(req, resp): """Serves files from static directory""" resp.content_type = const.TEXT_HTML static = g.app.config.get('application', 'static').strip('/') static_path_re = re.compile("^\/%s\/%s" % ( req.app.strip('/'), static, )) sfile_path = '/' + req.app.strip('/') + '/' + req.route.strip('/') sfile_path = static_path_re.sub('', sfile_path) sfile_path = g.app.path.rstrip('/') + '/static' + sfile_path if os.path.isfile(sfile_path): sfile = open(sfile_path, 'rb').read() resp.content_type = const.APPLICATION_OCTET_STREAM mime_type = mimetypes.guess_type(sfile_path) if mime_type[0] is not None: resp.content_type = mime_type[0] if mime_type[1] is not None: resp.content_type += ';charset=%s' % mime_type[1] return sfile elif os.path.isdir(sfile_path): page = HTMLDoc() resp.content_type = const.TEXT_HTML folder = os.listdir(sfile_path) html = page.create_element('HTML') head = html.create_element('HEAD') title = head.create_element('TITLE') title.append(req.route) body = html.create_element('BODY') h1 = body.create_element('H1') h1.append(req.route) for item in folder: item = req.route.rstrip('/') + '/' + item a = body.create_element('A') a.set_attribute('href', item) a.append(item) body.create_element('BR') h3 = body.create_element('H3') h3.append(metadata.identity) return str(page) else: raise FileNotFoundError("No such file or directory: '%s'" % sfile_path)
def static(req, resp): sfile_path = g.app.app_root.rstrip('/') + '/static' \ + '/' + '/'.join(req.relative_resource_uri.strip('/').split('/')[1:]) try: if os.path.isfile(sfile_path): sfile = open(sfile_path, 'rb').read() resp.content_type = const.APPLICATION_OCTET_STREAM mime_type = mimetypes.guess_type(sfile_path) if mime_type is not None: resp.content_type = mime_type[0] if mime_type[1] is not None: resp.content_type += ';charset=%s' % mime_type[1] return sfile elif os.path.isdir(sfile_path): page = HTMLDoc() resp.content_type = const.TEXT_HTML folder = os.listdir(sfile_path) html = page.create_element('HTML') head = html.create_element('HEAD') title = head.create_element('TITLE') title.append(req.relative_resource_uri) body = html.create_element('BODY') h1 = body.create_element('H1') h1.append(req.relative_resource_uri) for item in folder: item = req.relative_resource_uri.rstrip('/') + '/' + item a = body.create_element('A') a.set_attribute('href', item) a.append(item) body.create_element('BR') h3 = body.create_element('H3') h3.append(metadata.identity) return str(page) else: raise FileNotFoundError("No such file or directory: '%s'" % sfile_path) except Exception as e: return "Error %s" % (e,)
def form(model, values=None, readonly=False): html = HTMLDoc() fields = model.fields if values is None and not isinstance(model, type): values = model.dict elif values is None: values = {} def html_field(field): if obj.readonly is True: if value is None: field_readonly = False else: field_readonly = True else: field_readonly = readonly if obj.null: required = False else: required = True label = obj.label if isinstance(obj, Model.Enum): html.append( field_select(field, obj.enum, value=value, readonly=field_readonly, disabled=field_readonly, label=label, callback=obj.callback, data_url=obj.data_url, data_endpoint=obj.data_endpoint)) elif isinstance(obj, Model.DateTime): html.append( field_datetime(field, value=value, readonly=field_readonly, disabled=field_readonly, required=required, placeholder=obj.placeholder, label=label)) elif isinstance(obj, Model.Boolean): if value: checked = True else: checked = False html.append( field_checkbox(field, value=True, disabled=field_readonly, checked=checked, label=label, attrs={'data-boolean': None})) elif isinstance(obj, (Model.LongText, Model.MediumText)): html.append( field_textarea(field, value=value, readonly=field_readonly, disabled=field_readonly, required=required, placeholder=obj.placeholder, label=label)) elif isinstance(obj, Model.Password): html.append( field_password(field, value=value, readonly=field_readonly, disabled=field_readonly, required=required, placeholder=obj.placeholder, label=label)) elif isinstance(obj, Model.Uuid): html.append( field_select(field, None, value=value, readonly=field_readonly, disabled=field_readonly, label=label, callback=obj.callback)) elif isinstance( obj, (Model.Decimal, Model.Double, Model.Float, Model.String, Model.BaseInteger, Model.Ip4, Model.Ip6)): html.append( field_text(field, value=value, readonly=field_readonly, disabled=field_readonly, required=required, placeholder=obj.placeholder, label=label)) else: pass for field in fields: obj = fields[field] if obj.hidden is False and obj.internal is False: value = values.get(field) if value is None: value = obj.default if hasattr(value, '__call__'): value = value() html_field(field) return html
class NAVMenu(object): """CSS HTML Menu. Args: name (str): Name of the Application. logo (str): URL location of the logo image. url (str): Application URL. style (str): In-line CSS style to be applied to Menu. css (str): CSS to be applied to Menu. """ def __init__(self, name='Site', logo=None, url='#', style=None, css="navbar-expand-lg navbar-light bg-light"): self._html_object = HTMLDoc() nav = self._html_object.create_element('nav') nav.set_attribute('class', 'navbar ' + css) if style is not None: nav.set_attribute('style', style) navbar_brand = nav.create_element('a') navbar_brand.set_attribute('class', 'navbar-brand') navbar_brand.set_attribute('href', url) if logo is not None: img = navbar_brand.create_element('img') img.set_attribute('src', logo) img.set_attribute('alt', 'Logo') img.set_attribute('height', '30') if logo and name: img.set_attribute('class', 'mr-2') if name is not None: navbar_brand.append(name) toggle = nav.create_element('button') toggle.set_attribute('class', 'navbar-toggler') toggle.set_attribute('type', 'button') toggle.set_attribute('data-toggle', 'collapse') toggle.set_attribute('data-target', '#navbarSupportedContent') toggle.set_attribute('aria-controls', 'navbarSupportedContent') toggle.set_attribute('aria-expanded', 'false') toggle.set_attribute('aria-label', 'Toggle navigation') toggle_span = toggle.create_element('span') toggle_span.set_attribute('class', 'navbar-toggler-icon') div = nav.create_element('div') div.set_attribute('class', 'collapse navbar-collapse') div.set_attribute('id', 'navbarSupportedContent') ul = div.create_element('ul') ul.set_attribute('class', 'navbar-nav mr-auto') self._ul = ul self.submenus = OrderedDict() def submenu(self, name): """Create new submenu item. Add submenu on menu and returns submenu for adding more items. Args: name (str): Name of submenu item. Returns meny object. """ class Submenu(object): def __init__(self, name, parent): # Create new menu for submenu. self._column_count = 0 self._row = None li = parent.create_element('li') li.set_attribute('class', 'nav-item dropdown') a = li.create_element('a') a.set_attribute('class', 'nav-link dropdown-toggle') name_id = 'dropdown_' + name.replace(' ', '').replace('-', '_') a.set_attribute('id', name_id) a.set_attribute('role', 'button') a.set_attribute('data-toggle', 'dropdown') a.set_attribute('aria-haspopup', 'true') a.set_attribute('aria-expanded', 'false') a.set_attribute('href', '#') a.append(name) div = li.create_element('div') div.set_attribute('class', 'dropdown-menu') div.set_attribute('aria-labelledby', name_id) table = div.create_element('table') self._html_object = table def link(self, name, href='#', active=False, **kwargs): kwargs = orderdict(kwargs) """Add submenu item. Args: name (str): Menu item name. href (str): Url for link. (default '#') Kwargs: Kwargs are used to additional flexibility. Kwarg key and values are used for properties of <a>. """ if self._row is None or self._column_count > 1: self._column_count = 0 self._row = self._html_object.create_element('tr') column = self._row.create_element('td') a = column.create_element('a') a.set_attribute('class', 'dropdown-item') a.set_attribute('href', href) for kwarg in kwargs: a.set_attribute(kwarg, kwargs[kwarg]) a.append(name) self._column_count += 1 def submenu(self, name): return self # Create new menu for submenu. if name in self.submenus: return self.submenus[name] else: submenu = Submenu(name, self._ul) # Add Submenu to submenu cache. self.submenus[name] = submenu return submenu def link(self, name, href='#', active=False, **kwargs): """Add submenu item. Args: name (str): Menu item name. href (str): Url for link. (default '#') Kwargs: Kwargs are used to additional flexibility. Kwarg key and values are used for properties of <a> attribute. """ kwargs = orderdict(kwargs) li = self._ul.create_element('li') if active: li.set_attribute('class', 'nav-item active') else: li.set_attribute('class', 'nav-item') a = li.create_element('a') a.set_attribute('class', 'nav-link') a.set_attribute('href', href) for kwarg in kwargs: a.set_attribute(kwarg, kwargs[kwarg]) a.append(name) def __str__(self): return str(self._html_object)
def handle_error(self, req, resp, exception, traceback): title = None description = None try: resp.status = exception.status except AttributeError: if isinstance(exception, AccessDenied): resp.status = 403 elif isinstance(exception, NotFound): resp.status = 404 elif isinstance(exception, JSONDecodeError): resp.status = 400 elif isinstance(exception, FieldError): resp.status = 400 elif isinstance(exception, ValidationError): resp.status = 400 else: resp.status = 500 if isinstance(exception, FieldError): description = str(exception) if title is None: try: title = exception.title except AttributeError: if resp.status in HTTP_STATUS_CODES: title = str( resp.status) + ' ' + HTTP_STATUS_CODES[resp.status] else: title = exception.__class__.__name__ if description is None: try: description = exception.description except AttributeError: description = str(exception) try: for header in exception.headers: resp.set_header(header, exception.headers[header]) except AttributeError: pass if 'error_template' in g: return render_template(g, title, description) elif resp.content_type is None or 'json' in resp.content_type.lower(): to_return = {} to_return['error'] = {} to_return['error']['title'] = title to_return['error']['description'] = description return to_return elif 'html' in resp.content_type.lower(): dom = HTMLDoc() html = dom.create_element('html') head = html.create_element('head') t = head.create_element('title') t.append(resp.status) body = html.create_element('body') h1 = body.create_element('h1') h1.append(title) h2 = body.create_element('h2') h2.append(description) return dom.get() else: return title + ' ' + description
def select(name, options, selected, empty=False, cls=None, onchange=None, disabled=False, readonly=False, data_url=None, data_endpoint=None): html = HTMLDoc() select = html.create_element('select') select.set_attribute('name', name) select.set_attribute('id', name) if data_url: select.set_attribute('data-url', data_url) if data_endpoint: select.set_attribute('data-endpoint', data_endpoint) if onchange is not None: select.set_attribute('onchange', onchange) if cls is not None: select.set_attribute('class', cls) if empty is True: option = select.create_element('option') option.set_attribute('value', '') option.append('') if options is not None: for opt in options: if isinstance(options, (list, tuple,)): if isinstance(opt, (list, tuple,)): try: option = select.create_element('option') option.set_attribute('value', opt[0]) option.append(opt[1]) if opt[0] == selected: option.set_attribute('selected') selected = opt[1] except IndexError: raise ValueError('Malformed values for HTML select') else: if opt is not None: option = select.create_element('option') option.set_attribute('value', opt) if opt == selected: option.set_attribute('selected') selected = opt option.append(opt) elif isinstance(options, dict): option = select.create_element('option') option.set_attribute('value', opt) if opt == selected: option.set_attribute('selected') selected = options[opt] option.append(options[opt]) if disabled or readonly: input = html.create_element('input') input.set_attribute('type', 'text') input.set_attribute('id', name) input.set_attribute('name', name) input.set_attribute('disabled') if selected is not None: input.set_attribute('value', selected) input.set_attribute('class', 'form-control') return input return html
class HMenu(object): """CSS HTML Menu. """ def __init__(self, name='Site', logo=None, url='#', style=None, css="navbar-expand-lg navbar-light bg-light"): self._html_object = HTMLDoc() nav = self._html_object.create_element('nav') div = nav.create_element('div') div.set_attribute('class', 'navmenu') ul = div.create_element('ul') self._ul = ul self.submenus = OrderedDict() def submenu(self, name): """Create new submenu item. Add submenu on menu and returns submenu for adding more items. Args: name (str): Name of submenu item. Returns meny object. """ class Submenu(object): def __init__(self, name, parent, feather='plus-circle'): self.submenus = OrderedDict() # Create new menu for submenu. li = parent.create_element('li') a = li.create_element('a') a.set_attribute('role', 'button') a.set_attribute('href', '#') a.set_attribute('data-event', 'dropdown') span = a.create_element('span') span.set_attribute('data-feather', feather) a.append(name) ul = li.create_element('ul') self._ul = ul def link(self, name, href='#', feather='corner-down-right', **kwargs): kwargs = orderdict(kwargs) """Add submenu item. Args: name (str): Menu item name. href (str): Url for link. (default '#') Kwargs: Kwargs are used to additional flexibility. Kwarg key and values are used for properties of <a>. """ li = self._ul.create_element('li') a = li.create_element('a') a.set_attribute('href', href) for kwarg in kwargs: a.set_attribute(kwarg, kwargs[kwarg]) span = a.create_element('span') span.set_attribute('data-feather', feather) a.append(name) def submenu(self, name): # Create new menu for submenu. if name in self.submenus: return self.submenus[name] else: submenu = Submenu(name, self._ul) # Add Submenu to submenu cache. self.submenus[name] = submenu return submenu # Create new menu for submenu. if name in self.submenus: return self.submenus[name] else: submenu = Submenu(name, self._ul) # Add Submenu to submenu cache. self.submenus[name] = submenu return submenu def link(self, name, href='#', feather='arrow-right-circle', **kwargs): """Add submenu item. Args: name (str): Menu item name. href (str): Url for link. (default '#') Kwargs: Kwargs are used to additional flexibility. Kwarg key and values are used for properties of <a> attribute. """ kwargs = orderdict(kwargs) li = self._ul.create_element('li') a = li.create_element('a') a.set_attribute('href', href) for kwarg in kwargs: a.set_attribute(kwarg, kwargs[kwarg]) span = a.create_element('span') span.set_attribute('data-feather', feather) a.append(name) def __str__(self): return str(self._html_object)
class Menu(object): """CSS HTML Menu. This class is used to define and generate a simple menu driven by css. Requires following css are bare minimum included in modole docuementation. However css needed is already included in the UI by defaolt. Returns html menu. """ def __init__(self, css_menu='menu menu-vertical menu-theme'): self._html_object = HTMLDoc() self._ol = self._html_object.create_element('ol') if css_menu is not None: self._ol.set_attribute('class', css_menu) self.submenus = {} def submenu(self, name, image=None): """Create new submenu item. Add submenu on menu and returns submenu for adding more items. Args: name (str): Name of submenu item. Returns meny object. """ # Create new menu for submenu. if name in self.submenus: return self.submenus[name] else: submenu = self.__class__(css_menu=None) # Add Submenu to submenu cache. self.submenus[name] = submenu li = self._ol.create_element('li') a = li.create_element('a') a.set_attribute('href','#') if image is not None: img = a.create_element('img') img.set_attribute('alt', name) img.set_attribute('title', name) img.set_attribute('src', image) else: a.append(name) span = a.create_element('span') span.set_attribute('class', 'caret') li.append(submenu._html_object) return submenu def link(self, name, href='#', image=None, **kwargs): """Add submenu item. Args: name (str): Menu item name. href (str): Url for link. (default '#') Kwargs: Kwargs are used to additional flexibility. Kwarg key and values are used for properties of <a> attribute. """ li = self._ol.create_element('li') a = li.create_element('a') a.set_attribute('href', href) for kwarg in kwargs: a.set_attribute(kwarg, **kwargs) if image is not None: img = a.create_element('img') img.set_attribute('alt', name) img.set_attribute('title', name) img.set_attribute('src', image) else: a.append(name) def __str__(self): return str(self._html_object)
def form(model, values=None, readonly=False): html = HTMLDoc() fields = model.fields if values is None and not isinstance(model, type): values = model.dict elif values is None: values = {} def html_field(field): value = values.get(field) if value is None: value = obj.default if hasattr(value, '__call__'): value = value() form_group = html.create_element('div') form_group.set_attribute('class', 'form-group') label = form_group.create_element('label') label.set_attribute('class', 'control-label col-sm-2') label.set_attribute('for', 'field') if obj.label is not None: label.append(obj.label) else: label.append(obj.name.title().replace('_', ' ')) div = form_group.create_element('div') div.set_attribute('class', 'col-sm-10') if obj.readonly is True: field_readonly = True else: field_readonly = readonly if isinstance(obj, Model.Enum): div.append( select(field, obj.enum, value, cls="select", readonly=field_readonly)) elif isinstance(obj, Model.DateTime): if value is not None: value = format_datetime(value) input = div.create_element('input') input.set_attribute('type', 'text') input.set_attribute('class', 'form-control') input.set_attribute('id', field) input.set_attribute('name', field) if readonly is True: input.set_attribute('readonly') input.set_attribute('disabled') if obj.placeholder is not None: input.set_attribute('placeholder', obj.placeholder) if value is not None: input.set_attribute('value', value) if field_readonly: input.set_attribute('readonly') input.set_attribute('disabled') if obj.null is False: input.set_attribute('required') if obj.placeholder: input.set_attribute('placeholder', obj.placeholder) elif isinstance(obj, Model.Boolean): input = div.create_element('input') input.set_attribute('type', 'checkbox') input.set_attribute('id', field) input.set_attribute('name', field) if field_readonly is True: input.set_attribute('disabled') if value is True: input.set_attribute('checked') input.set_attribute('value', 'true') elif isinstance(obj, ( Model.String, Model.Confirm, )): input = div.create_element('input') if obj.password is False: input.set_attribute('type', 'text') else: input.set_attribute('type', 'password') input.set_attribute('class', 'form-control') input.set_attribute('id', field) input.set_attribute('name', field) if readonly is True: input.set_attribute('readonly') input.set_attribute('disabled') if obj.placeholder is not None: input.set_attribute('placeholder', obj.placeholder) if value is not None: input.set_attribute('value', value) if field_readonly: input.set_attribute('readonly') input.set_attribute('disabled') if obj.null is False: input.set_attribute('required') if obj.placeholder: input.set_attribute('placeholder', obj.placeholder) else: pass for field in fields: obj = fields[field] if obj.hidden is False and obj.internal is False: html_field(field) return html