def upload(): form = UploadForm(request.form) if request.method == 'POST' and form.validate(): room = Room() room.set_attrs(form.data) image = request.files.get('image') video = request.files.get('video') # print(video) # 对文件名进行包装,为了安全,不过对中文的文件名显示有问题 filename_image = secure_filename(image.filename) filename_video = secure_filename(video.filename) image_path = os.path.join(current_app.config['UPLOAD_PATH_IMAGE'], filename_image) video_path = os.path.join(current_app.config['UPLOAD_PATH_VIDEO'], filename_video) image.save(image_path) video.save(video_path) datas = form.data datas = datas.update({image:image_path}) # datas = datas.update({video:video_path}) print(type(form.data)) print(form.data) # room.set_attrs(form.data) # # db.session.add(room) # db.session.commit() return redirect(url_for('web.upload')) elif request.method == 'GET': return render_template('upload.html', form={'data': {}}) else: return form.errors
def test_allocations_load_state(self): path = "db/" file_name = "mydb" file_ = file_name+".db" #clean up to avoid conflict between tests os.remove(path+file_) self.clear_stores() #memory livingspace = LivingSpace('hwan') LivingSpace.add(livingspace) fellow = Fellow("onon", "ekek", "000009", "Y") fellow.register() livingspace.allocate_to(fellow) prev_allocations = Room.all_allocations().copy() Allocation.save_state(file_name) #clear memory stores self.clear_stores() empty_allocations = Room.all_allocations().copy() #db Allocation.load_state(file_name) loaded_allocations = Room.all_allocations().copy() #compare expected_output = ["HWAN", "LIVINGSPACE", "000009"] output = [prev_allocations[0], empty_allocations, loaded_allocations[0]] self.assertEqual(output, [expected_output, [], expected_output])
def create_event(attributes): start_at = datetime.strptime(attributes['start_at'], DATETIME_FORMAT) - timedelta(hours=UTC_OFFSET) room = Room( name=attributes['name'], teacher=current_user, role=Room.CONSULTATION ) event = Event( name=attributes['name'], teacher=current_user, room=room, start_at=start_at ) groups = [] for group_id in attributes['groups']: groups.append( Group.query.get(group_id) ) room.groups = groups db.session.add(room) db.session.add(event) db.session.commit() _get_events()
def test_to_json(): room = Room(1, False, True, 0) assert room.to_json() == { "room_id": 1, "is_on": False, "is_veg_room": room.is_veg_room, "brightness": room.brightness, }
def print_room(room_name): try: room = Room(room_name) allocations = room.allocations() print_pretty(" Allocations to room: " + room.name) print_pretty(Room.members(allocations)) except Exception as e: print_pretty(str(e))
def find_all_rooms_listener(message) -> None: found_rooms = message["rooms"] for fr in found_rooms: rooms.append(Room.from_json(fr)) room_map = {room.room_id: room for room in rooms} first_id = room_dict["room"]["room_id"] second_id = room_dict2["room"]["room_id"] assert room_map[first_id] == Room.from_json(room_dict["room"]) assert room_map[second_id] == Room.from_json(room_dict2["room"])
def find_room_listener(message) -> None: print("got message:", message) assert "room" in message assert message["room"] is not None returned_room = Room.from_json(message["room"]) expected_room = Room.from_json(room_dict["room"]) print("returned_room:", returned_room, "expected_room:", expected_room) assert returned_room == expected_room flag.append(True)
def create_rooms(number_of_rooms, creator_id, room_status): for i in range(number_of_rooms): room = Room(code=f"room{len(Room.query.all()) + i + 1}", created_by=creator_id, status=room_status, collection_id=1) db.session.add(room) db.session.commit() room.add_user(creator_id)
def test_print_existing_allocations_to_screen(self): self.clear_stores() office = Office("NDO2") Dojo.add_room(office) fellow = Fellow("Xone2", "Ndobile2", "0856443324", "y") fellow.register() office.allocate_to(fellow) allocations_ = Room.all_allocations() output = Room.members(allocations_, room_tag=True) expected_output = " NDO2-OFFICE, 0856443324, NDOBILE2, XONE2, FELLOW\n" self.assertEqual(output, expected_output)
def test_add_many_users(self): first_room = Room(name="Room1") db.session.add(first_room) db.session.commit() second_room = Room(name="Room2") db.session.add(second_room) db.session.commit() third_room = Room(name="Room3") db.session.add(third_room) db.session.commit() self.assertEqual(Room.query.count(), 3)
def test_print_existing_allocations_to_default_file(self): self.clear_stores() office = Office("ND2") Dojo.add_room(office) fellow = Fellow("Xne2", "Ndoile2", "0868443324", "y") fellow.register() office.allocate_to(fellow) allocations_ = Room.all_allocations() expected_output = Room.members(allocations_, room_tag=True) Room.to_file(expected_output) path = "output/" f = open(path + "File.txt", "r") output = f.read() #"NDO2-Office, 0856443324, NDOBILE2, XONE2, FELLOW" f.close() self.assertEqual(expected_output, output)
def create_and_save_room(name, active, user, course): ''' Helper to create a room and save it to the graph :param name: the name of the room :param active: whether or not this room will be active by default :param admin_id: the user id representing the admin :param course_id: the course code / id representing the course that this room studies :return ValueError: raised if either the course or user cannot be found in the graph ''' new_room = Room(name=name, active=active) new_room.save() new_room.admin.connect(user) user.rooms.connect(new_room) new_room.course.connect(course) return new_room
def test_create_room_from_json(): room = Room.from_json({"room_id": 1}) assert room.room_id == 1 assert room.is_on == False # auto-initialized to False if not present assert room.is_veg_room == False # auto-initialized to False if not present assert room.brightness == None # auto-initialized to None
def reallocate_person(phone, room_name): try: person = get_person(phone) room = get_room(room_name) print_pretty(Room.reallocate(person, room)) except Exception as e: print_pretty(str(e))
def test_common(self): new_room = Room(name="Room") db.session.add(new_room) db.session.commit() room = Room.query.one() self.assertEqual(room.name, "Room")
def test_user_and_room_with_many_schedules(self): new_user = User(name="Luiza") db.session.add(new_user) new_room = Room(name="Room") db.session.add(new_room) first_schedule = Schedule(date=datetime(2018, 10, 12), user=new_user, room=new_room) db.session.add(first_schedule) second_schedule = Schedule(date=datetime(2018, 10, 13), user=new_user, room=new_room) db.session.add(second_schedule) db.session.commit() user = User.query.one() room = Room.query.one() self.assertEqual(len(user.schedules), 2) self.assertEqual(len(room.schedules), 2) self.assertEqual(user.schedules[0].date, datetime(2018, 10, 12).date()) self.assertEqual(user.schedules[1].date, datetime(2018, 10, 13).date()) self.assertEqual(room.schedules[0].date, datetime(2018, 10, 12).date()) self.assertEqual(room.schedules[1].date, datetime(2018, 10, 13).date())
def test_create_room(): room = Room(1, False, True, 0) assert room.room_id == 1 assert room.is_on == False assert room.is_veg_room == True assert room.brightness == 0
def mock_room(): return Room.from_json({ "room_id": 1, "is_on": False, "is_veg_room": True, "brightness": 0 })
def return_all_entities_listener(message) -> None: print("Received message in entities_listener:", message) assert "rooms" in message assert "racks" in message assert "shelves" in message assert "grows" in message assert "recipes" in message assert "recipe_phases" in message found_rooms = [Room.from_json(r) for r in message["rooms"]] found_racks = [Rack.from_json(r) for r in message["racks"]] found_shelves = [Shelf.from_json(s) for s in message["shelves"]] found_grows = [Grow.from_json(g) for g in message["grows"]] found_recipes = [Recipe.from_json(r) for r in message["recipes"]] found_recipe_phases = [ RecipePhase.from_json(rp) for rp in message["recipe_phases"] ] assert collections.Counter(found_rooms) == collections.Counter(rooms) assert collections.Counter(found_racks) == collections.Counter(racks) assert collections.Counter(found_shelves) == collections.Counter( shelves) assert collections.Counter(found_grows) == collections.Counter(grows) assert collections.Counter(found_recipes) == collections.Counter( recipes) assert collections.Counter(found_recipe_phases) == collections.Counter( recipe_phases) flag.append(True)
def test_print_existing_allocations_to_specific_file(self): self.clear_stores() office = Office("ND88") Dojo.add_room(office) fellow = Fellow("Xne88", "Ndoile88", "086800000", "y") fellow.register() office.allocate_to(fellow) allocations_ = Room.all_allocations() expected_output = Room.members(allocations_, room_tag=True) file_name = office.name + "-Allocations" Room.to_file(expected_output, file_name) path = "output/" f = open(path + file_name + ".txt", "r") output = f.read() f.close() self.assertEqual(expected_output, output)
def return_all_entities_listener(message) -> None: message_dict = json.loads(message) print("Received message in entities_listener:", message_dict) assert "rooms" in message_dict assert "racks" in message_dict assert "shelves" in message_dict assert "grows" in message_dict assert "grow_phases" in message_dict assert "recipes" in message_dict assert "recipe_phases" in message_dict found_rooms = [Room.from_json(r) for r in message_dict["rooms"]] found_racks = [Rack.from_json(r) for r in message_dict["racks"]] found_shelves = [Shelf.from_json(s) for s in message_dict["shelves"]] found_grows = [Grow.from_json(g) for g in message_dict["grows"]] found_grow_phases = [ GrowPhase.from_json(g) for g in message_dict["grow_phases"] ] found_recipes = [Recipe.from_json(r) for r in message_dict["recipes"]] found_recipe_phases = [ RecipePhase.from_json(rp) for rp in message_dict["recipe_phases"] ] assert collections.Counter(found_rooms) == collections.Counter(rooms) assert collections.Counter(found_racks) == collections.Counter(racks) assert collections.Counter(found_shelves) == collections.Counter( shelves ) assert len(found_grows) > 0 x = len(found_grows) assert ( found_grows[x - 1].start_datetime.strftime("%Y-%m-%d %H:%M:%S") == start ) assert ( found_grows[x - 1].estimated_end_datetime.strftime( "%Y-%m-%d %H:%M:%S" ) == end ) i = len(found_grow_phases) assert ( found_grow_phases[i - 1].phase_start_datetime.strftime( "%Y-%m-%d %H:%M:%S" ) == start ) assert ( found_grow_phases[i - 1].phase_end_datetime.strftime( "%Y-%m-%d %H:%M:%S" ) == end ) j = len(found_recipes) assert found_recipe_phases[j - 1].power_level == p_level assert found_recipe_phases[j - 1].red_level == r_level assert found_recipe_phases[j - 1].blue_level == b_level flag.append(True) grow.append(found_grows[0].grow_id)
def create_default_room(db, group): room = Room(name='Default', role=Room.SIMPLE) db.session.add(room) group.rooms.append(room) return room
def insert_room(): room = Room(name="") session.add(room) session.commit() room_id = session.query(Room.id).first() return room_id
def init_room(num, uid, user_name, good_word=None, bad_word=None, white=False): delete_room() if num < 4: send_message(uid, '不能少于4个人') return elif num > 13: send_message(uid, '不能多于13个人') return exist_room = Room.query.filter_by(owner_id=uid).all() if len(exist_room) != 0: for room in exist_room: db.session.delete(room) db.session.commit() if good_word is None and bad_word is None: words_path = os.path.join(os.path.dirname(__file__), '..', '..', 'words.txt') with open(words_path, 'r') as f: lines = f.readlines() line_sample = sample(lines, 1)[0].strip() good_word, bad_word = line_sample.split(' ') records = Room.query.all() exist_room_ids = [record.room_id for record in records] rows = int(os.getenv('ROWS')) all_room_ids = range(rows) ok_room_ids = list(set(all_room_ids) - set(exist_room_ids)) room_id = choice(ok_room_ids) bad_num = 0 if num < 7: bad_num = 1 elif num >= 7: bad_num = 2 if white: bad_number = sample(range(num), bad_num + 1) white_number = bad_number[-1] + 1 bad_number = bad_number[:-1] else: white_number = -1 bad_number = sample(range(num), bad_num) bad_number = [str(n + 1) for n in bad_number] str_bad_number = ','.join(bad_number) new_room = Room(room_id, num, good_word, bad_word, str_bad_number, user_name, uid, white_number) db.session.add(new_room) db.session.commit() message = wrap_new_message(room_id, bad_num, num, bad_word, good_word, bad_number, white_number) send_message(uid, message)
def assign_partner(user_id): user = User.query.get(user_id) room = Room('name') db.session.add(room) db.session.commit() current_user.room_id = room.id user.room_id = room.id db.session.commit() return redirect(url_for('main.index'))
def test_print_populated_room(self): self.clear_stores() office = Office("NDO") Dojo.add_room(office) fellow = Fellow("Xone", "Ndobile", "0856443334", "y") fellow.register() office.allocate_to(fellow) allocations = office.allocations() output = Room.members(allocations) self.assertEqual(output, " 0856443334, NDOBILE, XONE, FELLOW\n")
def read_all_rooms(conn) -> List[Room]: sql = "SELECT room_id, is_on, is_veg_room, brightness FROM rooms" with conn.cursor() as cursor: cursor.execute(sql) all_rooms = cursor.fetchall() rooms = [ Room(rid, bool(is_on), bool(is_veg), brightness) for (rid, is_on, is_veg, brightness) in all_rooms ] cursor.close() return rooms
def print_unallocated(out, file_name): try: output = Room.all_unallocated_persons() if len(output) > 0: if out is True: if file_name is not None: Room.to_file(output, file_name) print_pretty( " A list of unallocated persons can be found in the output directory under the file %s.txt" % file_name) else: Room.to_file(output) print_pretty( " A list of unallocated persons can be found in the output directory under the file File.txt" ) else: print_pretty(output) else: print_pretty(" There are no unallocated persons to show") except Exception as e: print_pretty(str(e))
def message_sent(message): logging.debug("message sent:", message) entities_processed = [] print("message:", message) if "room" in message: # a room is contained in this update entities_processed.append("room") room_json = message["room"] room = Room.from_json(room_json) app_config.logger.debug(room) print("Saw room in message") app_config.db.write_room(room) if "rack" in message: # a rack is contained in this update entities_processed.append("rack") rack_json = message["rack"] rack = Rack.from_json(rack_json) app_config.logger.debug(rack) print("Saw rack in message") app_config.db.write_rack(rack) if "recipe" in message: # a recipe is contained in this update entities_processed.append("recipe") recipe_json = message["recipe"] recipe = Recipe.from_json(recipe_json) app_config.logger.debug(recipe) print("Saw recipe in message") app_config.db.write_recipe(recipe) if "shelf" in message: # a shelf is contained in this update entities_processed.append("shelf") shelf_json = message["shelf"] shelf = Shelf.from_json(shelf_json) app_config.logger.debug(shelf) print("Saw shelf in message") app_config.db.write_shelf(shelf) if "plant" in message: # a plant is contained in this update entities_processed.append("plant") plant_json = message["plant"] plant = Plant.from_json(plant_json) app_config.logger.debug(plant) print("Saw plant in message") app_config.db.write_plant(plant) send_message_to_namespace_if_specified( socketio, message, "message_received", {"processed": entities_processed})
def load_state(cls, file_name="default"): Room.clear() path = "db/" file_ = file_name + ".db" engine = create_engine("sqlite:///" + path + file_, echo=False) Session = sessionmaker(bind=engine) session = Session() allocation_info = session.query(Allocation).all() for allocation_ in allocation_info: allocation = [ allocation_.roomname, allocation_.roomtype, allocation_.phonenumber ] allocation_str = "%s-%s-%s" % (allocation_.roomname, allocation_.roomtype, allocation_.phonenumber) allocation_name_type_str = "%s-%s" % (allocation_.roomname, allocation_.roomtype) allocations.append(allocation) allocations_name_type.append(allocation_name_type_str) allocations_set.add(allocation_str) session.close()