コード例 #1
0
ファイル: form_helper.py プロジェクト: naomhan/uliweb-peafowl
    def to_widget(self):
        """
        """
        from uliweb.form.widgets import Select
        from uliweb.utils.common import safe_str

        field = self.field
        attrs = self.attrs

        buf = Buf()
        _value = [safe_str(x) for x in (self.form.data.get(field.name) or [])]
        for i, (v, title) in enumerate(field.get_choices()):
            _attrs = copy.deepcopy(attrs)
            if safe_str(v) in _value:
                _attrs['checked'] = None
            _attrs.pop('class', None)
            _attrs['id'] = _attrs['id'] + '_' + str(i+1)
            v_attrs = to_attrs(_attrs)
            if self.inline:
                buf << '<label class="%s-inline"><input type="%s" value="%s"%s> %s</label>' % (self.input_type,
                                            self.input_type, v, v_attrs, title)
            else:
                buf << '<div class="%s"><label><input type="%s" value="%s"%s>%s</label></div>' % (self.input_type,
                                            self.input_type, v, v_attrs, title)
        return str(buf)
コード例 #2
0
ファイル: __init__.py プロジェクト: limodou/uliweb-apps
 def on_finish(self):
     """
     在处理成功后执行此处理,如果返回True,表示不执行缺省处理,否则按缺省处理进行
     :param ret: 命令执行结果
     :return:
     """
     #增加对返回值的处理,当self.ret返回为AsyncCommandList时,将当前任务置为
     #父结点,增加关联的子结点
     #动态生成的父任务
     if isinstance(self.ret, AsyncCommandList):
         self.ret.commit(self.task)
         self.task.children_count = len(self.ret.tasks)
         self.task.current_status = SUCCESS
         self.task.status = STARTED
         self.task.execution_info=safe_str(self.ret.result)
     #处理父任务
     elif self.task.children_count > 0:
         self.task.current_status = SUCCESS
         self.task.status = STARTED
         self.task.execution_info=safe_str(self.ret)
     #一般任务
     else:
         self.task.status = SUCCESS
         self.task.finished_time = date.now()
         self.task.execution_info = safe_str(self.ret)
コード例 #3
0
ファイル: __init__.py プロジェクト: biluo1989/uliweb
def csrf_token():
    """
    Get csrf token or create new one
    """
    from uliweb import request, settings
    from uliweb.utils.common import safe_str
    
    v = {}
    token_name = settings.CSRF.cookie_token_name
    if request.session.get(token_name):
        v = request.session[token_name]
        if time.time() >= v['created_time'] + v['expiry_time']:
            v = {}
        else:
            v['created_time'] = time.time()
    if not v:
        token = request.cookies.get(token_name)
        if not token:
            token = uuid.uuid4().get_hex()
        
        v = {'token':token, 'expiry_time':settings.CSRF.timeout, 'created_time':time.time()}

    if not request.session.deleted:
        request.session[token_name] = v
    return safe_str(v['token'])
コード例 #4
0
ファイル: __init__.py プロジェクト: biluo1989/uliweb
 def download(self, filename, action=None, x_filename='', real_filename=''):
     """
     action will be "download", "inline"
     and if the request.GET has 'action', then the action will be replaced by it.
     """
     from uliweb.utils.common import safe_str
     from uliweb.utils.filedown import filedown
     from uliweb import request
     from StringIO import StringIO
     
     action = request.GET.get('action', action)
     
     fname = safe_str(filename)
     if not x_filename:
         x_filename = fname
     if self.x_file_prefix:
         x_filename = os.path.normpath(os.path.join(self.x_file_prefix, x_filename)).replace('\\', '/')
     
     if not real_filename:
         #if not real_filename, then get the file info from database
         obj = self.get_file_record(filename)
         fname = obj.filename.encode('utf8')
         fileobj = StringIO(obj.content), obj.create_time, obj.size
         #fileobj should be (filename, mtime, size)
     else:
         fileobj = None
         s = settings.GLOBAL
         real_filename = files.encode_filename(real_filename, to_encoding=s.FILESYSTEM_ENCODING)
     
     return filedown(request.environ, fname, action=action, 
         x_sendfile=bool(self.x_sendfile), x_header_name=self.x_header_name, 
         x_filename=x_filename, real_filename=real_filename, fileobj=fileobj)
コード例 #5
0
ファイル: __init__.py プロジェクト: biluo1989/uliweb
    def download(self, filename, action='download', x_filename='', real_filename=''):
        """
        action will be "download", "inline"
        and if the request.GET has 'action', then the action will be replaced by it.
        """
        from uliweb.utils.common import safe_str
        from uliweb.utils.filedown import filedown
        
        s = settings.GLOBAL

        action = request.GET.get('action', action)
        
        if not real_filename:
            real_filename = self.get_filename(filename, True, convert=False)
        else:
            real_filename = files.encode_filename(real_filename, to_encoding=s.FILESYSTEM_ENCODING)

        if not x_filename:
            x_filename = safe_str(filename, s.FILESYSTEM_ENCODING)
        if self.x_file_prefix:
            x_filename = os.path.normpath(os.path.join(self.x_file_prefix, x_filename)).replace('\\', '/')
        
        return filedown(request.environ, filename, action=action, 
            x_sendfile=bool(self.x_sendfile), x_header_name=self.x_header_name, 
            x_filename=x_filename, real_filename=real_filename)
コード例 #6
0
ファイル: __init__.py プロジェクト: uliwebext/uliweb-layout
    def left_side_menu(self, menu_items, is_folder, level, *actives):
        from uliweb.utils.common import safe_str

        if len(actives) > 0:
            active = actives[0]
            items = actives[1:]
        else:
            active = None
            items = ()
        out = StringIO()
        if is_folder:
            out.write("<ul class='sidebar-menu'>")
        else:
            out.write("<ul class='treeview-menu'>")
        for x in menu_items:
            if active == x['name']:
                li_class = "active"
            else:
                li_class = ""
            if is_folder:
                li_class = "treeview " + li_class
                sub_icon = "<i class=\"fa fa-link\"></i>"
            else:
                sub_icon = ""
            if x.get('subs', None):
                link = "#"
                target = '_self'
                out.write(
                    '<li class=\"%s\"><a href=\"%s\" target=\"%s\">%s<span>%s</span><i class=\"fa fa-angle-left pull-right\"></i></a>' % (
                    li_class, link, target,sub_icon, safe_str(x["title"])))
            else:
                link = x.get("link", "#")
                target = x.get('target', '_self')
                out.write(
                    '<li class=\"%s\"><a href=\"%s\" target=\"%s\">%s<span>%s</span></a>' % (
                    li_class, link, target,sub_icon, safe_str(x["title"])))

            if x.get('subs', None):
                out.write(self.left_side_menu(x['subs'], False, level + 1, *items))
            out.write("</li>")
        out.write("</ul>")
        return out.getvalue()
コード例 #7
0
ファイル: taglibs.py プロジェクト: hunterfu/uliweb
def _to_attrs(attrs, args=None, **kwargs):
    if args and not isinstance(args, dict):
        raise ValueError("args should be a dict value, but {!r} found.".format(args))
    else:
        args = args or {}

    kwargs.update(args)
    for k, v in kwargs.items():
        value = attrs.setdefault(k, '')
        attrs[k] = value + ' ' + v
    return ' '.join(['{0}="{1}"'.format(k, safe_str(v)) for k, v in attrs.items()])
コード例 #8
0
ファイル: views.py プロジェクト: tangjn/plugs
 def pre_save(obj, data):
     flag = False
     if data["topic_type"] != obj.topic_type:
         flag = True
     if not flag and data["subject"] != obj.subject:
         flag = True
     if not flag and data["content"] != safe_str(post.content):
         flag = True
     if flag:
         data["modified_user"] = request.user.id
         data["updated_on"] = date.now()
コード例 #9
0
ファイル: __init__.py プロジェクト: limodou/uliweb
 def __repr__(cls):
     d = []
     d.append('{}{{'.format(cls.__name__))
     for name in cls._fields_list:
         f = cls.properties[name]
         field_name = ''
         if f.field_name:
             field_name = ' ,field_name={}'.format(f.field_name)
         d.append('    {}(type=\'{}\', label=\'{}\'{})'.format(f.name, f.type, safe_str(f.label), field_name))
     d.append('}')
     return '\n'.join(d)
コード例 #10
0
ファイル: views.py プロジェクト: qq40660/forum2
 def pre_save(obj, data):
     flag = False
     if data['topic_type'] != obj.topic_type:
         flag = True
     if not flag and data['subject'] != obj.subject:
         flag = True
     if not flag and data['content'] != safe_str(post.content):
         flag = True
     if flag:
         data['modified_user'] = request.user.id
         data['updated_on'] = date.now()
コード例 #11
0
ファイル: filedown.py プロジェクト: 08haozi/uliweb
def _get_download_filename(env, filename):
    from uliweb.utils.common import safe_str
    import urllib2
    from werkzeug.useragents import UserAgent
    
    agent = UserAgent(env)
    
    fname = safe_str(filename, 'utf8')
    if agent.browser == 'msie':
        result = 'filename=' + urllib2.quote(fname)
    elif agent.browser == 'safari':
        result = 'filename=' + fname
    else:
        result = "filename*=UTF-8''" + urllib2.quote(fname)
    return result
コード例 #12
0
ファイル: filedown.py プロジェクト: bobgao/uliweb
def _get_download_filename(env, filename):
    from uliweb import request
    from uliweb.utils.common import safe_str
    import urllib2
    from werkzeug.useragents import UserAgent

    agent = UserAgent(env)

    fname = safe_str(filename, "utf8")
    if agent.browser == "msie":
        result = "filename=" + urllib2.quote(fname)
    elif agent.browser == "safari":
        result = "filename=" + fname
    else:
        result = "filename*=UTF-8''" + urllib2.quote(fname)
    return result
コード例 #13
0
ファイル: uliform.py プロジェクト: Inzaghi2012/uliweb
    def html(self, data='', py=True):
        """
        Convert data to html value format.
        """

        if py:
            value = self.to_html(data)
        else:
            value = data
        if self.static:
            return str('<span class="value">%s</span>' % safe_str(value))
        else:
            if self.hidden:
                build = Hidden
            else:
                build = self.build
            return str(build(name=self.name, value=value, id=self.id, **self.html_attrs))
コード例 #14
0
ファイル: layout.py プロジェクト: limodou/uliweb
 def html(self):
     return '\n'.join([safe_str(x) for x in [self.begin(), self.hiddens(), self.body(), self.buttons_line(), self.end()] if x])
コード例 #15
0
ファイル: html.py プロジェクト: limodou/uliweb
 def __str__(self):
     return safe_str(self.text)
コード例 #16
0
ファイル: models.py プロジェクト: chyhutu/plugs
 def get_files():
     result = []
     for x in get_attachments(self):
         result.append('%-70s  %-12s  %s' % (safe_str(x.filename), safe_str(unicode(x.submitter)), str(x.created_date)))
         
     return '\n'.join(result)
コード例 #17
0
ファイル: dbinit.py プロジェクト: 08haozi/uliweb
Perm = get_model('permission')
Rel = get_model('role_perm_rel')

r = uliweb.settings.get('ROLES', {})
for name, v in r.items():
    if isinstance(v, (tuple, list)):
        if len(v) == 2:
            description, method = v
            reserve = False
        else:
            description, method, reserve = v
    else:
        description, reserve = v, True
    role = Role.get(Role.c.name==name)
    if not role:
        role = Role(name=safe_str(name), description=safe_str(description), reserve=reserve)
        msg = 'Add Role(%s)...' % name
    else:
        role.update(description=description, reserve=reserve)
        msg = 'Update Role(%s)...' % name
    flag = role.save()
    if flag:
        print msg

def process_permission_roles(perm, v):
    """
    v is roles
    """
    if isinstance(v, (tuple, list)):
        roles = v
    else:
コード例 #18
0
ファイル: filedown.py プロジェクト: limodou/uliweb
def filedown(environ, filename, cache=True, cache_timeout=None,
    action=None, real_filename=None, x_sendfile=False,
    x_header_name=None, x_filename=None, fileobj=None,
    default_mimetype='application/octet-stream'):
    """
    @param filename: is used for display in download
    @param real_filename: if used for the real file location
    @param x_urlfile: is only used in x-sendfile, and be set to x-sendfile header
    @param fileobj: if provided, then returned as file content
    @type fileobj: (fobj, mtime, size)

    filedown now support web server controlled download, you should set
    xsendfile=True, and add x_header, for example:

    nginx
        ('X-Accel-Redirect', '/path/to/local_url')
    apache
        ('X-Sendfile', '/path/to/local_url')
    """
    from .common import safe_str
    from werkzeug.http import parse_range_header

    guessed_type = mimetypes.guess_type(filename)
    mime_type = guessed_type[0] or default_mimetype
    real_filename = real_filename or filename

    #make common headers
    headers = []
    headers.append(('Content-Type', mime_type))
    d_filename = _get_download_filename(environ, os.path.basename(filename))
    if action == 'download':
        headers.append(('Content-Disposition', 'attachment; %s' % d_filename))
    elif action == 'inline':
        headers.append(('Content-Disposition', 'inline; %s' % d_filename))
    if x_sendfile:
        if not x_header_name or not x_filename:
            raise Exception("x_header_name or x_filename can't be empty")
        headers.append((x_header_name, safe_str(x_filename)))
        return Response('', status=200, headers=headers,
            direct_passthrough=True)
    else:
        request = environ.get('werkzeug.request')
        if request:
            range = request.range
        else:
            range = parse_range_header(environ.get('HTTP_RANGE'))
        #when request range,only recognize "bytes" as range units
        if range and range.units=="bytes":
            try:
                fsize = os.path.getsize(real_filename)
            except OSError as e:
                return Response("Not found",status=404)
            mtime = datetime.utcfromtimestamp(os.path.getmtime(real_filename))
            mtime_str = http_date(mtime)
            if cache:
                etag = _generate_etag(mtime, fsize, real_filename)
            else:
                etag = mtime_str

            if_range = environ.get('HTTP_IF_RANGE')
            if if_range:
                check_if_range_ok = (if_range.strip('"')==etag)
                #print "check_if_range_ok (%s) = (%s ==%s)"%(check_if_range_ok,if_range.strip('"'),etag)
            else:
                check_if_range_ok = True

            rbegin,rend = range.ranges[0]
            if check_if_range_ok and (rbegin+1)<fsize:
                if rend == None:
                    rend = fsize

                headers.append(('Content-Length',str(rend-rbegin)))
                #werkzeug do not count rend with the same way of rfc7233,so -1
                headers.append(('Content-Range','%s %d-%d/%d' %(range.units,rbegin, rend-1, fsize)))
                headers.append(('Last-Modified', mtime_str))
                if cache:
                    headers.append(('ETag', '"%s"' % etag))
                #for small file, read it to memory and return directly
                #and this can avoid some issue with google chrome
                if (rend-rbegin) < FileIterator.chunk_size:
                    s = "".join([chunk for chunk in FileIterator(real_filename,rbegin,rend)])
                    return Response(s,status=206, headers=headers, direct_passthrough=True)
                else:
                    return Response(FileIterator(real_filename,rbegin,rend),
                        status=206, headers=headers, direct_passthrough=True)

        #process fileobj
        if fileobj:
            f, mtime, file_size = fileobj
        else:
            f, mtime, file_size = _opener(real_filename)
        headers.append(('Date', http_date()))

        if cache:
            etag = _generate_etag(mtime, file_size, real_filename)
            headers += [
                ('ETag', '"%s"' % etag),
            ]
            if cache_timeout:
                headers += [
                    ('Cache-Control', 'max-age=%d, public' % cache_timeout),
                    ('Expires', http_date(time() + cache_timeout))
                ]
            if not is_resource_modified(environ, etag, last_modified=mtime):
                f.close()
                return Response(status=304, headers=headers)
        else:
            headers.append(('Cache-Control', 'public'))


        headers.extend((
            ('Content-Length', str(file_size)),
            ('Last-Modified', http_date(mtime))
        ))

        return Response(wrap_file(environ, f), status=200, headers=headers,
            direct_passthrough=True)
コード例 #19
0
ファイル: __init__.py プロジェクト: chyhutu/plugs
 def get_key(self, key):
     return md5(safe_str(key)).hexdigest()
コード例 #20
0
ファイル: dbinit.py プロジェクト: wangjun/shapps
def dbinit():
    RbacOrg = get_model('rbacorg')
    RbacScheme = get_model('rbacscheme')
    Role = get_model('role')
    Perm = get_model('permission')
    User = get_model('user')
    UserGroup = get_model('usergroup')
    OrgRole = get_model('orgrole')
    Rel = get_model('role_perm_rel')

    for k,v in settings.get('RBACSCHEME', {}).items():
        scheme_name,gorg_name,rp_list = v
        if not gorg_name:
            gorg_name = "%s_gorg"%(scheme_name)
        gorg = RbacOrg.get(RbacOrg.c.name==gorg_name)
        if not gorg:
            print "Add gorg(%s) of RbacScheme(%s)"%(gorg_name, scheme_name)
            gorg = RbacOrg(name=gorg_name)
            flag = gorg.save(); assert(flag)
        rbacscheme = RbacScheme.get(RbacScheme.c.name==scheme_name)
        if not rbacscheme:
            print "Add RbacScheme(%s)"%(scheme_name)
            rbacscheme = RbacScheme(name=scheme_name,gorg=gorg)
            flag = rbacscheme.save(); assert(flag)
        for role_name,perm_name in rp_list:
            role = Role.get(Role.c.name==role_name)
            if not role:
                print "Add Role(%s)"%(role_name)
                role = Role(name=safe_str(role_name))
                flag = role.save(); assert(flag)
            perm = Perm.get(Perm.c.name==perm_name)
            if not perm:
                print "Add Permission(%s)"%(perm_name)
                perm = Perm(name=safe_str(perm_name))
                flag = perm.save(); assert(flag)
            rel = Rel.get(and_(Rel.c.role==role.id,
                Rel.c.permission==perm.id,
                Rel.c.scheme==rbacscheme.id))
            if not rel:
                print "Add Role_Perm_Rel(%s,%s,%s)"%(role_name,perm_name,scheme_name)
                rel = Rel(role=role,permission=perm,scheme=rbacscheme)
                flag = rel.save(); assert(flag)

    for k,v in settings.get('RBACORG', {}).items():
        rbacorg_name,rbacscheme_name = v
        rbacscheme = RbacScheme.get(RbacScheme.c.name==rbacscheme_name)
        if not rbacscheme:
            raise Exception, 'RbacScheme [%s] not found.' % rbacscheme
        rbacorg = RbacOrg.get(RbacOrg.c.name==rbacorg_name)
        if not rbacorg:
            print "Add RbacOrg(%s,%s)"%(rbacorg_name, rbacscheme_name)
            rbacorg = RbacOrg(name=rbacorg_name,rbacscheme=rbacscheme)
            flag = rbacorg.save(); assert(flag)
        elif (not rbacorg.rbacscheme) or (rbacorg.rbacscheme.id!=rbacscheme.id):
            print "Update RbacOrg[%s]'s scheme to %s"%(rbacorg_name,rbacscheme_name)
            rbacorg.update(rbacscheme=rbacscheme)
            rbacorg.save()

    for k,v in settings.get('ORGROLE').items():
        role_name, rbacorg_name, usernames, usergroupnames = v
        role = Role.get(Role.c.name==role_name)
        if not role:
            raise Exception, 'Role [%s] not found.' % role_name
        rbacorg = RbacOrg.get(RbacOrg.c.name==rbacorg_name)
        if not rbacorg:
            raise Exception, 'RbacOrg [%s] not found.' % rbacorg_name
        orgrole = OrgRole.get(and_(OrgRole.c.role==role.id,
            OrgRole.c.organization==rbacorg.id))
        if not orgrole:
            print "Add OrgRole(%s,%s)"%(role_name, rbacorg_name)
            orgrole = OrgRole(role=role,organization=rbacorg)
            flag = orgrole.save(); assert(flag)
        for username in usernames:
            user = User.get(User.c.username==username)
            if user:
                if not orgrole.users.has(user):
                    print "Add User(%s) to OrgRole(%s,%s)"%(username, role_name, rbacorg_name)
                    orgrole.users.add(user)
        for usergroupname in usergroupnames:
            usergroup = UserGroup.get(UserGroup.c.name==usergroupname)
            if usergroup:
                if not orgrole.usergroups.has(usergroup):
                    print "Add UserGroup(%s) to OrgRole(%s,%s)"%(usergroupname, role_name, rbacorg_name)
                    orgrole.usergroups.add(usergroup)
コード例 #21
0
ファイル: __init__.py プロジェクト: bobgao/uliweb
def get_id(tablename, condition):
    from uliweb.utils.common import safe_str
    return "__objcache__:%s:%s" % (tablename, safe_str(condition.right.value))
コード例 #22
0
ファイル: form_helper.py プロジェクト: naomhan/uliweb-peafowl
    def convert_html(self, value):
        if isinstance(value, (tuple, list)):
            return ' '.join(['<span class="label label-default">%s</span>' % safe_str(x)
                             for x in value])

        return self.field.to_html(value)
コード例 #23
0
ファイル: form_helper.py プロジェクト: naomhan/uliweb-peafowl
 def to_widget(self):
     _attrs = to_attrs(self.attrs)
     return '<input type="%s" value="%s"%s></input>' % (self.input_type, safe_str(self.html_value), _attrs)
コード例 #24
0
ファイル: form_helper.py プロジェクト: naomhan/uliweb-peafowl
 def to_hidden(self):
     return '<input type="hidden" value="%s"></input>' % safe_str(self.html_value)
コード例 #25
0
ファイル: views.py プロジェクト: chyhutu/plugs
 def creator(text=text):
     content, kwargs = self._get_page_html(text)
     return safe_str(repr(kwargs) + '||||' + content)
コード例 #26
0
ファイル: uliform.py プロジェクト: limodou/uliweb
    def get_help_string(self, **kwargs):
        if self.help_string:
#            return str(Tag('label', self.help_string, _for=self.id, **kwargs))
            return safe_str(self.help_string)
        else:
            return ''