示例#1
0
 def json(self):
     d = self.__dict__.copy()
     comments = [c.json() for c in self.comments()]
     d['comments'] = comments
     log('debug weibo json({})comments({}) type=({}) '.format(
         d, comments, type(comments)))
     return d
示例#2
0
文件: views.py 项目: a58492906/CM2
def DeleteFile(request):
    infor = json.loads(request.body)
    bookID=infor['id']
    type = infor['type']
    userID=infor['userID']
    user=User.objects.get(id=userID)
    current=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    if type =='pdf':
        file=book.objects.get(id=bookID)
    else:
        file=others.objects.get(id=bookID)
    if type=='pdf':
        newLog=log(logType='Delete',titles=file.titles,user=user.username,file_type=file.file_type,path=file.path,
               file_ownership=file.file_ownership,modification_time=current,monograph_part=file.monograph_part,
               study_reference=file.study_reference,Intervention=file.Intervention,study_design=file.study_design,
               study_ID=file.study_ID)
    else:
        newLog=log(logType='Delete',titles=file.titles,user=user.username,file_type=file.file_type,path=file.path,
               file_ownership=file.file_ownership,modification_time=current,monograph_part=file.monograph_part)
    abso_path = '/Applications/XAMPP/htdocs' + file.path
    dest_path='/Applications/XAMPP/htdocs/Bin'
    
    if os.path.exists(abso_path) is False:
        return Response({'status':abso_path})
    else:
        credentials = get_credentials()
        http = credentials.authorize(httplib2.Http())
        service = discovery.build('gmail', 'v1', http=http)
        SendMessage(service, "me", CreateMessage("*****@*****.**", "*****@*****.**",  "File Delete Notification", file.titles + " \n\nDeleted.Check details in the log page"))
        shutil.move(abso_path, dest_path)       
        file.delete()
        newLog.save()
        return Response({'status':200})
示例#3
0
 def update(cls, id, form):
     t = cls.find(id)
     valid_names = [
         'title',
         'content',
     ]
     log("weibo update ***** id({}) form({}) t ({})".format(id, form, t))
     for key in form:
         # 这里只应该更新我们想要更新的东西
         if key in valid_names:
             setattr(t, key, form[key])
     # 更新修改时间
     t.ut = int(time.time())
     t.save()
     return t
示例#4
0
文件: views.py 项目: a58492906/CM2
def AddFile(request): 
    newFile = request.FILES['file'] 
    type = request.POST.get('type')
    title=request.POST.get('title')
    category=request.POST.get('category')
    monograph=request.POST.get('monograph')
    path='/New File/'+ newFile.name
    folder_path = '/Applications/XAMPP/htdocs/New File'
    current=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    userID=request.POST.get('userID')
    user=User.objects.get(id=userID)
    if type=='pdf':
        reference=request.POST.get('studyRef')
        intervention=request.POST.get('intervention')
        design=request.POST.get('studyDesgin')
        ID=request.POST.get('studyID')
        file=book(titles=title,file_type=type,path=path,file_ownership=category,modification_time=current,
                  monograph_part=monograph,study_reference=reference,Intervention=intervention,study_design=design,study_ID=ID)
    
    else:
        file=others(titles=title,file_type=type,path=path,
                    file_ownership=category,modification_time=current,monograph_part=monograph)
    file.save()
    destination = open(os.path.join(folder_path, newFile.name), 'wb+')
    for chunk in newFile.chunks():     
        destination.write(chunk)
    newLog=log(logType='Add',titles=title,user=user.username,file_type=type,path=path,
                   file_ownership=category,modification_time=current,monograph_part=monograph)
    newLog.save()    
    return Response({'status':200})
示例#5
0
文件: views.py 项目: a58492906/CM2
def EditFile(request): 
    newFile = request.FILES['file'] 
    type = request.POST.get('type')
    id = request.POST.get('id')
    userID=request.POST.get('userID')
    current=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    if newFile is None:
        return Response({'status':400}) 
    else:   
        if type =='pdf':
            file=book.objects.get(id=id)
        else:
            file=others.objects.get(id=id)
        user=User.objects.get(id=userID)
        newLog=log(logType='Edit',titles=file.titles,user=user.username,file_type=file.file_type,path=file.path,file_ownership=file.file_ownership,modification_time=current,monograph_part=file.monograph_part)
        path=file.path
        abso_path = '/Applications/XAMPP/htdocs' + path
        fpath , fname = os.path.split(path)
        if os.path.exists(abso_path) is False:
            return Response({'status':400})
        else:
            os.remove(abso_path)
            abso_path = '/Applications/XAMPP/htdocs' + fpath
            destination = open(os.path.join(abso_path, newFile.name), 'wb+')
            for chunk in newFile.chunks():     
                destination.write(chunk)   
            file.titles=newFile.name
            fpath = os.path.join(fpath, '', newFile.name)
            file.path=fpath    
            file.modification_time=current
            file.save()
            newLog.save()
            destination.close()  
            return Response({'status':200})
示例#6
0
def update_data():
    if request.method == 'GET':
        return '<html><h1>404!!你访问的页面不存在</h1><body></body></html>'
    if not session.get('username'):
        return redirect(url_for('admin_login'))
    t_name = request.form['table']
    op = request.form['operation']

    data = request.form.getlist('data[]')
    num = len(data)
    if t_name == 'department':
        with db.transaction():
            i = 1 if num % 2 else 0
            while i < num:
                departmentID = data[i]
                departmentName = data[i+1]
                i += 2
                departmentE = departments.find_first(
                    'where departmentID=? or departmentName=?',
                    departmentID, departmentName)
                if op == 'add':
                    if departmentE:
                        return "error! The id have already exists"
                    department = departments(
                        departmentID=departmentID,
                        departmentName=departmentName)
                    lg = log(
                        details=u'{} add {} {} into table department'
                        .format(session.get('username'),
                                departmentID, departmentName))
                    try:
                        department.insert()
                        lg.insert()
                    except Exception, e:
                        return e.message
                elif op == 'delete':
                    if not departmentE:
                        return "error! the item doesn't exist"
                    lg = log(
                        details=u'{} delete {} {} from table department'
                        .format(session.get('username'),
                                departmentID, departmentName))
                    try:
                        departmentE.delete()
                        lg.insert()
                    except Exception, e:
                        return e
示例#7
0
def logEntry(event, table=None, tableRow_uuid=None):
    uuid = UUID.uuid4()
    timestamp = datetime.now()
    tenant_uuid = session['tenant_uuid']
    user_uuid = session['user_uuid']

    req = log(uuid = uuid,
              timestamp = timestamp,
              tenant_uuid = tenant_uuid,
              user_uuid = user_uuid,
              table = table,
              tableRow_uuid = tableRow_uuid,
              event = event)

    try:
        db.session.add(req)
        db.session.commit()
        return {'success': 'Log entry added'}
    except:
        return {'Error': 'Could not add log entry'}
示例#8
0
 def __init__(self, form):
     self.id = None
     self.title = form.get('title', '')
     self.content = form.get('content', '')
     log('debug weibo init form = ({}) content =({}) '.format(
         form, self.content))
示例#9
0
 def comments(self):
     log('debug Weibo comment({})'.format(
         Comment.find_all(weibo_id=self.id)))
     return Comment.find_all(weibo_id=self.id)
示例#10
0
                )
                if ques:
                    return 'the problem has already existed in database'
                ques = question(
                    title=data[0],
                    option=data[1],
                    type=data[2],
                    difficult=data[3],
                    part=data[4],
                    score=data[5],
                    right_ans=data[6]

                )
                lg = log(
                    details=u'{} add {} into table question'
                    .format(session.get('username'),
                            data[0])
                )
                try:
                    ques.insert()
                    lg.insert()
                except Exception, e:
                    return e.message
            elif op == 'delete':
                i = 1
                while i < num:
                    data[i+1] = data[i+1][:-2].replace('\n', '')
                    k = 1
                    for t in data:
                        print k, t
                        k += 1
示例#11
0
def getLogPage(action, request, session):
    """
        Get Log page from DB by selected number filtered by requested userID and wizardID.

        Arguments:
            action  - 301
            request - form (page, per_page, userID, wizardID)
            session - current session

        Filter by (attrs):
            userID  - user ID
            wizardID- wizard ID
            otype   - order type (Config.valid_order_types)
            context - search context

        Returns:
            exchange_error, exchange_message - exchange error info
            data    - Pagination object from DB models
            items   - page column items
    """
    print_db_state()

    form = request.form

    print_action(action, 'DBase.GetLogPage')

    exchange_message = ''
    exchange_error = 0
    data = None

    page = int(form.get('page', 0)) or 1
    per_page = int(form.get('per_page', 0)) or DEFAULT_PER_PAGE

    sort = form.get('sort') or ''

    userID = form.get('userID', None)
    user = userID and User.query.filter_by(userID=userID).first()

    if IsDebug and userID:
        print '>>> User[%s]: %s' % (userID, user and user.userID == userID and 'OK' or 'invalid!')

    wizardID = form.get('wizardID', None)
    module = wizardID and Module.query.filter_by(wizardID=wizardID).first()

    if IsDebug and wizardID:
        print '>>> Module[%s]: %s' % (wizardID, module and module.wizardID == wizardID and 'OK' or 'invalid!')

    otype = int(form.get('otype', -1))

    if IsDebug and otype in valid_order_types:
        print '>>> Order type[%s]: %s' % (otype, valid_order_names[otype])

    context = form.get('search_context', None)

    if IsDebug and context:
        print '>>> Search context: [%s]' % context

    data = log(DEFAULT_LOG_MODE, page, per_page, user=user, module=module, otype=otype, context=context, check=IsDBCheck, sort=sort)

    items = []
    headers = get_log_headers()
    line_in_page = 0 #(page-1) * per_page

    for row in data.items:
        x = dict(zip(headers[0], row))
        line_in_page += 1

        s = x['document'] or ''
        if s and s.startswith('#'):
            x['document'] = s[1:].strip()

        x['root'] = '%s' % request.script_root
        x['image'] = '%s-16.png' % ( \
            x['rating'] == RATING_UP and 'up' or x['rating'] == RATING_DOWN and 'down' or 
            x['rating'] == RATING_EQUAL and 'equal' or 'undef')
        x['num'] = line_in_page
        x['cdate'] = cdate(x['reg_date'], fmt=LOCAL_EASY_TIMESTAMP)
        x['price'], x['currency'] = x['current_price'].split()
        x['code'] = x['otype'] == ORDER_DONE and x['document'] or x['code']
        x['updatable'] = x['option_update'] and 'updatable' or x['option_cost'] and 'cost' or 'fixed'

        for n, column in enumerate(headers[1]):
            x['%s_title' % column['id']] = column['title']

        items.append([x['id'], [ column.has_key('value') and (column['value'] % x) or x[column['id']]
            for n, column in enumerate(headers[1])
                if column.get('visible') ]
        ])

    return (exchange_error, exchange_message, data, items)