示例#1
0
def processEdit(id, eventName, discountPercent, discountAmount, contact,
                rooms):
    """Save the form data into a booking"""
    b = Booking.select().where(Booking.id == id).get()
    food = {}
    for field in request.form:
        if field.startswith('dish_'):
            food[int(field.replace('dish_', ''))] = int(request.form[field])
    b.eventName = eventName
    b.discountPercent = discountPercent
    b.discountAmount = discountAmount
    b.contact_id = contact
    rooms = Room.select().where(Room.id << rooms).execute()
    if Room.areRoomsFree(rooms, b.startTime, b.endTime, id):
        BookingRoom.delete().where(BookingRoom.booking == b).execute()
        for room in rooms:
            br = BookingRoom(booking=b, room=room)
            br.save()
        Order.delete().where(Order.booking == b).execute()
        for f in food:
            if food[f] > 0:
                Order(dish=Dish.get(Dish.id == int(f)),
                      booking=b,
                      quantity=food[f]).save()
        b.calculateTotal()
        b.save()
    else:
        flash(
            'A room that you selected is no longer available.  Please select a new room.',
            'error')
        return redirect(request.referrer)
    flash('Booking Updated', 'success')
    return redirect(url_for('bookings.index'))
示例#2
0
文件: database.py 项目: roesel/book
def stats_occupation(when):
    floor_occupation = {}
    floor_occupation_rel = {}
    building_occupation = {}
    building_occupation_rel = {}
    rows = Room.select(Room.building).group_by(Room.building)
    buildings_of_the_campus = [row.building for row in rows]
    for building in buildings_of_the_campus:
        floor_occupation[building] = {}
        floor_occupation_rel[building] = {}
        rooms_of_the_building = Room.select().where(Room.building == building)
        rows = Room.select(
            Room.floor).where(Room.building == building).group_by(Room.floor)
        floors_of_the_building = [row.floor for row in rows]
        for floor in floors_of_the_building:
            floor_occupation[building][floor] = 0
            floor_occupation_rel[building][floor] = 0
    day_occupation = Booking.select().where(Booking.when == when,
                                            Booking.status == 'approved')
    for booking in day_occupation:
        room_id = booking.room
        room = Room.get(Room.id == room_id)
        floor_occupation[room.building][room.floor] += 1
        floor_occupation_rel[room.building][room.floor] = floor_occupation[
            room.building][room.floor] / POP_LIMIT_FLOOR
    for building in floor_occupation:
        building_occupation[building] = sum(
            floor_occupation[building].values())
        building_occupation_rel[
            building] = building_occupation[building] / POP_LIMIT_BUILDING
    return building_occupation, floor_occupation, building_occupation_rel, floor_occupation_rel
示例#3
0
def chat():
	form = RoomForm()
	if form.validate_on_submit():
		db.session.add(g.user)
		
		#create a list of all existing rooms with this roomname
		room = Room.query.filter_by(roomname=form.roomname.data).first()

		# the room doesn't exist yet, so make it and set its name
		# and password to the given data
		if room == None:
			room = Room(roomname=form.roomname.data,
						password=form.roomkey.data,
						created_time=datetime.utcnow())

			#delete room in 25 min
			remove_room.apply_async(args=[room.roomname], countdown=app.config['ROOM_TTL'])	

			db.session.add(room)
		#the room does exist
		else:
			#if the 'attempted' password isn't the same as the room's password
			if room.password != form.roomkey.data:
				flash('That password\'s not right.', 'danger')
				return redirect(url_for('chat'))
		
		room.approve_user(g.user)
		db.session.commit()
		return redirect(url_for('room', roomname=form.roomname.data))
	return render_template('chat.html',
							title='Chat',
							form=form)
示例#4
0
文件: rooms.py 项目: Trcx528/CDCC
def edit(id):
    """Display a room details"""
    return render_template(
        'admin/room/edit.html',
        room=Room.select().where(Room.id == id).get(),
        rooms=Room.select().where(Room.id != id,
                                  Room.isDeleted == False).order_by(Room.name))
示例#5
0
文件: rooms.py 项目: Trcx528/CDCC
def delete(id):
    """soft delete a room"""
    room = Room.select().where(Room.id == id).get()
    rooms = room.adjacentRooms()
    for r in rooms:
        r.removeAdjacentRoom(id)
    Room.update(isDeleted=True).where(Room.id == id).execute()
    flash("Room %s deleted" % room.name, "success")
    return redirect(url_for('rooms.index'))
示例#6
0
def deploy():
    '''Run deployment tasks'''
    # migrate database to latest revision
    from flask_migrate import upgrade
    upgrade()

    verbose = False
    if app.debug:
        verbose_mode = input('Run in verbose mode? [yes/No]: ')
        if verbose_mode.lower() in ['y', 'yes']:
            verbose = True

    # insert data
    data = 'common'

    from app.models import Permission
    Permission.insert_entries(data=data, verbose=verbose)

    from app.models import Role
    Role.insert_entries(data=data, verbose=verbose)

    from app.models import Room
    Room.insert_entries(data=data, verbose=verbose)

    from app.models import DeviceType
    DeviceType.insert_entries(data=data, verbose=verbose)

    from app.models import LessonType
    LessonType.insert_entries(data=data, verbose=verbose)

    from app.models import Lesson
    Lesson.insert_entries(data=data, verbose=verbose)

    from app.models import Video
    Video.insert_entries(data=data, verbose=verbose)

    data = input(
        'Enter data identifier (e.g.: 20180805 or press the enter/return key for initial data): '
    )
    if data == '':
        data = 'initial'
    datadir = os.path.join(app.config['DATA_DIR'], data)
    if os.path.exists(datadir):
        from app.models import User
        User.insert_entries(data=data, verbose=verbose)

        from app.models import Punch
        Punch.insert_entries(data=data, verbose=verbose)

        from app.models import Device
        Device.insert_entries(data=data, verbose=verbose)

        from app.models import DeviceLessonType
        DeviceLessonType.insert_entries(data=data, verbose=verbose)

        from app.models import UserLog
        UserLog.insert_entries(data=data, verbose=verbose)
示例#7
0
 def room_init(row):
     room = Room()
     num = Room.query.filter_by(name=row['Nom']).count()
     if num > 0:
         Room.query.delete()
     room.name = row['Nom']
     room.max_number = row['Espace total']
     room.description = row['Description']
     return room
示例#8
0
def seed():
    # os.remove('.db')
    # shutil.rmtree('migrations')
    with app.app_context():
        init()
        migrate()
        upgrade()

        Room.add(name="test", password="")
示例#9
0
文件: views.py 项目: 2675694536/flask
def add_stu(request):
    room = Room()
    room.roomname = 'python班'
    room.save()
    stu = Student()
    stu.name = '张飞%d' % random.randrange(10)
    stu.sex = '男'
    stu.roomid = room
    stu.save()
    return HttpResponse('添加成功')
示例#10
0
    def post(self, request):
        userprofiles_list = UserProfile.objects.filter(id=-1)

        users = self.request.POST.getlist('user')

        if len(users) == 1:
            room_name = self.request.user.username + '+' + users[0]
        elif self.request.POST.get('room_name'):
            room_name = self.request.POST.get('room_name')
        else:
            room_name = 'room'

        room = Room(room_name=room_name)
        room.save()

        room.room_uid = get_uid(self, room)
        room.save()

        for u in users:
            userprofiles_list |= UserProfile.objects.filter(user__username=u)
            room.userprofiles.add(
                UserProfile.objects.filter(user__username=u).first())
            room.save()
        userprofiles_list |= UserProfile.objects.filter(
            user__username=self.request.user.username)
        ser = UserProfileSerializer(userprofiles_list, many=True)

        response = {'users': ser.data, 'room_name': room_name}

        return Response(response)
示例#11
0
 def test_room_allocation(self):
     r1 = Room(room_name="Demo Room 1")
     r2 = Room(room_name="Demo Room 2")
     s1 = Student(first_name="billy")
     s2 = Student(first_name="bella")
     s3 = Student(first_name="mikes")
     s1.room = r1
     s2.room = r1
     s3.room = r2
     self.assertTrue(s1 in r1.students)
     self.assertTrue(s2 in r1.students)
     self.assertTrue(s3 in r2.students)
示例#12
0
def init_test():
    db.drop_all()
    db.create_all()
    Role.insert_roles()
    Room.insert_rooms()
    print("wwwwwwwwwwwwwwwwwww")
    users = {"16300240019": "严佳雯", "15307130371": "王佳羽", "16307130026": "张天翔"}
    for id in users:
        user = User(urpid=id)
        user.username = users[id]
        user.password = id
        db.session.add(user)
    db.session.commit()
示例#13
0
def create():

    token = request.json.get('token')
    if token is None:
        abort(
            401,
            'Authentication token is absent! You should request token by POST {post_token_url}'
            .format(post_token_url=url_for('user.post_token')))

    requesting_user = User.verify_api_auth_token(token)

    hosted_room = Room.query.filter_by(host=requesting_user,
                                       closed=None).first()
    if hosted_room:
        return jsonify({
            'errors': [{
                'message':
                'User {username} already has opened room "{room_name}"!'.
                format(username=requesting_user.username,
                       room_name=hosted_room.room_name)
            }]
        }), 403

    connected_room = requesting_user.connected_rooms
    if connected_room.count() > 0:
        return jsonify({
            'errors': [{
                'message':
                'User {username} already is connected to other room!'.format(
                    username=requesting_user.username)
            }]
        }), 403

    room_name = request.json.get('roomName')
    new_room = Room(room_name=room_name,
                    host=requesting_user,
                    created=datetime.utcnow())
    db.session.add(new_room)
    new_room.connect(requesting_user)
    db.session.commit()

    return jsonify({
        'roomId': new_room.id,
        'roomName': new_room.room_name,
        'host': new_room.host.username,
        'created': new_room.created,
        'closed': new_room.closed,
        'connectedUsers': new_room.connected_users.count(),
        'status': 'open' if new_room.closed is None else 'closed',
        'connect': url_for('room.connect', room_id=new_room.id)
    }), 201
示例#14
0
def index(request):
    ImageFormSet = modelformset_factory(RoomImage,
                                        form=UploadImageForm,
                                        extra=6)

    if request.method == "POST":
        formset = ImageFormSet(request.POST,
                               request.FILES,
                               queryset=RoomImage.objects.none())

        if formset.is_valid():
            room = Room(area=request.POST['area'],
                        size=request.POST['size'],
                        floor=request.POST['floor'],
                        security_deposit=request.POST['security_deposit'],
                        month_price=request.POST['month_price'],
                        management_cost=request.POST['management_cost'],
                        air_conditioner=request.POST['air_conditioner'],
                        washer=request.POST['washer'],
                        bed=request.POST['bed'],
                        fire_type=request.POST['fire_type'],
                        desk=request.POST['desk'],
                        term=request.POST['term'],
                        veranda=request.POST['veranda'],
                        kitchen=request.POST['kitchen'],
                        tv=request.POST['tv'],
                        microwave=request.POST['microwave'],
                        two_room=request.POST['two_room'],
                        hash1=request.POST['hash1'],
                        hash2=request.POST['hash2'],
                        hash3=request.POST['hash3'],
                        detail=request.POST['detail'],
                        elevator=request.POST['elevator'],
                        wardrobe=request.POST['wardrobe'])
            room.save()

            for form in formset.cleaned_data:
                if form != {}:
                    image = form['image']
                    photo = RoomImage(room=room, image=image)
                    photo.save()
    else:
        formset = ImageFormSet(queryset=RoomImage.objects.none())

    rooms = Room.objects.all().order_by('-id')
    serializer = RoomSerializer(rooms, many=True)
    c = {'formset': formset, 'rooms': serializer.data}
    c.update(csrf(request))

    return render_to_response('index.html', c)
示例#15
0
def startRoom(request):
    if not request.user.is_staff:
        return HttpResponseForbidden()

    try:
        roomid = request.GET['roomid']
        timer = request.GET['time']
    except:
        return HttpResponseBadRequest()

    cmd = f'python3 plug-ins/goldennum.py "{secret_key.secret_key}" {roomid} {timer}'
    cmd_run = f'nohup {cmd} > tmp/logs/{roomid}.out 2>&1'

    if sys.platform == "win32":
        cmd_run = f'start /b {cmd_run}'
    else:
        cmd_run = f'{cmd_run} &'

    rooms = Room.objects.filter(roomid=roomid)
    if not rooms:
        newRoom = Room()
        newRoom.status = "on"
        newRoom.roomid = roomid
        newRoom.time = timer
        newRoom.cmd = cmd.replace('"', '')
        newRoom.lastTime = str(int(time.time()))
        newRoom.history = json.dumps({
            "goldenNums": [],
            "userActs": {}
        })
        newRoom.save()
        os.makedirs("./tmp/logs", exist_ok=True)
        os.system(cmd_run)
        return HttpResponse("Room started new")
    else:
        room = rooms[0]
        # flag = os.system('ps axu | grep "' + room.cmd +'" | grep -v "grep" | wc -l')
        # print(json.dumps(flag))
        if room.status != "on":
            room.status = "on"
            room.time = timer
            room.cmd = cmd.replace('"', '')
            room.lastTime = str(int(time.time()))
            room.save()
            os.makedirs("./tmp/logs", exist_ok=True)
            os.system(cmd_run)
            return HttpResponse("Room restarted")
        else:
            return HttpResponse("Room have started")
示例#16
0
def add_new_room(data):
    uuid = data.get('uuid')
    name = data.get('name')
    texture_id = data.get('texture_id')
    floor_id = data.get('floor_id')
    user_id = get_user_id(uuid=uuid)
    if user_id:
        room = Room(user_id=user_id, texture_id=texture_id, name=name, floor_id=floor_id)
        try:
            room.save()
        except Exception as err:
            return generate_room_name_already_exist_response(name)
        return generate_room_created_success_response(room)
    else:
        return generate_user_not_login_response()
示例#17
0
def new_group():
    form = NewRoomForm()
    if form.validate_on_submit():
        #Post
        roomname = form.roomname.data
        room = Room()
        room.roomname = roomname
        room.administrator = current_user.id
        room.users.append(current_user)
        db.session.add(room)
        db.session.commit()
        flash("Grupo {} creado".format(roomname))
        return redirect("/index")
    else:
        return render_template("new_room.html", title="Nuevo Grupo", form=form)
示例#18
0
def addroom(name, password, description):
    if name is "":
        print("Error: Name is empty")
        return

    if password is "":
        print("Warning: Password is empty")

    with app.app_context():
        if Room.exists(name):
            print("Error: Room {} already exists".format(name))
            return

        Room.add(name=name, password=password, description=description)
        print("Success: Room {} added".format(name))
示例#19
0
def get_accessible_rooms(user_id):
    if user_id == 2:
        rooms = Room.select().where(
            Room.name << ['BM4118', 'BM5117', 'BM4113'])
    elif user_id == 3:
        rooms = Room.select().where(
            Room.name << ['BM4118', 'BM4114', 'SV1115', 'SV2116'])
    elif user_id == 4:
        rooms = Room.select().where(
            Room.name << ['CH1117', 'CH3117', 'CH3118', 'BM4113', 'SV2116'])
    else:
        rooms = Room.select()

    room_list = [model_to_dict(c) for c in rooms]
    return room_list
示例#20
0
def initdb():
    db.drop_all()
    db.create_all()
    
    timeslots = extract_timeslots()
    rooms = extract_rooms()
    sigles = extract_sigles()
    
    # auto data loading from different datasources
    Timeslot.insert_timeslots(timeslots)
    Weekday.insert_days()
    Role.insert_roles()
    User.insert_admin()
    User.insert_teachers(load_teachers())
    Room.insert_rooms(rooms)
示例#21
0
def check_bookings_count(when, room_id):
    room_count = Booking.select().join(Room).where(
        (Booking.when == when) & 
        (Room.id == room_id)
    ).count()
    room_check = False
    if room_count < POP_LIMIT_ROOM:
        room_check = True

    room = Room.get(Room.id == room_id)
    floor_count = Booking.select().join(Room).where(
        (Booking.when == when) & 
        (Room.floor == room.floor) & 
        (Room.building  == room.building)
    ).count()
    floor_check = False
    if floor_count < POP_LIMIT_FLOOR:
        floor_check = True 

    building_count = Booking.select().join(Room).where( 
        (Booking.when == when) & 
        (Room.building  == room.building) 
    ).count()
    building_check = False
    if building_count < POP_LIMIT_BUILDING:
        building_check = True

    count_check = room_check*floor_check*building_check
    return count_check, [room_check, floor_check, building_check]
示例#22
0
def change_room(data: dict) -> dict:
    ans = {
        'roomChanged': False,
    }
    admin: User = User.login(data)
    room: Room = Room.get_room({'roomId': data.get('room', {}).get('id')})
    if admin.id == room.admin_id:
        room.name = data.get('room', {}).get('name') or room.room_name
        room.admin_id = data.get('room').get('adminId') or room.admin_id

        if data.get('room', {}).get('users') is not None:
            room.users = [
                user for user in User.query.filter(
                    User.id.in_([user['id']
                                 for user in data['room']['users']])).all()
            ]
        room.msgs = [msg for msg in room.msgs if msg.user not in room.users]
        if data.get('room', {}).get('alarms') is not None:
            room.alarms.clear()
            for alarm in data['room']['alarms']:
                alarm = Alarm.query.filter_by(id=alarm['id']).first() or \
                        Alarm(
                            alarm_name=alarm['name'],
                            counter=0,
                            time=time(hour=alarm['time'][0],
                                      minute=alarm['time'][1], ),
                            days=''.join(map(str, alarm['days'])),
                        )
                alarm.counter = len(room.users)
                room.alarms.append(alarm)
        db.session.commit()
        ans['roomChanged'] = True
    return ans
示例#23
0
def search_rooms(data: dict) -> dict:
    ans = {
        'rooms': [],
    }
    User.login(data)
    ans['rooms'] = Room.get_rooms(data)
    return ans
示例#24
0
def browse():
    """
    Lists all available rooms one can join to be a member of.
    User should be able to search for a specific room or create their own.
    """
    form = RoomForm()
    members = []
    rooms = Room.query.limit(current_app.config['ROOMS_PER_PAGE']).all()
    joined_rooms = getUserRooms(current_user.get_id())

    if form.validate_on_submit():
        user = current_user.get_id()
        room = Room(type=int(form.type.data),
                    name=form.name.data,
                    description=form.description.data,
                    owner_id=user)
        db.session.add(room)
        db.session.commit()
        room.members.append(User.query.get(user))
        db.session.execute(room_users.update().where(
            (room_users.c.user_id == user)
            & (room_users.c.room_id == room.id)).values({'role': '1'}))
        db.session.commit()
        flash('Room created successfully!')
        return redirect(url_for('main.browse'))

    for i in range(1, 21):
        members.append(getAllMembers(i))

    return render_template('browse.html',
                           rooms=rooms,
                           joined_rooms=joined_rooms,
                           members=members,
                           form=form)
示例#25
0
文件: database.py 项目: roesel/book
def check_bookings_count(when, room_id, status='approved'):
    assert status in ['approved', 'pending', 'denied']
    room_count = Booking.select().join(Room).where((Booking.when == when) & (
        Room.id == room_id) & (Booking.status == status)).count()
    room_check = False
    if room_count < POP_LIMIT_ROOM:
        room_check = True

    room = Room.get(Room.id == room_id)
    floor_count = Booking.select().join(
        Room).where((Booking.when == when) & (Room.floor == room.floor)
                    & (Room.building == room.building)
                    & (Booking.status == status)).count()
    floor_check = False
    if floor_count < POP_LIMIT_FLOOR:
        floor_check = True

    building_count = Booking.select().join(
        Room).where((Booking.when == when) & (Room.building == room.building)
                    & (Booking.status == status)).count()
    building_check = False
    if building_count < POP_LIMIT_BUILDING:
        building_check = True

    count_check = room_check * floor_check * building_check
    return bool(count_check), [room_check, floor_check, building_check]
示例#26
0
文件: rooms.py 项目: Trcx528/CDCC
def restore(id):
    """Restore a soft deleted room"""
    room = Room.select().where(Room.id == id).get()
    room.isDeleted = False
    room.save()
    flash('Room %s restored' % room.name, "success")
    return redirect(url_for('rooms.edit', id=id))
示例#27
0
def get_room(data: dict) -> dict:
    ans = {
        'room': {},
    }
    user: User = User.login(data)
    room: Room = Room.get_room(data)
    ans['room']['id'] = room.id
    ans['room']['name'] = room.room_name
    ans['room']['adminId'] = room.admin_id
    ans['room']['users'] = [{
        'id': user.id,
        'name': user.user_name
    } for user in room.users]
    ans['room']['unapprovedUsers'] = []
    if user.id == room.admin_id:
        for msg in room.msgs:
            user: User = User.query.get(msg.user_id)
            ans['room']['unapprovedUsers'].append({
                'id': user.id,
                'name': user.user_name,
                'msg': msg.body
            })
    ans['room']['alarms'] = [{
        'id': alarm.id,
        'name': alarm.alarm_name,
        'time': [alarm.time.hour, alarm.time.minute],
        'days': alarm.days,
        'counter': alarm.counter,
    } for alarm in room.alarms]
    return ans
示例#28
0
def send_message(recipient):
    user = User.query.filter_by(username=recipient).first_or_404()
    form = MessageForm()

    if form.validate_on_submit():
        if not user.get_room(current_user):
            room = Room(author=current_user, recipient=user)
            db.session.add(room)
            db.session.commit()

        session['name'] = current_user.username
        session['room'] = current_user.get_room(user).id

        msg = Message(author=current_user,
                      recipient=user,
                      body=form.message.data)
        user.add_notification('unread_message_count', user.new_messages())
        db.session.add(msg)
        db.session.commit()
        flash(_('Your message has been sent.'))
        return redirect(url_for('main.dialog', recipient=recipient))

    return render_template('send_message.html',
                           title=_('Send Message'),
                           form=form,
                           recipient=recipient)
示例#29
0
def index():
    create_form = CreateRoomForm()
    join_form = JoinRoomForm()
    if create_form.validate_on_submit():
        room = Room(name=create_form.room_name.data)
        room.generate_code()
        db.session.add(room)
        db.session.commit()
        flash(f'Room {room.name} created.')
        return redirect(url_for('lobby', room_code=room.code))
    elif join_form.validate_on_submit():
        return redirect(url_for('join', room_code=join_form.room_code.data))
    return render_template('index.html',
                           title='Questionable',
                           create_form=create_form,
                           join_form=join_form)
示例#30
0
def index_student(room_name, role):
    if not Room.exists(room_name):
        return redirect(url_for("app.index_room"))
    elif role not in ["student", "assistant"]:
        return redirect(url_for("app.index_role"))

    return render_template("{}.html".format(role))
示例#31
0
def index(request):
    ImageFormSet = modelformset_factory(RoomImage, form=UploadImageForm, extra=6)
    
    if request.method == "POST":
        formset = ImageFormSet(request.POST, request.FILES, queryset=RoomImage.objects.none())

        if formset.is_valid():
            room = Room (area = request.POST['area'],
                         size = request.POST['size'],
                        floor = request.POST['floor'],
                        security_deposit = request.POST['security_deposit'],
                        month_price = request.POST['month_price'],
                        management_cost = request.POST['management_cost'],
                        air_conditioner = request.POST['air_conditioner'],
                        washer = request.POST['washer'],
                        bed = request.POST['bed'],
                        fire_type = request.POST['fire_type'],
                        desk = request.POST['desk'],
                        term = request.POST['term'],
                        veranda = request.POST['veranda'],
                        kitchen = request.POST['kitchen'],
                        tv = request.POST['tv'],
                        microwave = request.POST['microwave'],
                        two_room = request.POST['two_room'],
                        hash1 = request.POST['hash1'],
                        hash2 = request.POST['hash2'],
                        hash3 = request.POST['hash3'],
                        detail = request.POST['detail'],
                        elevator = request.POST['elevator'],
                        wardrobe = request.POST['wardrobe']
                        )
            room.save()
            
            for form in formset.cleaned_data:
                if form != {}:
                    image = form['image']
                    photo = RoomImage(room=room, image=image)
                    photo.save()
    else:
        formset = ImageFormSet(queryset=RoomImage.objects.none())

    rooms = Room.objects.all().order_by('-id')
    serializer = RoomSerializer(rooms, many=True)
    c = {'formset': formset, 'rooms': serializer.data}
    c.update(csrf(request))
        
    return render_to_response('index.html', c)
示例#32
0
文件: index.py 项目: lmorchard/CREM
def rooms():
    if request.method == 'GET':
        roomlist = Room.query.all()
        return jsonify(rooms=[i.ui_rooms for i in roomlist])
    else:
        rooms = request.json
        for room in rooms:
            if 'id' not in room:
                db_room = Room()
            else:
                db_room = Room.query.get(room['id'])
            db_room.room_name = room['name']
            db_room.room_sq_ft = room['sq_ft']
            db_room.room_capacity = room['capacity']
            db_room.room_group_id = room['group_id']
            db.session.add(db_room)

        # Update the database.
        try:
            db.session.commit()
        except SQLAlchemyError, e:
            return ('Error updating the room records: %s' % e, 500)
        return ('Room configs successfully updated.', 200)
    def __json__(group=None):
        _json = {
            'id': fields.Integer,
            'location': fields.String,
            'uri': fields.Url('apartment')
        }

        if group == 'flat':
            return _json

        from app.models import Room
        _json['rooms'] = fields.List(fields.Nested(Room.__json__('flat')))

        return _json
    def __json__(group=None):
        _json = {
            'id': fields.Integer,
            'firstName': fields.String,
            'lastName': fields.String,
            'email': fields.String,
            'telephoneNumber': fields.String,
            'uri': fields.Url('user')
        }

        if group == 'flat':
            return _json

        from app.models import Room
        _json['room'] = fields.Nested(Room.__json__('flat'))

        return _json
示例#35
0
    ('Charlevoix C', 756, 64, 'Charlevoix'),
    ('Portage Auditorium', 1439, 68, None),
    ('Windover', 1475, 40, None),
    ('TC Linguinis', 1930, 40, None),
    ('Baldwin Board Room', 431, 12, None),
    ('Board of Directors', 511, 15, None),
    ('Board of Governors', 391, 5, None),
    ('Board of Regents', 439, 15, None),
    ('Board of Trustees', 534, 40, None),
    ('Hamlin', 360, 25, None),
    ('Montcalm', 665, 50, None),
    ('Nicolet', 667, 50, None),
    ('Game Table A', 20, 10, 'Lobby'),
    ('Game Table B', 20, 10, 'Lobby'),
    ('Game Table C', 20, 10, 'Lobby'),
    ('Game Table D', 20, 10, 'Lobby'),
)

for room_info in room_infos:
    room = Room()
    room.room_name = room_info[0]
    room.room_sq_ft = room_info[1]
    room.room_capacity = room_info[2]
    if room_info[3]:
        room.room_group = db.session.query(RoomGroup).\
            filter(RoomGroup.room_group_name == room_info[3]).first()
    db.session.add(room)

# Commit the test data to the database.
db.session.commit()