def post(self, *args, **kwargs): if is_json_request(self.request): body = json.loads(self.request.body) body = body.get('data', None) else: body = self.get_argument('data', None) body = escape.json_decode(body) if body else {} # self.send_error(reason="仅支持Content-type:application/json") # return db = self.settings['mongo_client'][self.db] for row in body: id = row.get('id', None) if row.get('_state', None) == 'removed': if self.is_object_id(id): yield db[self.cname].remove({"_id": ObjectId(id)}) if id and self.is_object_id(id): # update row['update_time'] = format_datetime(datetime.now()) row['update_user'] = self.current_user.get('userid', '') yield db[self.cname].update({"_id": ObjectId(id) if self.is_object_id(id) else id}, { "$set": clone_dict(row, without=[]) }) else: obj = clone_dict(row) obj['id'] = ObjectId() obj['_id'] = obj['id'] obj['create_time'] = format_datetime(datetime.now()) obj['create_user'] = self.current_user.get('userid', '') yield db[self.cname].insert(obj) # self.write(generate_response(message="保存成功")) self.send_message("保存成功")
def __init__(self, *args, **kwargs): event = kwargs.pop('event') super(ProgrammeAdminForm, self).__init__(*args, **kwargs) self.helper = horizontal_form_helper() self.helper.form_tag = False self.helper.layout = Layout( Fieldset(u'Ohjelmavastaavan merkinnät (eivät näy ohjelmanjärjestäjälle)', 'category', 'room', 'start_time', 'length', 'tags', 'notes', ), ) self.fields['length'].widget.attrs['min'] = 0 self.fields['category'].queryset = Category.objects.filter(event=event) self.fields['room'].queryset = Room.objects.filter(venue=event.venue) self.fields['tags'].queryset = Tag.objects.filter(event=event) # XXX self.fields['start_time'].choices = [('', u'---------')] + [ ( start_time, format_datetime(start_time) ) for start_time in AllRoomsPseudoView(event).start_times() ]
def get_programmes_by_start_time(self, include_unpublished=False, request=None): results = [] prev_start_time = None cont_criteria = dict() if include_unpublished else dict( state='published') for start_time in self.start_times(): cur_row = [] criteria = dict( category__event=self.event, start_time=start_time, length__isnull=False, ) if not include_unpublished: criteria.update(state='published') incontinuity = prev_start_time and (start_time - prev_start_time > ONE_HOUR) incontinuity = 'incontinuity' if incontinuity else '' prev_start_time = start_time results.append((start_time, incontinuity, cur_row)) for room in self.rooms.all(): programmes = room.programmes.filter(**criteria) num_programmes = programmes.count() if num_programmes == 0: if room.programme_continues_at(start_time, **cont_criteria): # programme still continues, handled by rowspan pass else: # there is no (visible) programme in the room at start_time, insert a blank cur_row.append((None, None)) else: if programmes.count() > 1: logger.warn( 'Room %s has multiple programs starting at %s', room, start_time) if (request is not None and self.event.programme_event_meta.is_user_admin( request.user)): messages.warning( request, 'Tilassa {room} on päällekkäisiä ohjelmanumeroita kello {start_time}' .format( room=room, start_time=format_datetime( start_time.astimezone(tzlocal())), )) programme = programmes.first() rowspan = self.rowspan(programme) cur_row.append((programme, rowspan)) return results
def get_programmes_by_start_time(self, include_unpublished=False, request=None): results = [] prev_start_time = None cont_criteria = dict() if include_unpublished else dict(state='published') for start_time in self.start_times(): cur_row = [] criteria = dict( category__event=self.event, start_time=start_time, length__isnull=False, ) if not include_unpublished: criteria.update(state='published') incontinuity = prev_start_time and (start_time - prev_start_time > ONE_HOUR) incontinuity = 'incontinuity' if incontinuity else '' prev_start_time = start_time results.append((start_time, incontinuity, cur_row)) for room in self.rooms.all(): programmes = room.programme_set.filter(**criteria) num_programmes = programmes.count() if num_programmes == 0: if room.programme_continues_at(start_time, **cont_criteria): # programme still continues, handled by rowspan pass else: # there is no (visible) programme in the room at start_time, insert a blank cur_row.append((None, None)) else: if programmes.count() > 1: logger.warn('Room %s has multiple programs starting at %s', room, start_time) if ( request is not None and self.event.programme_event_meta.is_user_admin(request.user) ): messages.warning(request, 'Tilassa {room} on päällekkäisiä ohjelmanumeroita kello {start_time}'.format( room=room, start_time=format_datetime(start_time.astimezone(tzlocal())), ) ) programme = programmes.first() rowspan = self.rowspan(programme) cur_row.append((programme, rowspan)) return results
def get(self, *args, **kwargs): keys = yield Task(self.client.keys) result = [] for key in keys: tmp_user=yield Task(self.client.get,key) # china user=pickle.loads(tmp_user) if not user.get('user',None): continue expirestime=user['__expires__'] result.append({ "id":key, "loginname":user['user']['username'], "remoteip":user['user']['remote_ip'], "logintime":format_datetime(user['user']['login_time']), "lastaccesstime":format_datetime(user['last_access_time']) , "expiretime":format_datetime(utc_to_local(expirestime)) , }) self.send_message(result)
def post(self, *args, **kwargs): body = escape.json_decode(self.request.body) role_id = body.get("role_id", None) users = body.get("users", []) if role_id and users: db = self.settings["db"] role = yield db.roles.find_one({"_id": ObjectId(role_id)}) for item in users: if item["_state"] == "removed": yield db.users.update( {"_id": ObjectId(item["id"])}, { "$pull": {"roles": role["code"]}, "$set": { "update_time": format_datetime(datetime.now()), "update_user": self.current_user.get("username", ""), }, }, ) elif item["_state"] == "added" and not item.get("id", None): user = clone_dict(item) if hasattr(user, "roles"): user["roles"].append(role["code"]) else: user["roles"] = [role["code"]] user["id"] = ObjectId() user["_id"] = user["id"] user["create_time"] = format_datetime(datetime.now()) user["create_user"] = self.current_user.get("username", "") yield db.users.insert(user) else: user = clone_dict(item) user["update_time"] = format_datetime(datetime.now()) user["update_user"] = self.current_user.get("username", "") # if user.get('roles',None): user["roles"].append(role["code"]) # yield db.users.update({'_id': ObjectId(item['id'])}, {"$push":{"roles":role['code']}}) yield db.users.update({"_id": ObjectId(item["id"])}, {"$set": user})
def get(self, *args, **kwargs): code=self.get_argument('code','') industry_code=self.get_argument('industry_code','') # 下载现金流总表 urls=[ ('balancesheet','http://money.finance.sina.com.cn/corp/go.php/vDOWN_BalanceSheet/displaytype/4/stockid/%s/ctrl/all.phtml'%code), ('profitstatement','http://money.finance.sina.com.cn/corp/go.php/vDOWN_ProfitStatement/displaytype/4/stockid/%s/ctrl/all.phtml'%code), ('cashflow','http://money.finance.sina.com.cn/corp/go.php/vDOWN_CashFlow/displaytype/4/stockid/%s/ctrl/all.phtml'%code) ] db=self.settings['db'] for cname,url in urls: file_path=self.download_file(url,code) result=[] with open(file_path,'rb') as f: for line in f: line=line.decode('gb2312').encode('utf8') line_arr=line.split('\t') if len(line_arr)==1: pass else: result.append(line_arr) df=pd.DataFrame(result) df=df.set_index(df[0]) del df[0] df=df.T df['code']=code columns={'industry_code':industry_code,'type':cname,'columns':df.columns.tolist()} for i in range(len(df)): data=df.ix[i+1].to_dict() _id=ObjectId() data['_id']=_id data['id']=_id data['create_user']=self.current_user.get('userid') data['create_time']=format_datetime(datetime.now()) yield db[cname].insert(data) yield db.stock.columns.update({'industry_code':industry_code,'type':cname},{'$set':columns},True) del df yield db.csrcindustry.update({'securities_code':code},{'$set':{'download_flag':1}}) self.send_message('下载成功')
def post(self, *args, **kwargs): file_list = self.request.files.get("file", []) fs = motor.MotorGridFS(self.database, self.root_collection) name = self.get_argument("name", "") chunk = int(self.get_argument("chunk", 0)) chunks = int(self.get_argument("chunks", 0)) if chunks and name: # 存在多块数据 file_data = file_list[0] dir_path = os.path.dirname(__file__).split("/")[:-1] dir_path.append("upload") upload_path = "/".join(dir_path) upload_path = upload_path + "/" + self.session.id if not os.path.exists(upload_path): os.mkdir(upload_path) file_path = upload_path + "/" + name with open(file_path, "a+") as f: f.write(file_data.get("body")) if not chunks or chunk == chunks - 1: catalog_id = self.get_argument("catalog_id", None) if not catalog_id: self.send_error(reason="必须选择目录") return file_type = mimetypes.guess_type(name)[0] or "text/plain" _id = ObjectId() with open(file_path, "r") as f: body = f.read() # body=file_data.get('body') kwargs = { "filename": name, "_id": _id, "id": _id, "create_user": self.current_user.get("userid"), "create_time": format_datetime(datetime.now()), "catalog_id": catalog_id, "content_type": file_data.get("content_type"), "file_size": "%sK" % str(len(body) / 1024.0), "filetype": file_type, } gridin = yield fs.new_file(**kwargs) yield gridin.write(body) yield gridin.close() os.remove(file_path) pass else: self.send_error(status_code="500", reason="内部错误")
def __init__(self, *args, **kwargs): event = kwargs.pop('event') super(ScheduleForm, self).__init__(*args, **kwargs) self.helper = horizontal_form_helper() self.helper.form_tag = False self.fields['length'].widget.attrs['min'] = 0 self.fields['room'].queryset = Room.get_rooms_for_event(event) self.fields['start_time'].choices = [('', '---------')] + [ (start_time, format_datetime(start_time)) for start_time in AllRoomsPseudoView(event).start_times() ] self.fields['tags'].queryset = Tag.objects.filter(event=event)
def __init__(self, *args, **kwargs): event = kwargs.pop('event') super(ScheduleForm, self).__init__(*args, **kwargs) self.helper = horizontal_form_helper() self.helper.form_tag = False self.fields['length'].widget.attrs['min'] = 0 self.fields['room'].queryset = Room.objects.filter(venue=event.venue) self.fields['start_time'].choices = [('', u'---------')] + [ ( start_time, format_datetime(start_time) ) for start_time in AllRoomsPseudoView(event).start_times() ]
def put(self, *args, **kwargs): """接受用户的请求对文档进行更新 :param args url路径的参数 """ if is_json_request(self.request): body = json.loads(self.request.body) else: self.send_error(reason="仅支持Content-type:application/json") db = self.settings['mongo_client'][self.db] id = body.get('_id', None) if id : # update body['update_time'] = format_datetime(datetime.now()) body['update_user'] = self.current_user.get('userid', '') yield db[self.cname].update({"_id": ObjectId(id) if self.is_object_id(id) else id}, { "$set": clone_dict(body) }) self.send_message("保存成功")
def get_programmes_by_start_time(self, include_unpublished=False, request=None): results = [] prev_start_time = None cont_criteria = dict() if include_unpublished else dict( state='published') rooms = self.rooms.all() criteria = dict( category__event=self.event, length__isnull=False, start_time__isnull=False, room__in=rooms, ) if not include_unpublished: criteria.update(state='published') # programme_index[start_time][room] = list of programmes # TODO select_related programme_index = defaultdict(lambda: defaultdict(list)) programmes = (Programme.objects.filter(**criteria).select_related( 'category__event').select_related('room').prefetch_related('tags')) for programme in programmes: programme_index[programme.start_time][programme.room_id].append( programme) for start_time in self.start_times(): cur_row = [] incontinuity = prev_start_time and (start_time - prev_start_time > ONE_HOUR) incontinuity = 'incontinuity' if incontinuity else '' prev_start_time = start_time results.append((start_time, incontinuity, cur_row)) for room in rooms: programmes = programme_index[start_time][room.id] num_programmes = len(programmes) if num_programmes == 0: if room.programme_continues_at(start_time, **cont_criteria): # programme still continues, handled by rowspan pass else: # there is no (visible) programme in the room at start_time, insert a blank cur_row.append((None, None)) else: if num_programmes > 1: logger.warn( 'Room %s has multiple programs starting at %s', room, start_time) if (request is not None and self.event.programme_event_meta.is_user_admin( request.user)): messages.warning( request, 'Tilassa {room} on päällekkäisiä ohjelmanumeroita kello {start_time}' .format( room=room, start_time=format_datetime( start_time.astimezone(tzlocal())), )) programme = programmes[0] rowspan = self.rowspan(programme) cur_row.append((programme, rowspan)) return results
def __str__(self): from core.utils import format_datetime return format_datetime(self.start_time) if self.start_time else 'None'
def formatted_times(self): return '{start_time} – {end_time}'.format( start_time=format_datetime(self.start_time), end_time=format_datetime(self.end_time), )
def formatted_start_time(self): return format_datetime(self.start_time) if self.start_time else ''
def formatted_times(self): return u'{start_time} – {end_time}'.format( start_time=format_datetime(self.start_time), end_time=format_datetime(self.end_time), )
def __unicode__(self): from core.utils import format_datetime return format_datetime(self.start_time) if self.start_time else u'None'
def formatted_start_time(self): from core.utils import format_datetime return format_datetime(self.start_time) if self.start_time else ''
def get_programmes_by_start_time(self, include_unpublished=False, request=None): results = [] prev_start_time = None cont_criteria = dict() if include_unpublished else dict(state='published') rooms = self.rooms.all() criteria = dict( category__event=self.event, length__isnull=False, start_time__isnull=False, room__in=rooms, ) if not include_unpublished: criteria.update(state='published') # programme_index[start_time][room] = list of programmes # TODO select_related programme_index = defaultdict(lambda: defaultdict(list)) programmes = ( Programme.objects.filter(**criteria) .select_related('category__event') .select_related('room') .prefetch_related('tags') ) for programme in programmes: programme_index[programme.start_time][programme.room_id].append(programme) for start_time in self.start_times(): cur_row = [] incontinuity = prev_start_time and (start_time - prev_start_time > ONE_HOUR) incontinuity = 'incontinuity' if incontinuity else '' prev_start_time = start_time results.append((start_time, incontinuity, cur_row)) for room in rooms: programmes = programme_index[start_time][room.id] num_programmes = len(programmes) if num_programmes == 0: if room.programme_continues_at(start_time, **cont_criteria): # programme still continues, handled by rowspan pass else: # there is no (visible) programme in the room at start_time, insert a blank cur_row.append((None, None)) else: if num_programmes > 1: logger.warn('Room %s has multiple programs starting at %s', room, start_time) if ( request is not None and self.event.programme_event_meta.is_user_admin(request.user) ): messages.warning(request, 'Tilassa {room} on päällekkäisiä ohjelmanumeroita kello {start_time}'.format( room=room, start_time=format_datetime(start_time.astimezone(tzlocal())), ) ) programme = programmes[0] rowspan = self.rowspan(programme) cur_row.append((programme, rowspan)) return results
def get_start_time(self): return format_datetime(self.start_time)
def get_end_time(self): return format_datetime(self.end_time)