def _get_title(self, action, obj=None): name = getattr(self.model, '__verbose_name__', '') if action == 'add': return _("Add") + safe_unicode(name) elif action == 'edit': return _("Edit") + safe_unicode(name) elif action == 'view': return _("View") + safe_unicode(name)
def ungettext(msgid1, msgid2, n): try: t = translation(_domain) except IOError: if n == 1: return msgid1 else: return msgid2 return t.ungettext(safe_unicode(msgid1), safe_unicode(msgid2), n)
def ugettext(message): try: t = translation(_domain) except IOError: return message if PY2: return t.ugettext(safe_unicode(message)) else: return t.gettext(safe_unicode(message))
def create_pagination( url, total, page, rows, length=None, total_message=None, first=None, next=None, prev=None, last=None ): """ Create bootstrap style pagination html code :param total: total records count :param page: current page number :param rows: records count per page :param url: base url for page link :param length: the maximum of page links """ import math from uliweb import settings from uliweb.utils.common import safe_unicode length = length or settings.BOOTSTRAP_PAGINATION.length total_message = safe_unicode(total_message or settings.BOOTSTRAP_PAGINATION.total_message) first = safe_unicode(first or settings.BOOTSTRAP_PAGINATION.first) next = safe_unicode(next or settings.BOOTSTRAP_PAGINATION.next) prev = safe_unicode(prev or settings.BOOTSTRAP_PAGINATION.prev) last = safe_unicode(last or settings.BOOTSTRAP_PAGINATION.last) def get_url(p): from uliweb.utils.common import query_string return query_string(url, page=p) pages = int(math.ceil(total * 1.0 / rows)) begin = max(1, page - length / 2 + 1) end = min(pages, begin + length - 1) begin = max(1, end - length + 1) buf = [] buf.append("<ul>") total_message = total_message.replace("$pages", str(pages)) total_message = total_message.replace("$total", str(total)) buf.append('<li class="disabled total"><a href="#">%s</a></li>' % total_message) if pages and (begin != 1): buf.append('<li class="first"><a href="%s">%s</a></li>' % (get_url(1), first)) if pages and (page != 1): buf.append('<li class="prev"><a href="%s">%s</a></li>' % (get_url(page - 1), prev)) for i in range(begin, end + 1): if page == i: cls = " active" href = "#" else: cls = "" href = get_url(i) buf.append('<li class="page%s"><a href="%s">%s</a></li>' % (cls, href, i)) if pages and (page != pages): buf.append('<li class="next"><a href="%s">%s</a></li>' % (get_url(page + 1), next)) if pages and (end != pages): buf.append('<li class="last"><a href="%s">%s</a></li>' % (get_url(pages), last)) buf.append("</ul>") return "".join(buf)
def to_python(self, data): """ Convert a data to python format. """ if data is None: return u'' return safe_unicode(data, DEFAULT_ENCODING)
def _set_width(self, col, value): from uliweb.utils.common import safe_unicode length = len(safe_unicode(value)) if self.auto_width: self.widths[col] = min(max(self.default_min_width, length), self.default_max_width)
def get_filename(self, filename, filesystem=False, convert=False, subpath=''): """ Get the filename according to self.to_path, and if filesystem is False then return unicode filename, otherwise return filesystem encoded filename @param filename: relative filename, it'll be combine with self.to_path @param filesystem: if True, then encoding the filename to filesystem @param convert: if True, then convert filename with FilenameConverter class @param subpath: sub folder in to_path """ from uliweb.utils.common import safe_unicode #make sure the filename is unicode s = settings.GLOBAL if convert: _p, _f = os.path.split(filename) _filename = os.path.join(_p, self.filename_convert(_f)) else: _filename = filename nfile = safe_unicode(_filename, s.HTMLPAGE_ENCODING) if subpath: paths = [application_path(self.to_path), subpath, nfile] else: paths = [application_path(self.to_path), nfile] f = os.path.normpath(os.path.join(*paths)).replace('\\', '/') if filesystem: return files.encode_filename(f, to_encoding=s.FILESYSTEM_ENCODING) return f
def get_filename(self, filename, filesystem=False, convert=False): """ Get the filename according to self.to_path, and if filesystem is False then return unicode filename, otherwise return filesystem encoded filename @param filename: relative filename, it'll be combine with self.to_path @param filesystem: if True, then encoding the filename to filesystem @param convert: if True, then convert filename with FilenameConverter class """ from uliweb.utils.common import safe_unicode #make sure the filename is unicode s = settings.GLOBAL if convert: _p, _f = os.path.split(filename) _filename = os.path.join(_p, self.filename_convert(_f)) else: _filename = filename nfile = safe_unicode(_filename, s.HTMLPAGE_ENCODING) f = os.path.normpath(os.path.join(self.to_path, nfile)).replace('\\', '/') if filesystem: return files.encode_filename(f, to_encoding=s.FILESYSTEM_ENCODING) return f
def generic_add(model=None, get_url=get_url, layout=None, template=None, title=None, view=None, data=None): from uliweb.utils.generic import AddView from uliweb import response if not view: Model = get_model(model) if not model or not Model: return error("Can't find model [%s], please check it" % model) get_url = partial(get_url, action='view') view = AddView(model, get_url) result = view.run() if isinstance(result, dict): layout = layout or 'layout.html' template = template or 'generic_add.html' response.template = template if not title: name = getattr(model, '__verbose_name__', '') title = _("Add") + safe_unicode(name) elif callable(title): title = title('add') data = data or {} result['layout'] = layout result['get_url'] = get_url result['title'] = title result.update(data) return result
def generic_edit(model=None, id=None, obj=None, get_url=get_url, layout='layout.html', template=None, title=None, view=None, data=None): from uliweb.utils.generic import EditView from uliweb import response if not view: Model = get_model(model) if not model or not Model: return error("Can't find model [%s], please check it" % model) if not obj: obj = Model.get(Model.c.id == int(id)) view = EditView(model, get_url('view', id=id), obj=obj) result = view.run() if isinstance(result, dict): template = template or 'generic_edit.html' response.template = template if not title: name = getattr(model, '__verbose_name__', '') title = _("View") + safe_unicode(name) + ('(#%d)' % id) elif callable(title): title = title('edit', obj) data = data or {} result['get_url'] = get_url result['title'] = title result['obj_id'] = id result.update(data) return render_template(template, layout, result) else: return result
def generic_add(model=None, get_url=get_url, layout='layout.html', template=None, title=None, view=None, data=None): from uliweb.utils.generic import AddView from uliweb import response if not view: Model = get_model(model) if not model or not Model: return error("Can't find model [%s], please check it" % model) get_url = partial(get_url, action='view') view = AddView(model, get_url) result = view.run() if isinstance(result, dict): template = template or 'generic_add.html' response.template = template if not title: name = getattr(model, '__verbose_name__', '') title = _("Add") + safe_unicode(name) elif callable(title): title = title('add') data = data or {} result['get_url'] = get_url result['title'] = title result.update(data) return render_template(template, layout, result) else: return result
def html(self): if self.table_cell: if self.error: error = self.get_error() error_class = ' has-error' else: error = '' error_class = '' return ('<div class="table-field-row%s">' % error_class + safe_unicode(self.label) + '<div class="table-field-col">' + safe_unicode(self.content) + safe_unicode(error) + '</div></div>') col_cls = 'form-group' if self.error: col_cls = col_cls + ' has-error' if self.name: _id = 'div_field_%s' % self.name else: _id = None buf = Buf() with buf.div(_class=col_cls, id=_id): buf << self.label if self.dir == 'h': if self.label: buf << '<div class="col-sm-%d">' % (12-self.label_width) else: buf << '<div class="col-sm-offset-%d col-sm-%d">' % (self.label_width, 12-self.label_width) # buf << '<div class="table-field-row">' buf << self.content # buf << '</div>' buf << self.get_help_string() if self.error: buf << self.get_error() if self.dir == 'h': buf << '</div>' return str(buf)
def get_filename(filename, filesystem=False): from uliweb import application from uliweb.utils import files from uliweb.utils.common import safe_unicode #make sure the filename is unicode s = application.settings.GLOBAL filename = safe_unicode(filename, s.HTMLPAGE_ENCODING) path = os.path.normpath(application.settings.UPLOAD.TO_PATH).replace('\\', '/') f = os.path.normpath(os.path.join(path, filename)).replace('\\', '/') if not f.startswith(path): raise Forbidden("You can not visit unsafe files.") if filesystem: return files.encode_filename(f, s.HTMLPAGE_ENCODING, s.FILESYSTEM_ENCODING) return f
def get_filename(self, filename, filesystem=False, convert=False): """ Get the filename according to self.to_path, and if filesystem is False then return unicode filename, otherwise return filesystem encoded filename @param filename: relative filename, it'll be combine with self.to_path @param filesystem: if True, then encoding the filename to filesystem @param convert: if True, then convert filename with FilenameConverter class """ from uliweb.utils.common import safe_unicode #make sure the filename is unicode s = settings.GLOBAL if convert: _p, _f = os.path.split(filename) _filename = os.path.join(_p, self.filename_convert(filename)) else: _filename = filename nfile = safe_unicode(_filename, s.HTMLPAGE_ENCODING) return nfile
def generic_edit(model=None, id=None, obj=None, get_url=get_url, layout=None, template=None, title=None, view=None, data=None): from uliweb.utils.generic import EditView from uliweb import response if not view: Model = get_model(model) if not model or not Model: return error("Can't find model [%s], please check it" % model) if not obj: obj = Model.get(Model.c.id == int(id)) view = EditView(model, get_url('view', id=id), obj=obj) result = view.run() if isinstance(result, dict): layout = layout or 'layout.html' template = template or 'generic_edit.html' response.template = template if not title: name = getattr(model, '__verbose_name__', '') title = _("View") + safe_unicode(name) + ('(#%d)' % id) elif callable(title): title = title('edit', obj) data = data or {} result['layout'] = layout result['get_url'] = get_url result['title'] = title result['obj_id'] = id result.update(data) return result
def _link(cell, data, text, _var=None, _sh=None): t = safe_unicode(text).format(**_var) cell.value = data cell.hyperlink = t return cell.value
def default_menu(name, active='', validators=None, id=None, _class=None, menu_default_class='sidebar-menu'): """ :param menu: menu item name :param active: something like "z" :param check: validate callback, basic validate is defined in settings """ from uliweb.utils.common import safe_unicode if active and '/' not in active: active = '/'.join(__menu_items__[active].split('/')[1:] + [active]) s = [] for _t, y in iter_menu(name, active, validators): index = y['index'] indent = ' ' * index * 2 if _t == 'item': _lica = [] if y['active']: _lica.append('active') if y['expand']: _lica.append('open') if y['subs']: _lica.append("treeview") _licstr = 'class="%s"' % (' '.join(_lica)) if _lica else '' _name = ' name="%s"' % y['name'] s.extend([ indent, '<li ', _licstr, _name, '><a href="', y['link'], '">' ]) if 'icon' in y and y['icon']: if y['icon'].startswith("ion-"): s.extend(['<i class="ion %s"></i>' % y['icon']]) elif y['icon'].startswith("fa-"): s.extend(['<i class="fa %s"></i>' % y['icon']]) else: s.extend(['<i class="fa fa-%s"></i>' % y['icon']]) else: if index > 1: s.append('<i class="fa fa-angle-double-right"></i>') s.extend([indent, '<span>', safe_unicode(y['title']), '</span>']) if y['subs']: s.append('<i class="fa fa-angle-left pull-right"></i>') s.append('</a>') elif _t == 'open': pass elif _t == 'close': s.append('</li>\n') elif _t == 'begin': if index == 0: _id = (' id="%s"' % id) if id else '' _cls = (' %s' % _class) if _class else '' s.append('<ul class="%s %s"%s>\n' % (menu_default_class, _cls, _id)) else: s.extend(['\n', indent, '<ul class="treeview-menu">\n']) else: s.extend([indent, '</ul>\n', indent]) return ''.join(s)
def __str__(self): return safe_unicode(self.text)
def create_pagination(url, total, page, rows, length=None, total_message=None, first=None, next=None, prev=None, last=None): """ Create bootstrap style pagination html code :param total: total records count :param page: current page number :param rows: records count per page :param url: base url for page link :param length: the maximum of page links """ import math from uliweb import settings from uliweb.utils.common import safe_unicode length = length or settings.BOOTSTRAP_PAGINATION.length total_message = safe_unicode( total_message or settings.BOOTSTRAP_PAGINATION.total_message) first = safe_unicode(first or settings.BOOTSTRAP_PAGINATION.first) next = safe_unicode(next or settings.BOOTSTRAP_PAGINATION.next) prev = safe_unicode(prev or settings.BOOTSTRAP_PAGINATION.prev) last = safe_unicode(last or settings.BOOTSTRAP_PAGINATION.last) def get_url(p): from uliweb.utils.common import query_string return query_string(url, page=p) pages = int(math.ceil(total * 1.0 / rows)) begin = max(1, page - length / 2 + 1) end = min(pages, begin + length - 1) begin = max(1, end - length + 1) buf = [] buf.append('<ul>') total_message = total_message.replace('$pages', str(pages)) total_message = total_message.replace('$total', str(total)) buf.append('<li class="disabled total"><a href="#">%s</a></li>' % total_message) if pages and (begin != 1): buf.append('<li class="first"><a href="%s">%s</a></li>' % (get_url(1), first)) if pages and (page != 1): buf.append('<li class="prev"><a href="%s">%s</a></li>' % (get_url(page - 1), prev)) for i in range(begin, end + 1): if page == i: cls = ' active' href = '#' else: cls = '' href = get_url(i) buf.append('<li class="page%s"><a href="%s">%s</a></li>' % (cls, href, i)) if pages and (page != pages): buf.append('<li class="next"><a href="%s">%s</a></li>' % (get_url(page + 1), next)) if pages and (end != pages): buf.append('<li class="last"><a href="%s">%s</a></li>' % (get_url(pages), last)) buf.append('</ul>') return ''.join(buf)
def lngettext(msgid1, msgid2, n): return ldngettext(_domain, safe_unicode(msgid1), safe_unicode(msgid2), n)
def _write_header(self): from uliweb.utils.common import safe_unicode fields = [] max_rowspan = 0 for i, f in enumerate(self.fields_list): _f = list(f['title'].split('/')) max_rowspan = max(max_rowspan, len(_f)) fields.append((_f, i)) def get_field(fields, i, m_rowspan): f_list, col = fields[i] field = {'title':f_list[0], 'col':col, 'colspan':1, 'rowspan':1} if len(f_list) == 1: field['rowspan'] = m_rowspan return field def remove_field(fields, i): del fields[i][0][0] def clear_fields(fields): n = len(fields) for i in range(len(fields)-1, -1, -1): if len(fields[i][0]) == 0: n = min(n, fields[i][1]) del fields[i] if len(fields): return fields[0][1] return 0 n = len(fields) y = 0 while n>0: i = 0 while i<n: field = get_field(fields, i, max_rowspan-y) remove_field(fields, i) j = i + 1 while j<n: field_n = get_field(fields, j, max_rowspan-y) if safe_unicode(field['title']) == safe_unicode(field_n['title']) and field['rowspan'] == field_n['rowspan']: #combine remove_field(fields, j) field['colspan'] += 1 j += 1 else: break _f = self.fields[field['col']] y1 = self._row + y y2 = y1 + field['rowspan'] - 1 x1 = self._col + field['col'] x2 = x1 + field['colspan'] - 1 cell = self.sheet.cell(column=x1, row=y1, value=safe_unicode(field['title'])) self.sheet.merge_cells(start_row=y1, end_row=y2, start_column=x1, end_column=x2) self._format_header_cell(cell, start_row=y1, end_row=y2, start_column=x1, end_column=x2) i = j clear_fields(fields) n = len(fields) y += 1 self._row += y
def default_navigation(name, active='', validators=None, id=None, _class=None, menu_default_class='nav navbar-nav'): """ :param menu: menu item name :param active: something like "x/y/z" :param check: validate callback, basic validate is defined in settings """ from uliweb.utils.common import safe_unicode s = [] for _t, y in iter_menu(name, active, validators): index = y['index'] indent = ' ' * index * 2 if _t == 'item': _lica = [] if y['active']: _lica.append('active') # if y['expand']: # _lica.append('open') # if y['subs']: # s.extend([indent, '<li class="dropdown">']) # s.extend([indent, '<a href="#" class="dropdown-toggle" data-toggle="dropdown">{} <span class="caret"></span></a>'.format(safe_unicode(y['title']))]) # else: _licstr = 'class="%s"' % (' '.join(_lica)) if _lica else '' _name = ' name="%s"' % y['name'] if y['subs']: s.extend(['\n', indent, '<li class="dropdown">']) s.extend([ '\n', indent, u'<a href="#" class="dropdown-toggle" data-toggle="dropdown">{} <span class="caret"></span></a>' .format(safe_unicode(y['title'])) ]) s.extend(['\n', indent, '<ul class="dropdown-menu">\n']) else: s.extend([ indent, '<li ', _licstr, _name, '><a href="', y['link'], '">' ]) # remove icon # if 'icon' in y and y['icon']: # if y['icon'].startswith("ion-"): # s.extend(['<i class="ion %s"></i>' % y['icon']]) # elif y['icon'].startswith("fa-"): # s.extend(['<i class="fa %s"></i>' % y['icon']]) # else: # s.extend(['<i class="fa fa-%s"></i>' % y['icon']]) # else: if index > 1: s.append('<i class="fa fa-angle-double-right"></i>') s.extend([safe_unicode(y['title'])]) s.append('</a>') elif _t == 'open': pass elif _t == 'close': s.append('</li>\n') elif _t == 'begin': if index == 0: _id = (' id="%s"' % id) if id else '' _cls = (' %s' % _class) if _class else '' s.append('<ul class="%s %s"%s>\n' % (menu_default_class, _cls, _id)) # else: # s.extend(['\n', indent, '<li class="dropdown">']) # s.extend(['\n', indent, '<a href="#" class="dropdown-toggle" data-toggle="dropdown">{}</a>'.format(safe_unicode(y['title']))]) # s.extend(['\n', indent, '<ul class="dropdown-menu">\n']) else: s.extend([indent, '</ul>\n', indent]) return ''.join(s)
def _write_header(self): from uliweb.utils.common import safe_unicode fields = [] max_rowspan = 0 for i, f in enumerate(self.fields_list): _f = list(f['title'].split('/')) max_rowspan = max(max_rowspan, len(_f)) fields.append((_f, i)) def get_field(fields, i, m_rowspan): f_list, col = fields[i] field = { 'title': f_list[0], 'col': col, 'colspan': 1, 'rowspan': 1 } if len(f_list) == 1: field['rowspan'] = m_rowspan return field def remove_field(fields, i): del fields[i][0][0] def clear_fields(fields): n = len(fields) for i in range(len(fields) - 1, -1, -1): if len(fields[i][0]) == 0: n = min(n, fields[i][1]) del fields[i] if len(fields): return fields[0][1] return 0 n = len(fields) y = 0 while n > 0: i = 0 while i < n: field = get_field(fields, i, max_rowspan - y) remove_field(fields, i) j = i + 1 while j < n: field_n = get_field(fields, j, max_rowspan - y) if safe_unicode(field['title']) == safe_unicode( field_n['title'] ) and field['rowspan'] == field_n['rowspan']: #combine remove_field(fields, j) field['colspan'] += 1 j += 1 else: break _f = self.fields[field['col']] y1 = self._row + y y2 = y1 + field['rowspan'] - 1 x1 = self._col + field['col'] x2 = x1 + field['colspan'] - 1 cell = self.sheet.cell(column=x1, row=y1, value=safe_unicode(field['title'])) self.sheet.merge_cells(start_row=y1, end_row=y2, start_column=x1, end_column=x2) self._format_header_cell(cell, start_row=y1, end_row=y2, start_column=x1, end_column=x2) i = j clear_fields(fields) n = len(fields) y += 1 self._row += y
def ugettext(message): try: t = translation(_domain) except IOError: return message return t.ugettext(safe_unicode(message))
def lgettext(message): return ldgettext(_domain, safe_unicode(message))
def create_table_head(self): from uliweb.utils.common import safe_unicode fields = [] max_rowspan = 0 for i, f in enumerate(self.fields_list): _f = list(f['title'].split('/')) max_rowspan = max(max_rowspan, len(_f)) fields.append((_f, i)) def get_field(fields, i, m_rowspan): f_list, col = fields[i] field = { 'title': f_list[0], 'col': col, 'colspan': 1, 'rowspan': 1 } if len(f_list) == 1: field['rowspan'] = m_rowspan return field def remove_field(fields, i): del fields[i][0][0] def clear_fields(fields): n = len(fields) for i in range(len(fields) - 1, -1, -1): if len(fields[i][0]) == 0: n = min(n, fields[i][1]) del fields[i] if len(fields): return fields[0][1] return 0 n = len(fields) y = 0 posx = 0 while n > 0: i = 0 while i < n: field = get_field(fields, i, max_rowspan - y) remove_field(fields, i) j = i + 1 while j < n: field_n = get_field(fields, j, max_rowspan - y) if safe_unicode(field['title']) == safe_unicode( field_n['title'] ) and field['rowspan'] == field_n['rowspan']: #combine remove_field(fields, j) field['colspan'] += 1 j += 1 else: break _f = self.fields[field['col']] y1 = self.hbegin_y + y y2 = y1 + field['rowspan'] - 1 # x1 = self.hbegin_x + i + posx x1 = self.hbegin_x + field['col'] x2 = x1 + field['colspan'] - 1 self.sh.write_merge( y1, y2, x1, x2, safe_unicode(field['title']), self.style( style=_f['head_style'] or 'font: bold on;align: vert center,horz center; pattern: pattern solid, fore-colour pale_blue;borders:left thin, right thin, top thin, bottom thin;' )) width = _f['width'] if width and x1 == x2: self.sh.col(x1).width = width * 36 i = j posx = clear_fields(fields) n = len(fields) y += 1 if self.hbegin_y + y >= self.begin_y: self.begin_y = self.hbegin_y + y
def __unicode__(self): return safe_unicode(self.text)
def create_table_head(self): from uliweb.utils.common import safe_unicode fields = [] max_rowspan = 0 for i, f in enumerate(self.fields_list): _f = list(f['title'].split('/')) max_rowspan = max(max_rowspan, len(_f)) fields.append((_f, i)) def get_field(fields, i, m_rowspan): f_list, col = fields[i] field = {'title':f_list[0], 'col':col, 'colspan':1, 'rowspan':1} if len(f_list) == 1: field['rowspan'] = m_rowspan return field def remove_field(fields, i): del fields[i][0][0] def clear_fields(fields): n = len(fields) for i in range(len(fields)-1, -1, -1): if len(fields[i][0]) == 0: n = min(n, fields[i][1]) del fields[i] if len(fields): return fields[0][1] return 0 n = len(fields) y = 0 posx = 0 while n>0: i = 0 while i<n: field = get_field(fields, i, max_rowspan-y) remove_field(fields, i) j = i + 1 while j<n: field_n = get_field(fields, j, max_rowspan-y) if safe_unicode(field['title']) == safe_unicode(field_n['title']) and field['rowspan'] == field_n['rowspan']: #combine remove_field(fields, j) field['colspan'] += 1 j += 1 else: break _f = self.fields[field['col']] y1 = self.hbegin_y + y y2 = y1 + field['rowspan'] - 1 x1 = self.hbegin_x + i + posx x2 = x1 + field['colspan'] - 1 self.sh.write_merge(y1, y2, x1, x2, safe_unicode(field['title']), self.style(style=_f['head_style'] or 'font: bold on;align: vert center,horz center; pattern: pattern solid, fore-colour pale_blue;borders:left thin, right thin, top thin, bottom thin;')) width = _f['width'] if width and x1 == x2: self.sh.col(x1).width = width*36.5 i = j posx = clear_fields(fields) n = len(fields) y += 1 if self.hbegin_y + y >= self.begin_y: self.begin_y = self.hbegin_y + y