Exemplo n.º 1
0
def pre_delete(sender, instance):
    from uliweb.orm import get_model
    import pickle
    from datetime import datetime
    from uliweb import request

    tablename = sender.tablename
    if not need_audit(tablename):
        return

    Audit = get_model('audit')
    Tables = get_model('tables')

    table = Tables.get_table(tablename)
    changed_value = ''
    old_value = pickle.dumps(instance.to_dict(), pickle.HIGHEST_PROTOCOL)
    modify_flag = '3'

    obj = Audit(table_id=table,
                obj_id=instance.id,
                changed_value=changed_value,
                old_value=old_value,
                modified_date=datetime.now(),
                modified_user=request.user,
                modify_flag=modify_flag,
                title=unicode(instance))

    obj.save()
Exemplo n.º 2
0
def post_save(sender, instance, created, data, old_data):
    from uliweb.orm import get_model
    import pickle
    from datetime import datetime
    from uliweb import request
    
    tablename = sender.tablename
    if not need_audit(tablename):
        return

    Audit = get_model('audit')
    Tables = get_model('tables')
    
    table = Tables.get_table(tablename)
    changed_value = pickle.dumps(data, pickle.HIGHEST_PROTOCOL)
    if created:
        modify_flag = '1'
        old_value = ''
    else:
        old = {}
        modify_flag = '2'
        for k in data.iterkeys():
            old[k] = old_data[k]
        old_value = pickle.dumps(old, pickle.HIGHEST_PROTOCOL)
        
    obj = Audit(table_id=table, obj_id=instance.id, changed_value=changed_value,
        old_value=old_value, modified_date=datetime.now(), modified_user=request.user,
        modify_flag=modify_flag, title=unicode(instance))
        
    obj.save()
Exemplo n.º 3
0
 def handle(self, options, global_options, *args):
     from uliweb.orm import get_model
     from uliweb.utils.common import Serial
     import pprint
     
     self.get_application(global_options)
     WorkflowSpec = get_model('workflow_spec')
     TaskSpec = get_model('task_spec')
     
     print "TaskSpec : %s" % (TaskSpec.all().count())
     for task in TaskSpec.all():
         print " * %s" % task.name
         if global_options.verbose:
             print "   - modified_date: %s" % task.modified_date
             print "   - source: %s" % task.source
         if options.detail:
             pprint.pprint(Serial.load(task.content))
     
     print "\nWorkflowSpec : %s" % (WorkflowSpec.all().count())
     for wf in WorkflowSpec.all():
         print " * %s" % wf.name
         if global_options.verbose:
             print "   - modified_date: %s" % wf.modified_date
             print "   - source: %s" % wf.source
         if options.detail:
             pprint.pprint(Serial.load(wf.content))
Exemplo n.º 4
0
    def delrole(self):
        Perm = get_model('permission')
        Role = get_model('role')

        perm_id = request.POST.get('perm_id')
        role_id = request.POST.get('role_id')
        perm = Perm.get(int(perm_id))
        role = Role.get(int(role_id))
        if not perm:
            return json({
                'success': False,
                'message': "Can't find the permission id %s" % perm_id
            })
        if not role:
            return json({
                'success': False,
                'message': "Can't find the role id %s" % role_id
            })
        if perm.perm_roles.has(role):
            perm.perm_roles.remove(role)
            return json({
                'success':
                True,
                'message':
                "The permission %s has been delete from role %s successfully."
                % (perm.name, role.name)
            })
        else:
            return json({
                'success':
                False,
                'message':
                "The permission %s is not existed in role %s successfully." %
                (perm.name, role.name)
            })
Exemplo n.º 5
0
    def deluser(self):
        User = get_model('user')
        Role = get_model('role')

        user_id = request.POST.get('user_id')
        role_id = request.POST.get('role_id')
        user = User.get(int(user_id))
        role = Role.get(int(role_id))
        if not user:
            return json({
                'success': False,
                'message': "Can't find the user id %s" % user_id
            })
        if not role:
            return json({
                'success': False,
                'message': "Can't find the role id %s" % role_id
            })
        if role.users.has(user):
            role.users.remove(user)
            return json({
                'success':
                True,
                'message':
                "The user %s has been delete from role %s successfully." %
                (user.username, role.name)
            })
        else:
            return json({
                'success':
                False,
                'message':
                "The user %s is not existed in role %s successfully." %
                (user.username, role.name)
            })
Exemplo n.º 6
0
def has_permission(user, *permissions, **role_kwargs):
    """
    Judge if an user has permission, and if it does return role object, and if it doesn't
    return False. role_kwargs will be passed to role functions.
    With role object, you can use role.relation to get Role_Perm_Rel object.
    """
    Role = get_model('role')
    Perm = get_model('permission')
    Role_Perm_Rel = get_model('role_perm_rel')

    if isinstance(user, (unicode, str)):
        User = get_model('user')
        user = User.get(User.c.username == user)

    for name in permissions:
        perm = Perm.get(Perm.c.name == name)
        if not perm:
            continue

        flag = functions.has_role(
            user,
            *list(
                perm.perm_roles.filter(
                    Role_Perm_Rel.c.scheme == None).with_relation().all()),
            **role_kwargs)
        if flag:
            return flag

    return False
Exemplo n.º 7
0
 def remove_topic(self, forum_id, topic_id):
     from sqlalchemy.sql import select
     
     Forum = get_model('forum')
     forum = Forum.get(int(forum_id))
     Topic = get_model('forumtopic')
     topic = Topic.get(int(topic_id))
     Post = get_model('forumpost')
     post = Post.get((Post.c.topic==int(topic_id)) & (Post.c.floor==1))
     FA = get_model('forumattachment')
     
     if not topic:
         error("主题不存在")
         
     is_manager = post.topic.forum.managers.has(request.user)
     if is_manager:
         query = FA.filter(FA.c.slug==Post.c.slug).filter(Post.c.topic==int(topic_id))
         #删除相应附件
         for a in query:
             functions.delete_filename(a.file_name)
         #删除FA记录
         FA.filter(FA.c.slug.in_(select([Post.c.slug], Post.c.topic==int(topic_id)))).remove()
         #删除所有POST
         post_query = Post.filter(Post.c.topic==int(topic_id))
         post_count = post_query.count()
         post_query.remove()
         Topic.get(int(topic_id)).delete()
         Forum.filter(Forum.c.id==int(forum_id)).update(num_posts=Forum.c.num_posts-post_count, num_topics=Forum.c.num_topics-1)
         flash('删除成功!')
         return redirect(url_for(ForumView.forum_index, id=forum_id))
     else:
         flash('你无权限删除主题!')
         return redirect(url_for(ForumView.topic_view, forum_id=forum_id, topic_id=topic_id))
Exemplo n.º 8
0
def has_role(user, *roles, **kwargs):
    """
    Judge is the user belongs to the role, and if does, then return the role object
    if not then return False. kwargs will be passed to role_func.
    """
    Role = get_model('role')
    if isinstance(user, (unicode, str)):
        User = get_model('user')
        user = User.get(User.c.username == user)

    for role in roles:
        if isinstance(role, (str, unicode)):
            role = Role.get(Role.c.name == role)
            if not role:
                return False
        name = role.name

        func = __role_funcs__.get(name, None)
        if func:
            if isinstance(func, (unicode, str)):
                func = import_attr(func)

            assert callable(func)

            para = kwargs.copy()
            para['user'] = user
            flag = call_func(func, para)
            if flag:
                return role
        flag = role.users.has(user)
        if flag:
            return role
    return False
Exemplo n.º 9
0
    def edit_post(self, forum_id, topic_id, post_id):
        """
        修改回复
        """
        from uliweb.utils.generic import EditView
        
        Forum = get_model('forum')
        forum = Forum.get(int(forum_id))
        
        Topic = get_model('forumtopic')
        topic = Topic.get(int(topic_id))
        Post = get_model('forumpost')
        obj = Post.get(int(post_id))
        cur_page = request.values.get('page', 1)
        
        def pre_save(obj, data):
            data['updated_on'] = date.now()

        def post_save(obj, data):
            self._clear_files(obj.slug, data['content'])
        
        def get_form_field(name, obj):
            from uliweb.form import TextField
            if name == 'content':
                return TextField('内容', required=True, convert_html=True, rows=20)
        
        if obj.parent == None:
            anchor = post_id
        else:
            anchor = 'post_'+post_id
        url = '/forum/%s/%s?page=%s#%s' % (forum_id, topic_id, str(cur_page), anchor)
        view = EditView('forumpost', ok_url=url,
            obj=obj, pre_save=pre_save, post_save=post_save, get_form_field=get_form_field, 
            template_data={'forum':forum, 'topic':topic, 'slug':obj.slug, 'anchor':anchor})
        return view.run()
Exemplo n.º 10
0
    def handle(self, options, global_options, *args):
        from uliweb.orm import get_model
        from uliweb.utils.common import Serial
        import pprint

        self.get_application(global_options)
        WorkflowSpec = get_model('workflow_spec')
        TaskSpec = get_model('task_spec')

        print "TaskSpec : %s" % (TaskSpec.all().count())
        for task in TaskSpec.all():
            print " * %s" % task.name
            if global_options.verbose:
                print "   - modified_date: %s" % task.modified_date
                print "   - source: %s" % task.source
            if options.detail:
                pprint.pprint(Serial.load(task.content))

        print "\nWorkflowSpec : %s" % (WorkflowSpec.all().count())
        for wf in WorkflowSpec.all():
            print " * %s" % wf.name
            if global_options.verbose:
                print "   - modified_date: %s" % wf.modified_date
                print "   - source: %s" % wf.source
            if options.detail:
                pprint.pprint(Serial.load(wf.content))
Exemplo n.º 11
0
    def addbatchuser(self):
        User = get_model('user')
        Role = get_model('role')
        
        user_ids = request.POST.get('user_ids')
        role_id = request.POST.get('role_id')
        
        user_ids = user_ids.replace('\n', ',').replace('\r', '').replace(u',',',')
        user_ids = user_ids.split(',')
        
        error_users = []
        for user_id in user_ids:
            if user_id != '':
                user = User.get(User.c.username == user_id)
                if not user:
                    error_users.append(user_id)

        if len(error_users)>0:
            return json({'success':False, 'message': u"下列人员帐号找不到: %s, 请仔细检查后再次增加。" % ','.join(error_users)})  
        else:
            role = Role.get(int(role_id))
            for user_id in user_ids:
                user = User.get(User.c.username == user_id)
                if not role.users.has(user):
                    role.users.add(user)
            message = "批量增加人员成功"
            flash(message, category='success')
            return json({'success':True, 'message': message});
Exemplo n.º 12
0
    def api_org_roles_load(self, org_id):
        page = int(request.GET.get('iDisplayStart') or 0)
        psize = int(request.GET.get('iDisplayLength') or 10)
        RoleModel = get_model('role')
        UserModel = get_model('user')
        OrgRoleModel = get_model('orgrole')
        UserGroupModel = get_model('usergroup')

        totalRecords = OrgRoleModel.filter(OrgRoleModel.c.organization == org_id).count()
        query = select([RoleModel.c.id.label('role_id'), RoleModel.c.name.label('role_name'), OrgRoleModel.c.organization, OrgRoleModel.c.id.label('orgrole_id')]).select_from(join(RoleModel.table, OrgRoleModel.table, RoleModel.c.id == OrgRoleModel.c.role)).where(OrgRoleModel.c.organization == org_id).offset(page).limit(psize)
        result = do_(query)
        ret = {}
        def fetch_users(orgrole_id):
            ret = []
            userList = UserModel.filter(OrgRoleModel.users.join_filter(OrgRoleModel.c.id == orgrole_id))
            for s in userList:
                ret.append({s.id:s.username})
            return ret

        def fetch_usergroups(orgrole_id):
            ret = []
            userList = UserGroupModel.filter(OrgRoleModel.usergroups.join_filter(OrgRoleModel.c.id == orgrole_id))
            for s in userList:
                ret.append({s.id:s.name})
            return ret

        ret['aaData'] = [{'role_id':s['role_id'], 'role_name':s['role_name'], 'users':fetch_users(s.orgrole_id), 'usergroups':fetch_usergroups(s.orgrole_id), 'orgrole_id':s['orgrole_id']} for s in result]
        ret['iTotalRecords'] = totalRecords
        ret['iTotalDisplayRecords'] = totalRecords
        return json(ret)
Exemplo n.º 13
0
 def __init__(self):
     from uliweb.utils.generic import AddView,ListView,EditView
     self.PhoneNum = get_model('phonenumber')
     self.Tags = get_model('tags')
     self.AddView = AddView
     self.ListView = ListView
     self.EditView = EditView
Exemplo n.º 14
0
def has_role(user, *roles, **kwargs):
    """
    Judge is the user belongs to the role, and if does, then return the role object
    if not then return False. kwargs will be passed to role_func.
    """
    Role = get_model("role")
    if isinstance(user, (unicode, str)):
        User = get_model("user")
        user = User.get(User.c.username == user)

    for role in roles:
        if isinstance(role, (str, unicode)):
            role = Role.get(Role.c.name == role)
            if not role:
                continue
        name = role.name

        func = __role_funcs__.get(name, None)
        if func:
            if isinstance(func, (unicode, str)):
                func = import_attr(func)

            assert callable(func)

            para = kwargs.copy()
            para["user"] = user
            flag = call_func(func, para)
            if flag:
                return role
        flag = role.users.has(user)
        if flag:
            return role
    return False
Exemplo n.º 15
0
    def handle(self, options, global_options, *args):
        from uliweb.orm import get_model
        from uliweb.core.SimpleFrame import get_app_dir
        
        if not options.test:
            if not options.skip_warning:
                message = """This command will delete all workflow specs, are you sure to do?"""
                get_answer(message)

        self.get_application(global_options)
        
        if not options.test:
            clear()
            print ""
        
        apps_list = self.get_apps(global_options)
        tasks, workflows = loadspec(apps_list, global_options)
        
        from uliweb.orm import get_model
        from uliweb.utils.common import Serial
        WorkflowSpec = get_model('workflow_spec')
        TaskSpec = get_model('task_spec')
        
        if not options.test:
            for name in tasks:
                task, file = tasks[name]
                spec = TaskSpec(name=name, content=Serial.dump(task), source=file)
                spec.save()
            
            for name in workflows:
                workflow, file = workflows[name]
                spec = WorkflowSpec(name=name, content=Serial.dump(workflow), source=file)
                spec.save()
Exemplo n.º 16
0
def post_save(sender, instance, created, data, old_data):
    from uliweb.orm import get_model
    import pickle
    from datetime import datetime
    from uliweb import request

    tablename = sender.tablename
    if not need_audit(tablename):
        return

    Audit = get_model('audit')
    Tables = get_model('tables')

    table = Tables.get_table(tablename)
    changed_value = pickle.dumps(data, pickle.HIGHEST_PROTOCOL)
    if created:
        modify_flag = '1'
        old_value = ''
    else:
        old = {}
        modify_flag = '2'
        for k in data.iterkeys():
            old[k] = old_data[k]
        old_value = pickle.dumps(old, pickle.HIGHEST_PROTOCOL)

    obj = Audit(table_id=table,
                obj_id=instance.id,
                changed_value=changed_value,
                old_value=old_value,
                modified_date=datetime.now(),
                modified_user=request.user,
                modify_flag=modify_flag,
                title=unicode(instance))

    obj.save()
Exemplo n.º 17
0
def has_org_permission(user, org, *permissions, **role_kwargs):
    """
    Judge if an user has organization permission, and if it does return role
    object, and if it doesn't return False. role_kwargs will be passed to role
    functions. With role object, you can use role.relation to get Role_Perm_Rel
    object.
    """
    Role = get_model('role')
    Perm = get_model('permission')
    Role_Perm_Rel = get_model('role_perm_rel')

    if isinstance(user, (unicode, str)):
        User = get_model('user')
        user = User.get(User.c.username==user)

    if isinstance(org, (unicode, str)):
        RbacOrg = get_model('rbacorg')
        org = RbacOrg.get(RbacOrg.c.name==org)

    for name in permissions:
        perm = Perm.get(Perm.c.name==name)
        if not perm:
            continue

        flag = has_org_role(user, org, *list(perm.perm_roles.filter(Role_Perm_Rel.c.scheme==org.rbacscheme.id).with_relation().all()), **role_kwargs)
        if flag:
            return flag

    return False
Exemplo n.º 18
0
def clear():
    from uliweb.orm import get_model
    WorkflowSpec = get_model('workflow_spec')
    TaskSpec = get_model('task_spec')
    print "Deleting Workflow_Spec ..."
    WorkflowSpec.remove()
    print "Deleting Task_Spec  ..."
    TaskSpec.remove()
Exemplo n.º 19
0
def clear():
    from uliweb.orm import get_model
    WorkflowSpec = get_model('workflow_spec')
    TaskSpec = get_model('task_spec')
    print "Deleting Workflow_Spec ..."
    WorkflowSpec.remove()
    print "Deleting Task_Spec  ..."
    TaskSpec.remove()
Exemplo n.º 20
0
    def detail(self, schema_id):
        OrgModel = get_model('rbacorg')
        RoleModel = get_model('role')
        PermModel = get_model('Permission')
        RPRModel = get_model('Role_Perm_Rel')

        query = select([self.model.c.id, self.model.c.name, self.model.c.gorg, self.model.c.description, OrgModel.c.name.label('org_name')]).select_from(join(self.model.table, OrgModel.table, self.model.c.gorg == OrgModel.c.id)).where(self.model.c.id == schema_id)
        schemaList = do_(query)
        return {'schemaid':schema_id, 'schema_obj':schemaList.fetchone()}
Exemplo n.º 21
0
def scan_step_all_path():
    from uliweb import settings

    ScanPathes = get_model("scanpathes")
    ScanPathes.remove()

    allext = {}
    root_dp = settings.SCAN.DIR
    ScanPathes(path = ".",type = "d",).save()

    count = 0
    Begin()

    IGNORE_DIRS_SET = set(settings.SCAN.DIR_IGNORE)
    for root,dirs,files in os.walk(root_dp):
        root_relp = os.path.relpath(root,root_dp)
        if not isinstance(root_relp,unicode):
            root_relp = root_relp.decode("utf8")
        sys.stdout.write(".")
        rp = ScanPathes.get(ScanPathes.c.path==root_relp)
        if not rp:
            print "\ncan not find in db so do not scan %s"%(root)
            continue
        ignore_dirs = []
        for dn in dirs:
            dp = os.path.join(root,dn)
            if os.path.islink(dp):
                print "\nignore link:%s"%(dp)
                ignore_dirs.append(dn)
            elif dn in IGNORE_DIRS_SET:
                print "\nignore dir: %s"%(dp)
                ignore_dirs.append(dn)
            else:
                relp = os.path.relpath(dp,root_dp)
                do_(ScanPathes.table.insert().values(path = relp.decode("utf8"),type = "d",parent=rp.id))
        for dn in ignore_dirs:
            dirs.remove(dn)
        l = root.split(os.sep)
        for fn in files:
            fp = os.path.join(root,fn)
            if not os.path.islink(fp):
                p,ext = os.path.splitext(fn)
                relp = os.path.relpath(fp,root_dp)
                do_(ScanPathes.table.insert().values(path = relp.decode("utf8"),type = "f",ext=ext,parent=rp.id))
                if allext.has_key(ext):
                    allext[ext] += 1
                else:
                    allext[ext] = 1
            else:
                print "\nignore link:%s"%(fp)
    Commit()

    Exts = get_model("exts")
    Exts.remove()
    for i,k in enumerate(allext):
        Exts(ext = k,num = allext[k]).save()
    print
Exemplo n.º 22
0
    def forum_index(self, id):
        """
        显示某论坛页面
        """
        from uliweb.utils.generic import ListView

        pageno = int(request.values.get("page", 1)) - 1
        rows_per_page = int(request.values.get("rows", settings.get_var("PARA/FORUM_INDEX_NUMS")))

        Topic = get_model("forumtopic")
        Forum = get_model("forum")
        forum = Forum.get(int(id))
        condition = Topic.c.forum == int(id)
        order_by = [Topic.c.sticky.desc(), Topic.c.created_on.desc()]
        if not forum.managers.has(request.user):
            condition = (Topic.c.hidden == False) & condition

        filter = request.GET.get("filter", "all")
        if filter == "essence":
            condition = (Topic.c.essence == True) & condition

        def created_on(value, obj):
            return value.strftime("%Y-%m-%d")

        def last_reply_on(value, obj):
            return timesince(value)

        def subject(value, obj):
            if obj.topic_type:
                _type = u"[%s]" % obj.get_display_value("topic_type")
            else:
                _type = ""
            s = ""
            if obj.sticky:
                s += u'<font color="red">[顶]</font>'
            if obj.hidden:
                s += u'<font color="red">[隐]</font>'
            if obj.closed:
                s += u'<font color="red">[关]</font>'
            if obj.essence:
                s += u'<font color="red">[精]</font>'
            return _type + '<a href="/forum/%d/%d">%s</a>' % (int(id), obj.id, obj.subject) + s

        fields_convert_map = {"created_on": created_on, "subject": subject, "last_reply_on": last_reply_on}
        view = ListView(
            Topic,
            condition=condition,
            order_by=order_by,
            rows_per_page=rows_per_page,
            pageno=pageno,
            fields_convert_map=fields_convert_map,
        )
        if "data" in request.values:
            return json(view.json())
        else:
            return {"forum": forum, "filter": filter}
Exemplo n.º 23
0
    def edit_topic(self, forum_id, topic_id):
        """
        修改主题
        """
        from uliweb.utils.generic import EditView

        Forum = get_model('forum')
        forum = Forum.get(int(forum_id))
        Topic = get_model('forumtopic')
        topic = Topic.get(int(topic_id))
        Post = get_model('forumpost')
        post = Post.get((Post.c.topic == int(topic_id)) & (Post.c.floor == 1))

        def post_save(obj, data):
            #更新Post表
            post.content = data['content']
            post.save()

            self._clear_files(obj.slug, data['content'])

        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()

        def get_form_field(name, obj):
            from uliweb.form import TextField
            if name == 'content':
                return TextField('内容',
                                 required=True,
                                 rows=20,
                                 convert_html=True)

        data = {'content': post.content}
        view = EditView('forumtopic',
                        url_for(ForumView.topic_view,
                                forum_id=forum_id,
                                topic_id=topic_id),
                        obj=topic,
                        data=data,
                        pre_save=pre_save,
                        hidden_fields=['slug'],
                        post_save=post_save,
                        get_form_field=get_form_field,
                        template_data={
                            'forum': forum,
                            'topic': topic
                        })
        return view.run()
Exemplo n.º 24
0
    def edit_topic(self, forum_id, topic_id):
        """
        修改主题
        """
        from uliweb.utils.generic import EditView

        Forum = get_model("forum")
        forum = Forum.get(int(forum_id))
        Topic = get_model("forumtopic")
        topic = Topic.get(int(topic_id))
        Post = get_model("forumpost")
        post = Post.get((Post.c.topic == int(topic_id)) & (Post.c.floor == 1))

        # compatiable not saving the first post slug bug
        if not post.slug:
            post.slug = uuid.uuid1().hex
            post.save()

        def post_save(obj, data):
            # 更新Post表
            post.content = data["content"]
            post.save()

            self._clear_files(obj.slug, data["content"])

        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()

        def get_form_field(name, obj):
            from uliweb.form import TextField

            if name == "content":
                return TextField("内容", required=True, rows=20, convert_html=True)

        data = {"content": post.content}
        view = EditView(
            "forumtopic",
            url_for(ForumView.topic_view, forum_id=forum_id, topic_id=topic_id),
            obj=topic,
            data=data,
            pre_save=pre_save,
            hidden_fields=["slug"],
            post_save=post_save,
            get_form_field=get_form_field,
            template_data={"forum": forum, "topic": topic, "slug": post.slug},
        )
        return view.run()
Exemplo n.º 25
0
def ext(id):
    Exts = get_model("exts")
    ext = Exts.get(id)
    ext_str = ext.ext
    ScanPathes = get_model("scanpathes")
    pathes = ScanPathes.filter(ScanPathes.c.type=='f').filter(ScanPathes.c.ext==ext_str)
    return {
        'pathes':pathes,
        'get_path_css':get_path_css,
    }
Exemplo n.º 26
0
def get_tables(apps_dir, apps=None, engine=None, import_models=False, tables=None,
    settings_file='settings.ini', local_settings_file='local_settings.ini'):
    from uliweb.core.SimpleFrame import get_apps, get_app_dir
    from uliweb import orm
    from StringIO import StringIO
    
    engine = orm.engine_manager[engine]
    e = engine.options['connection_string']
    engine_name = e[:e.find('://')+3]
    
    buf = StringIO()
    
    if import_models:
        apps = get_apps(apps_dir, settings_file=settings_file, local_settings_file=local_settings_file)
        if apps:
            apps_list = apps
        else:
            apps_list = apps[:]
        models = []
        for p in apps_list:
            if p not in apps:
                log.error('Error: Appname %s is not a valid app' % p)
                continue
            if not is_pyfile_exist(get_app_dir(p), 'models'):
                continue
            m = '%s.models' % p
            try:
                mod = __import__(m, {}, {}, [''])
                models.append(mod)
            except ImportError:
                log.exception("There are something wrong when importing module [%s]" % m)
        
    else:
        old_models = orm.__models__.keys()
        try:
            for tablename, m in orm.__models__.items():
                orm.get_model(tablename)
        except:
            print "Problems to models like:", list(set(old_models) ^ set(orm.__models__.keys()))
            raise
            
    if apps:
        t = {}
        for tablename, m in engine.metadata.tables.items():
            if hasattr(m, '__appname__') and m.__appname__ in apps:
                t[tablename] = engine.metadata.tables[tablename]
    elif tables:
        t = {}
        for tablename, m in engine.metadata.tables.items():
            if tablename in tables:
                t[tablename] = engine.metadata.tables[tablename]
    else:
        t = engine.metadata.tables
                
    return t
Exemplo n.º 27
0
 def forum_index(self, id):
     """
     显示某论坛页面
     """
     from uliweb.utils.generic import ListView
     
     pageno = int(request.values.get('page', 1)) - 1
     rows_per_page=int(request.values.get('rows', settings.get_var('PARA/FORUM_INDEX_NUMS')))
     
     Topic = get_model('forumtopic')
     Forum = get_model('forum')
     forum = Forum.get(int(id))
     condition = Topic.c.forum == int(id)
     order_by = [Topic.c.sticky.desc(), Topic.c.created_on.desc()]
     if not forum.managers.has(request.user):
         condition = (Topic.c.hidden==False) & condition
     
     filter = request.GET.get('filter', 'all')
     if filter == 'essence':
         condition = (Topic.c.essence==True) & condition
         
     def created_on(value, obj):
         return value.strftime('%Y-%m-%d')
     
     def last_reply_on(value, obj):
         return timesince(value)
     
     def subject(value, obj):
         if obj.topic_type:
             _type = u'[%s]' % obj.get_display_value('topic_type')
         else:
             _type = ''
         s = ''
         if obj.sticky:
             s += u'<font color="red">[顶]</font>'
         if obj.hidden:
             s += u'<font color="red">[隐]</font>'
         if obj.closed:
             s += u'<font color="red">[关]</font>'
         if obj.essence:
             s += u'<font color="red">[精]</font>'
         if obj.homepage:
             s += u'<font color="red">[首]</font>'
         return _type+ '<a href="/forum/%d/%d">%s</a>' % (int(id), obj.id, obj.subject) + s
     
     fields_convert_map = {'created_on':created_on, 'subject':subject,
         'last_reply_on':last_reply_on}
     view = ListView(Topic, condition=condition, order_by=order_by,
         rows_per_page=rows_per_page, pageno=pageno,
         fields_convert_map=fields_convert_map)
     if 'data' in request.values:
         return json(view.json())
     else:
         return {'forum':forum, 'filter':filter}
Exemplo n.º 28
0
def ext(id):
    Exts = get_model("exts")
    ext = Exts.get(id)
    ext_str = ext.ext
    ScanPathes = get_model("scanpathes")
    pathes = ScanPathes.filter(ScanPathes.c.type == 'f').filter(
        ScanPathes.c.ext == ext_str)
    return {
        'pathes': pathes,
        'get_path_css': get_path_css,
    }
Exemplo n.º 29
0
def get_tables(apps_dir, apps=None, engine=None, import_models=False, settings_file='settings.ini', local_settings_file='local_settings.ini'):
    from uliweb.core.SimpleFrame import get_apps, get_app_dir
    from uliweb import orm
    from sqlalchemy import create_engine
    from StringIO import StringIO
    
    if not engine:
        engine = get_engine(apps_dir)
    
    _engine = engine[:engine.find('://')+3]
    
    buf = StringIO()
    
    con = create_engine(_engine, strategy='mock', executor=lambda s, p='': buf.write(str(s) + p))
    db = orm.get_connection(con)
    
    if import_models:
        apps = get_apps(apps_dir, settings_file=settings_file, local_settings_file=local_settings_file)
        if apps:
            apps_list = apps
        else:
            apps_list = apps[:]
        models = []
        for p in apps_list:
            if p not in apps:
                log.error('Error: Appname %s is not a valid app' % p)
                continue
            if not is_pyfile_exist(get_app_dir(p), 'models'):
                continue
            m = '%s.models' % p
            try:
                mod = __import__(m, {}, {}, [''])
                models.append(mod)
            except ImportError:
                log.exception("There are something wrong when importing module [%s]" % m)
        
    else:
        old_models = orm.__models__.keys()
        try:
            for tablename, m in orm.__models__.items():
                orm.get_model(tablename)
        except:
            print "Problems to models like:", list(set(old_models) ^ set(orm.__models__.keys()))
            raise
            
    if apps:
        tables = {}
        for tablename, m in db.metadata.tables.iteritems():
            if hasattr(m, '__appname__') and m.__appname__ in apps:
                tables[tablename] = db.metadata.tables[tablename]
    else:
        tables = db.metadata.tables
                
    return tables
Exemplo n.º 30
0
    def deserialize(self, obj):
        from redbreast.core.spec import CoreWFManager
        from uliweb.orm import get_model
        from uliweb.utils.common import Serial
        WFTask = get_model('workflow_task')
        WFTrans = get_model('workflow_trans')

        self.obj = obj
        if obj:
            workflow_spec = CoreWFManager.get_workflow_spec(obj.spec_name)
            self.spec = workflow_spec
            self.state = obj.state
            self.data = Serial.load(obj.data)
            self.ref_unique_id = obj.ref_unique_id

            #DEBUG -------------------------
            if __DEBUG__:
                print 'workflow deserialize -----------------------------(1)'
                print 'ref_unique_id: %s-%s' % (self.ref_unique_id, obj.ref_unique_id)
                print 'spec_name: %s' % self.spec.name
                print 'state: %s' % self.state
                print 'workflow deserialize -----------------------------(2)'

            #DEBUG


            start_task_obj = None
            task_list = {}

            for task_obj in obj.tasks.order_by(WFTask.c.id):
                if not start_task_obj:
                    start_task_obj = task_obj
                task_list[task_obj.id] = self.Task(
                    self, self.spec.get_task_spec(task_obj.alias_name), state=None)
                task_list[task_obj.id].deserialize(task_obj)

            #DEBUG -------------------------
            if __DEBUG__:
                for a in task_list:
                    print a, task_list[a]
                print "----------------------------------------------"
                print task_list[start_task_obj.id]
                print "----------------------------------------------"
            #DEBUG -------------------------

            self.task_tree = task_list[start_task_obj.id]

            for trans_obj in obj.trans.order_by(WFTrans.c.id):
                from_task_id = trans_obj._from_task_
                to_task_id = trans_obj._to_task_
                if from_task_id and to_task_id:
                    task_list[from_task_id].children.append(task_list[to_task_id])
                    task_list[to_task_id].parents.append(task_list[from_task_id])
Exemplo n.º 31
0
    def deserialize(self, obj):
        from redbreast.core.spec import CoreWFManager
        from uliweb.orm import get_model
        from uliweb.utils.common import Serial

        WFTask = get_model("workflow_task")
        WFTrans = get_model("workflow_trans")

        self.obj = obj
        if obj:
            workflow_spec = CoreWFManager.get_workflow_spec(obj.spec_name)
            self.spec = workflow_spec
            self.state = obj.state
            self.data = Serial.load(obj.data)
            self.ref_unique_id = obj.ref_unique_id

            # DEBUG -------------------------
            if __DEBUG__:
                print "workflow deserialize -----------------------------(1)"
                print "ref_unique_id: %s-%s" % (self.ref_unique_id, obj.ref_unique_id)
                print "spec_name: %s" % self.spec.name
                print "state: %s" % self.state
                print "workflow deserialize -----------------------------(2)"

            # DEBUG

            start_task_obj = None
            task_list = {}

            for task_obj in obj.tasks.order_by(WFTask.c.id):
                if not start_task_obj:
                    start_task_obj = task_obj
                task_list[task_obj.id] = self.Task(self, self.spec.get_task_spec(task_obj.alias_name), state=None)
                task_list[task_obj.id].deserialize(task_obj)

            # DEBUG -------------------------
            if __DEBUG__:
                for a in task_list:
                    print a, task_list[a]
                print "----------------------------------------------"
                print task_list[start_task_obj.id]
                print "----------------------------------------------"
            # DEBUG -------------------------

            self.task_tree = task_list[start_task_obj.id]

            for trans_obj in obj.trans.order_by(WFTrans.c.id):
                from_task_id = trans_obj._from_task_
                to_task_id = trans_obj._to_task_
                if from_task_id and to_task_id:
                    task_list[from_task_id].children.append(task_list[to_task_id])
                    task_list[to_task_id].parents.append(task_list[from_task_id])
Exemplo n.º 32
0
    def api_delete(self):
        id = int(request.POST.get('id'))
        model = self.model.get(id)
        orgmodel = get_model('rbacorg')
        Rel = get_model('role_perm_rel')
        model.delete()
        Rel.filter(Rel.c.scheme == id).remove()
        try:
            if model.gorg is not None:
                orgmodel.filter(orgmodel.c.id == model.gorg.id).remove()
        except NotFound as e:
            mylog.error('schema related global organization not found')

        return json({'status':'OK'})
Exemplo n.º 33
0
def forumsEX():
	c = get_model('forumcategory')
 	forum = get_model('forum')
 	user = get_model('user')
	d = {'cate':{}}	
	
	for obj in c.all():
            	d['cate'].update({obj.name:obj.forums.all()})
	
	Topic = get_model('forumtopic')	
	top20 = Topic.filter(Topic.c.closed==0).order_by(Topic.c.id.desc()).limit(20)
	d['top20'] = top20
	response.template = "forumsEX_index.html"
	return d
Exemplo n.º 34
0
    def schema_permission(self, schema_id):
        schemaObj = self.model.get(schema_id)
        RoleModel = get_model('role')
        PermModel = get_model('Permission')
        RPRModel = get_model('Role_Perm_Rel')
        roleList = list(RoleModel.all())
        roleDict = {}
        for s in roleList:
            roleDict[s.id] = s.name
        permList = list(PermModel.all())
        permDict = {}
        for s in permList:
            permDict[s.id] = s.name

        return {'schemaid':schema_id, 'schemaname':schemaObj.name, 'roleDict':roleDict, 'permDict':permDict}
Exemplo n.º 35
0
def forumsEX():
    c = get_model('forumcategory')
    forum = get_model('forum')
    user = get_model('user')
    d = {'cate': {}}

    for obj in c.all():
        d['cate'].update({obj.name: obj.forums.all()})

    Topic = get_model('forumtopic')
    top20 = Topic.filter(Topic.c.closed == 0).order_by(
        Topic.c.id.desc()).limit(20)
    d['top20'] = top20
    response.template = "forumsEX_index.html"
    return d
Exemplo n.º 36
0
 def __init__(self):
     self.status = {
         'close': {
             True: '打开',
             False: '关闭'
         },
         'sticky': {
             True: '取消顶置',
             False: '顶置'
         },
         'essence': {
             True: '取消精华',
             False: '精华'
         },
         'delete': {
             True: '恢复',
             False: '删除'
         },
         'hidden': {
             True: '取消隐藏',
             False: '隐藏'
         },
         'email': {
             True: '取消邮件关注',
             False: '设置邮件关注'
         },
         'homepage': {
             True: '取消首页显示',
             False: '设置首页显示'
         },
     }
     self.model = get_model('forum')
Exemplo n.º 37
0
 def view(self, id):
     from uliweb.utils.generic import DetailView
     from uliweb import orm
     from uliweb.contrib.upload import get_filename, get_url
     import os
     
     User = orm.get_model('user')
     
     def boolean_convert(b, obj):
         if b:
             return '<div class="ui-icon ui-icon-check"></div>'
         else:
             return '<div class="ui-icon ui-icon-closethick"></div>'
     
     user = User.get(int(id))
     if not user:
         error(_('User is not exists!'))
         
     image = get_filename(_get_portrait_image_thumbnail(user.id))
     if os.path.exists(image):
         image_url = get_url(_get_portrait_image_thumbnail(user.id))
     else:
         image_url = user.get_image_url()
     can_modify = user.id == request.user.id
     template_data = {'image_url':image_url, 'can_modify':can_modify}
     view = DetailView('user', obj=user, template_data=template_data)
     view.types_convert_map = {orm.BooleanProperty:boolean_convert}
     return view.run()
Exemplo n.º 38
0
    def _clear_files(self, slug, text):
        import re
        import itertools
        from uliweb.utils.image import fix_filename
        File = get_model('forumattachment')

        r_links = re.compile(
            r'<a.*?href=\"([^"\?]+)(?:\"|\?)|<img.*?src=\"([^"]+)\"|<embed.*?src=\"([^"]+)\"',
            re.DOTALL)
        files = filter(None, itertools.chain(*re.findall(r_links, text)))
        for row in File.filter(File.c.slug == slug):
            _f = functions.get_filename(row.file_name)
            url = functions.get_href(row.file_name)
            if url in files:
                row.enabled = True
                row.save()
            else:
                if os.path.exists(_f):
                    os.unlink(_f)
                thumbnail = fix_filename(_f, '.thumbnail')
                if os.path.exists(thumbnail):
                    os.unlink(thumbnail)

        File.filter(File.c.slug == slug).filter(
            File.c.enabled == False).remove()
Exemplo n.º 39
0
 def view(self, id):
     from uliweb.utils.generic import DetailView
     from uliweb import orm
     from uliweb.contrib.upload import get_filename, get_url
     import os
     
     User = orm.get_model('user')
     
     def boolean_convert(b, obj):
         if b:
             return '<div class="ui-icon ui-icon-check"></div>'
         else:
             return '<div class="ui-icon ui-icon-closethick"></div>'
     
     user = User.get(int(id))
     if not user:
         error(_('User is not exists!'))
         
     image = functions.get_filename(_get_portrait_image_thumbnail(user.id))
     if os.path.exists(image):
         image_url = functions.get_href(_get_portrait_image_thumbnail(user.id))
     else:
         image_url = user.get_image_url()
     can_modify = user.id == request.user.id
     template_data = {'image_url':image_url, 'can_modify':can_modify}
     view = DetailView('user', obj=user, template_data=template_data, table_class_attr='table table-bordered')
     view.types_convert_map = {orm.BooleanProperty:boolean_convert}
     return view.run()
Exemplo n.º 40
0
    def handle(self, options, global_options, *args):
        from getpass import getpass
        from uliweb.contrib.auth import create_user
        from uliweb import settings

        self.get_application(global_options)

        User = get_model("user")

        if not options.username:
            print >> sys.stderr, "error: username required"
            sys.exit(ERR_BAD_PARAM)
        if User.get(User.c.username == options.username):
            print >> sys.stderr, "error: same username user exists already"
            sys.exit(ERR_BAD_PARAM)

        password = ""
        while (not password):
            password = getpass("input the password:"******"user '%s' created successfully" % (options.username)
        else:
            print >> sys.stderr, "fail to create user '%s', error: %s" % (
                options.username, d.get("_", ""))
Exemplo n.º 41
0
    def serialize(self):
        obj = self.get_serialize_obj()
        if not obj:
            from uliweb.orm import get_model
            WFTrans = get_model('workflow_trans')
            data = {
                'workflow' : self.workflow.get_id(),
                'message'  : self.message,
                'type'     : self.type,
            }

            if self.from_task:
                data.update({
                    'from_task': self.from_task.get_id(),
                    'from_name': self.from_task.get_desc(),
                })

            if self.to_task:
                data.update({
                    'to_task'  : self.to_task.get_id(),
                    'to_name'  : self.to_task.get_desc(),
                })

            if self.operator:
                data.update({'created_user': self.operator})

            obj = WFTrans(**data)
            obj.save()
            self.obj = obj
Exemplo n.º 42
0
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
Exemplo n.º 43
0
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
Exemplo n.º 44
0
    def handle(self, options, global_options, *args):
        from uliweb import settings
        from uliweb.utils.test import client

        import os

        self.get_application(global_options)

        cwd = os.getcwd()

        c = client('.')

        ScanPathes = get_model("scanpathes")
        pathes = ScanPathes.filter(ScanPathes.c.type=='f').filter(ScanPathes.c.crbits!=0)
        num = settings.SCAN.CRFILES_PER_PAGE
        pagenum = (pathes.count()+(num-1))/num
        os.mkdir(os.path.join(cwd,'allcrfiles'))
        for i in range(pagenum):
            r = c.get('/allcrfiles/%d.html'%(i))
            fp = os.path.join(cwd,"allcrfiles/%d.html"%(i))
            f = open(fp,"w")
            f.write(r.data)
            f.close()
            print fp

        os.mkdir(os.path.join(cwd,'allcrfiles/crsnippet'))
        pathes = ScanPathes.filter(ScanPathes.c.type=='f').filter(ScanPathes.c.crbits!=0)
        for path in pathes:
            r = c.get('/allcrfiles/crsnippet/%d.html'%(path.id))
            fp = os.path.join(cwd,'allcrfiles/crsnippet/%d.html'%(path.id))
            f = open(fp,"w")
            f.write(r.data)
            f.close()
            print fp
Exemplo n.º 45
0
 def _get_users_list_view(self, c):
     from uliweb.utils.generic import ListView
     from uliweb.orm import get_model
     from uliweb import request
     from uliweb.core.html import Tag
     from uliweb import orm
     
     def username(value, obj):
         return str(Tag('a', value, href='/users/view/%d' % obj.id))
     
     def boolean_convert(b, obj):
         if b:
             return '<div class="ui-icon ui-icon-check"></div>'
         else:
             return '<div class="ui-icon ui-icon-closethick"></div>'
     
     pageno = int(request.values.get('page', 1)) - 1
     rows_per_page = int(request.values.get('rows', settings.get_var('PARA/ROWS_PER_PAGE', 10)))
     
     User = get_model('user')
     query = None
     condition = None
     if c.get('username'):
         condition = (User.c.username.like('%'+c['username']+'%')) & condition
     
     fields_convert_map = {'username':username}
     view =  ListView(User, condition=condition, query=query,
         rows_per_page=rows_per_page, pageno=pageno, 
         fields_convert_map=fields_convert_map, id='users_table')
     view.types_convert_map = {orm.BooleanProperty:boolean_convert}
     return view
Exemplo n.º 46
0
    def handle(self, options, global_options, *args):
        self.get_application(global_options)

        ScanPathes = get_model("scanpathes")

        fptxt = args[0]
        f = open(fptxt)
        for l in f:
            if len(l) > 8:
                index, mpath, mstatus, mlicence_org = l.split('\t')
                mlicence = mlicence_org.strip().lower()
                if mlicence.find('gpl') != -1:
                    if mlicence == 'gpl' or mlicence == 'lgpl':
                        path = ScanPathes.get(ScanPathes.c.path == mpath)
                        if path != None:
                            path.release = True
                            path.rnote = "release as %s,status:%s" % (
                                mlicence_org, mstatus)
                            path.save()
                            print "set %d %s as release" % (path.id, path.path)
                        else:
                            print mpath, "not found"
                    else:
                        print "warning,this mixed should handle manually:", index, mpath, mstatus, mlicence
        f.close()
Exemplo n.º 47
0
    def validate_username(self, data, all_data=None):
        from uliweb.orm import get_model

        User = get_model('user')
        user = User.get(User.c.username == data)
        if user:
            return _('User "%s" is already existed!') % data
Exemplo n.º 48
0
 def paste_image(self):
     """
     图片上传处理
     """
     import base64
     from StringIO import StringIO
     from uliweb.utils.common import log
 
     File = get_model('forumattachment')
     
     forum_id = request.GET.get('forum_id')
     slug = request.GET.get('slug')
 
     filename='forum/%s/%s.png' % (forum_id, slug)
     data = request.POST.get('urls')
     prefix = 'data:image/png;base64,'
     if data.startswith(prefix):
         fobj = StringIO(base64.b64decode(data[len(prefix):]))
         nname=functions.save_file(filename, fobj)
         url_name=functions.get_href(nname)
         ff = File(slug=slug, file_name=nname, name=nname)
         ff.save()
         return url_name
     else:
         return data
Exemplo n.º 49
0
    def handle(self, options, global_options, *args):
        from sqlalchemy import create_engine
        from uliweb import orm
        
        if not os.path.exists(options.output_dir):
            os.makedirs(options.output_dir)
        
        engine = get_engine(global_options.apps_dir)
        con = create_engine(engine)

        if not args:
            print "Failed! You should pass one or more tables name."
            sys.exit(1)
            
        for name in args:
            m = orm.get_model(name)
            if not m:
                print "Error! Can't find the table %s...Skipped!" % name
                continue
            t = m.table
            if global_options.verbose:
                print 'Dumpping %s...' % name
            filename = os.path.join(options.output_dir, name+'.txt')
            if options.text:
                format = 'txt'
            else:
                format = None
            dump_table(t, filename, con, delimiter=options.delimiter, 
                format=format, encoding=options.encoding)
Exemplo n.º 50
0
    def serialize(self):
        from uliweb.orm import get_model
        from uliweb.utils.common import Serial
        WF = get_model('workflow')

        data = {
            'spec_name'     : self.spec.name,
            'state'         : self.state,
            'data'          : Serial.dump(self.data),
            'desc'          : self.spec.desc,
            'ref_unique_id' : self.ref_unique_id,
        }

        #DEBUG -------------------------
        if __DEBUG__:
            print 'workflow serialize -----------------------------(1)'
            for i in data:
                print (i, data[i])

            print 'spec_name: %s' % self.spec.name
            print 'state: %s' % self.state
            print 'workflow serialize -----------------------------(2)'

        #DEBUG
        if self.obj:
            if self.operator:
                data.update({'modified_user': self.operator})
            self.obj.update(**data)
        else:
            if self.operator:
                data.update({'modified_user': self.operator})
                data.update({'created_user': self.operator})
            self.obj = WF(**data)
        self.obj.save()
Exemplo n.º 51
0
    def admin_forum_edit(self, id):
        """
        修改论坛
        """
        from uliweb.utils.generic import EditView

        forum = get_model('forum')

        obj = forum.get(int(id))

        def post_created_form(fcls, model, obj):
            fcls.managers.query = obj.managers

        def success_data(obj, data):
            d = obj.to_dict()
            d['managers'] = convert_managers(None, obj)
            return d

        view = EditView(
            self.model,
            obj=obj,
            success_data=success_data,
            post_created_form=post_created_form,
        )
        return view.run(json_result=True)
Exemplo n.º 52
0
 def uploadimage(self, tid):
     """
     上传图片
     :param tid: 论坛id
     """
     import Image
     from uliweb.utils.image import thumbnail_image, fix_filename
     from uliweb import json_dumps
     from uliweb.form import Form, ImageField
     
     File = get_model('tutorials_albums')
     obj = self.model.get_or_notfound(int(tid))
     
     class UploadForm(Form):
         filename = ImageField()
     
     form = UploadForm()
     flag = form.validate(request.values, request.files)
     if flag:
         filename = functions.save_file(os.path.join('tutorials', str(obj.id), form.filename.data.filename), form.filename.data.file)
         #process thumbnail
         rfilename, thumbnail = thumbnail_image(functions.get_filename(filename, filesystem=True), filename, settings.get_var('TUTORIALS/IMAGE_THUMBNAIL_SIZE'))
         thumbnail_url = functions.get_href(thumbnail)
         url = functions.get_href(filename)
         f = File(filename=filename, tutorial=int(tid))
         f.save()
         return json({'success':True, 'filename':form.filename.data.filename, 'url':url, 'thumbnail_url':thumbnail_url, 'id':f.id}, content_type="text/html;charset=utf-8")
     else:
         #如果校验失败,则再次返回Form,将带有错误信息
         return json({'success':False}, content_type="text/html;charset=utf-8")
Exemplo n.º 53
0
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
Exemplo n.º 54
0
    def postimage(self, tid):
        """
        处理HTML5文件上传
        :param tid:教程id
        """
        import base64
        from StringIO import StringIO
        from uliweb.utils.image import thumbnail_image, fix_filename

        File = get_model('tutorials_albums')

        if request.method == 'POST':
            _filename = os.path.join('tutorial/%s' % tid,
                                     request.values.get('filename'))
            fobj = StringIO(base64.b64decode(request.params.get('data')))
            filename = functions.save_file(_filename, fobj)
            #process thumbnail
            rfilename, thumbnail = thumbnail_image(
                functions.get_filename(filename, filesystem=True), filename,
                settings.get_var('TUTORIALS/IMAGE_THUMBNAIL_SIZE'))
            thumbnail_url = functions.get_href(thumbnail)
            url = functions.get_href(filename)
            f = File(filename=filename, tutorial=int(tid))
            f.save()
            return json({
                'success': True,
                'data': {
                    'filename': request.values.get('filename'),
                    'url': url,
                    'thumbnail_url': thumbnail_url,
                    'id': f.id
                }
            })
Exemplo n.º 55
0
    def handle(self, options, global_options, *args):
        from uliweb.manage import make_simple_application
        from uliweb import orm
        from getpass import getpass

        self.get_application(global_options)

        username = ''
        while not username:
            username = input("Please enter the super user's name: ")
        email = ''
        while not email:
            email = input("Please enter the email of [{}]: ".format(username))

        password = ''
        while not password:
            password = getpass(
                "Please enter the password for [{}({})]: ".format(
                    username, email))
        repassword = ''
        while not repassword:
            repassword = getpass("Please enter the password again: ")

        if password != repassword:
            print("The password is not matched, can't create super user!")
            return

        orm.set_dispatch_send(False)

        User = orm.get_model('user', options.engine)
        user = User(username=username, email=email)
        user.set_password(password)
        user.is_superuser = True
        user.save()
Exemplo n.º 56
0
 def api_loadschema(self):
     SchemaModel = get_model('rbacscheme')
     schemaList = list(SchemaModel.all())
     ret = {}
     for s in schemaList:
         ret[s.id] = s.name
     return json(ret)