Beispiel #1
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]
Beispiel #2
0
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]
Beispiel #3
0
def book_appointment(request):
    # check if the request is of type post and if the user is Donor
    if request.method == 'POST' and request.user.is_donor:

        # get the required format of the data
        appointment = request.POST['time']
        donor_id = request.POST['donor']
        hospital_id = request.POST['hospital']
        data = {
            'hospital': Hospital.objects.get(pk=hospital_id),
            'donor': Donor.objects.get(pk=donor_id),
            'appointment': request.POST.get("time")
        }
        # Try to create a new Booking with provided data
        try:
            booking = Booking()
            booking.new_appointment(data)
            return JsonResponse({
                'success':
                True,
                'message':
                "The appointment has been created successfully"
            })
        except:
            return JsonResponse({
                'success':
                False,
                'message':
                "You might have booking at this time at different hospital. Please, try different slot."
            })
    else:
        return redirect("app:app")
 def register_booking(self, model: RegisterBookingDto):
     booking = Booking()
     booking.flight_id = model.flight_id
     booking.passenger_id = model.passenger_id
     booking.booking_reference = model.booking_reference
     booking.price = model.price
     booking.seat_number = model.seat_number
     booking.flight_class = model.flight_class
     booking.save()
     return booking.id
Beispiel #5
0
def stats_occupation_around(when, room_id):
    same_building_occupation = {}
    same_building_occupation_rel = {}
    same_floor_occupation = {}
    same_floor_occupation_rel = {}
    room = Room.get(Room.id == room_id)
    same_building_occupation = Booking.select().join(Room).where(Booking.when == when, Room.building == room.building).count()
    same_building_occupation_rel = same_building_occupation/POP_LIMIT_BUILDING
    same_floor_occupation = Booking.select().join(Room).where(Booking.when == when, Room.building == room.building, Room.floor == room.floor).count()
    same_floor_occupation_rel = same_floor_occupation/POP_LIMIT_FLOOR
    return same_building_occupation, same_floor_occupation, same_building_occupation_rel, same_floor_occupation_rel
Beispiel #6
0
def create_booking():
    data = request.get_json() or {}
    if 'name' not in data or 'date' not in data or 'phone' not in data:
        return bad_request('name,date,phone are required')
    item = Booking()
    item.from_dict(data)
    db.session.add(item)
    db.session.commit()
    response = jsonify(item.to_dict())
    response.status_code = 201
    return response
Beispiel #7
0
def get_bookings_of_user(user_id):
    query = Booking.select().where(Booking.who == user_id)
    user_bookings = [model_to_dict(c) for c in query]
    for b in user_bookings:
        booking = Booking.get(Booking.id == b['id'])
        room = Room.get(Room.id == booking.room)
        same_floor_occupation = Booking.select().join(Room).where(
            Booking.when == booking.when, Room.building == room.building,
            Room.floor == room.floor).count()
        same_floor_occupation_rel = same_floor_occupation / POP_LIMIT_FLOOR * 100
        b['value_abs'] = same_floor_occupation
        b['value_rel'] = same_floor_occupation_rel
    return user_bookings
Beispiel #8
0
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
Beispiel #9
0
def render_booking(teacherid, day, time):
    form = BookingForm(teacher=teacherid, day=day, time=time)
    if request.method == 'POST':
        name = form.name.data
        phone = form.phone.data
        teacher = form.teacher.data
        day = form.day.data
        time = form.time.data
        db.session.add(
            Booking(created=datetime.now(),
                    remote_addr=request.remote_addr,
                    name=name,
                    phone=phone,
                    day=day,
                    time=time,
                    teacher_id=teacherid))
        db.session.commit()

        return render_template('booking_done.html',
                               name=name,
                               phone=phone,
                               teacher=teacher,
                               time=time,
                               day=days[day])

    return render_template(
        'booking.html',
        teacherid=teacherid,
        teacher=db.session.query(Teacher).get_or_404(teacherid),
        daydesc=days[day],
        day=day,
        time=time,
        form=form)
Beispiel #10
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'))
Beispiel #11
0
def index():
    contact_form = ContactForm(request.form)

    if request.method == "POST":
        if contact_form.validate_on_submit():
            name = contact_form.name.data
            email = contact_form.email.data
            arrival = contact_form.arrival_date.data
            departure = contact_form.departure_date.data

            user = Users(f_name=name,
                         m_name="middle",
                         l_name="last",
                         occupation="work",
                         email_address=email)

            duration = Booking(arrival_date=arrival, departure_date=departure)

            db.session.add(user)
            db.session.add(duration)
            db.session.commit()

            email_string = "Hello, " + name + \
                           " you have made a reservation for " + arrival + " to " + departure
            send_email(email_string, email)
            generate_pdf(name)

        return redirect(url_for('home.index'))

    return render_template('home/index.html', contact_form=contact_form)
Beispiel #12
0
    def db_access(first, middle, last, work, email, arrival, departure):
        """
        # Now setup an instance of the tables we are going 
        to interact with in order to store data
        # instantiate the variables just declared up there with 
        the relevant field in the table that the data will go to
        # giving it a path

        :param first:
        :param middle:
        :param last:
        :param work:
        :param email:
        :return:
        """
        email_string = "Hello, " + first + middle + last + \
            " you have made a reservation for " + arrival + " to " + departure
        clients = Users(f_name=first, m_name=middle, l_name=last,
                        occupation=work, email_address=email)

        duration = Booking(arrival_date=arrival, departure_date=departure)
        Functionality.send_email(email_string, email)

        # then add these new stored infor to the current user session
        # commit the changes
        sessionRep.add(clients)
        sessionRep.add(duration)
        sessionRep.commit()
Beispiel #13
0
def render_booking_done():
    teacher = Teacher.query.filter(
        Teacher.id == int(request.form.get("clientTeacher"))).first()
    schedule = Schedule.query.filter(
        Schedule.id == int(request.form.get("schedule"))).first()

    form = BookingForm()
    if form.validate_on_submit():
        name = form.clientName.data
        phone = form.clientPhone.data

        client = Client(name=name, phone=phone)

        db.session.add(client)
        # TODO
        # изменить ли структуру модели Client
        # так что бы хранил не id и ссылку
        # тогда можно без коммита
        db.session.commit()

        db.session.add(
            Booking(client=client.id, teacher=teacher.id,
                    schedule=schedule.id))
        db.session.commit()

        return render_template(
            "booking_done.html",
            name=name,
            phone=phone,
            day=ReadData.day_week.get(schedule.day_week, ""),
            time=schedule.time,
        )
    else:
        return url_for("booking.html")
Beispiel #14
0
def book(event_id):
    data = db.session.query(Event).join(
        Location, Location.id == Event.location_id).with_entities(
            Event.name, Event.capacity, Event.start, Event.end,
            Location.name.label('location_name'), Location.address,
            Event.img_name).filter(Event.id == event_id).first()

    ticket_amt = [(i, i) for i in range(1, data.capacity + 1)]
    form = BookingForm()
    form.amount.choices = ticket_amt

    if data is None:
        return render_template('error_event.html')
    if form.validate_on_submit():
        event = Event.query.get(event_id)
        event.capacity -= form.amount.data
        booking = Booking(user_id=current_user.id,
                          event_id=event_id,
                          quantity=form.amount.data,
                          book_time=datetime.utcnow(),
                          last_modified=datetime.utcnow())
        db.session.add(booking)
        db.session.commit()
        app.logger.info(
            'User ID {} has booked {} tickets (Booking ID {}) for Event ID {} at {}.'
            .format(booking.user_id, booking.quantity, booking.id,
                    booking.event_id, datetime.now()))
        flash(
            'Successfully purchased {} tickets for {}'.format(
                form.amount.data, data.name), "info")
        return redirect(url_for('main_panel.events'))
    return render_template('book.html',
                           event_id=event_id,
                           data=data,
                           form=form)
Beispiel #15
0
def get_pending_bookings_new(sort_by='booking_id'):
    query = Booking.select().where(Booking.status == 'pending')
    if sort_by == 'when':
        query_sorted = query.order_by(Booking.when)
    else:
        query_sorted = query
    pending_bookings = [model_to_dict(c) for c in query_sorted]
    for b in pending_bookings:
        booking = Booking.get(Booking.id == b['id'])
        same_room_pending = Booking.select().join(Room).where(
            Booking.when == booking.when, Booking.status == 'pending',
            Room.id == booking.room).count()
        if same_room_pending == 1:
            b['unique_request'] = True
        else:
            b['unique_request'] = False
    return pending_bookings
Beispiel #16
0
def get_pending_bookings(sort_by='booking_id'):
    query = Booking.select().where(Booking.status == 'pending')
    if sort_by == 'when':
        query_sorted = query.order_by(Booking.when)
    else:
        query_sorted = query
    pending_bookings = [model_to_dict(c) for c in query_sorted]
    return pending_bookings
Beispiel #17
0
def create_booking(bus_id):
    bus = Bus.query.get(bus_id)
    if not bus.booking_time_expired():
        create_booking_form = CreateBookingForm(data=request.form, bus=bus)
        if create_booking_form.validate_on_submit():
            # create booking
            grid_id = create_booking_form.grid_id.data
            pricing_id = create_booking_form.pricing_id.data
            passenger_name = create_booking_form.passenger_name.data
            passenger_telephone = create_booking_form.passenger_telephone.data
            pickup = create_booking_form.pickup.data
            pricing = Pricing.query.get(pricing_id)
            grid = Grid.query.get(grid_id)
            branch = bus.branch
            user = current_user
            if not user.is_authenticated:
                user = None

            fare = pricing.price
            stop = pricing.stop
            booking = Booking(passenger_name=passenger_name,
                              passenger_telephone=passenger_telephone,
                              seat_number=grid.number,
                              pickup=pickup,
                              fare=fare,
                              stop=stop,
                              grid_id=grid_id,
                              pricing_id=pricing_id,
                              paid=True,
                              branch=branch,
                              bus=bus,
                              created_by=user.id)

            db.session.add(booking)
            grid.booking = booking

            create_payment(booking)
            db.session.commit()
            bookings = bus.bookings
            booking_fields = Fields().booking_fields()
            bookings_json = json.loads(
                json.dumps(marshal_data(bookings, booking_fields)))
            res = json.dumps({
                "handle": "create_booking_passed",
                "data": {
                    "grid": grid.grid_dict(),
                    "bookings": bookings_json
                }
            })
            redis.publish(app.config.get("REDIS_CHAN"), res)
            flash(f'Booked Seat {grid.number}', 'success')
            return redirect(url_for('bus.get_bus', bus_id=bus.id))
        else:
            flash(f'Failed', 'danger')
            return render_template("bus/bus.html",
                                   bus=bus,
                                   create_booking_form=create_booking_form)
Beispiel #18
0
def get_floor_count(when, room_id, status='approved'):
    assert status in ['approved', 'pending', 'denied']
    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()

    return floor_count
Beispiel #19
0
def property(request, property_id):
    prop = Property.objects.get(id=property_id)
    bookings = Booking.objects.filter(property=property_id)
    checker = None
    guest = None

    if request.method == 'POST':
        guest = request.POST.get('guest')
        start_date = request.POST.get('start_date')
        start_date = datetime.strptime(start_date, '%Y-%m-%d').date()
        end_date = request.POST.get('end_date')
        end_date = datetime.strptime(end_date, '%Y-%m-%d').date()
        price = prop.price * (end_date - start_date).days * 1.08

        if len(bookings) > 0:
            for booking in bookings:
                if (booking.start_date <= start_date <= booking.end_date
                        or booking.start_date <= end_date <= booking.end_date
                    ) or (start_date <= booking.start_date
                          and end_date >= booking.end_date):
                    checker = False
                else:
                    checker = True
        else:
            checker = True

        if checker:
            p = Booking(property=prop,
                        start_date=start_date,
                        end_date=end_date,
                        price=price,
                        guest=guest)
            p.save()

    context = {
        'property': prop,
        'checker': checker,
        'guest': guest,
    }

    return render(request, 'app/property.html', context)
Beispiel #20
0
def saveBooking(request):
    name = request.POST.get('u_name')
    block_name = request.POST.get('bn')
    flat_type = request.POST.get('ft')
    flat_no = request.POST.get('fno')
    email = request.POST.get('u_email')
    purpose = request.POST.get('u_pur')
    date = request.POST.get('u_date')
    message = request.POST.get('u_mes')
    # print(name,block_name,flat_type,flat_no,email,purpose,date,message)
    bk = Booking(name=name,
                 flat_no=flat_no,
                 booking_purpose=purpose,
                 booking_date=date,
                 message=message,
                 email=email,
                 flat_type=flat_type,
                 block_name=block_name)
    bk.save()
    res = UserRegister.objects.get(flat_no=flat_no)
    return render(request, 'userhome.html', {'res': res})
Beispiel #21
0
def booking(teacher_id, day, hour):
    form = BookingForm()
    if form.validate_on_submit():
        bk = Booking(teacher_id=teacher_id, day=day, hour=hour)
        bk.student_name = form.contact_info.student_name.data
        bk.student_phone = form.contact_info.student_phone.data
        teacher = Teacher.query.get(teacher_id)
        teacher.set_hour_state(day, hour, False)  # теперь время - занято
        bk.save()
        return render_template("done.html",
                               title={
                                   "label": "Тема",
                                   "value": "Пробный урок"
                               },
                               time={
                                   "label": days[bk.day],
                                   "value": f"{bk.hour}:00"
                               },
                               name=bk.student_name,
                               phone=bk.student_phone)

    return render_template("booking.html",
                           teacher=Teacher.query.get(teacher_id),
                           time={
                               "day": day,
                               "hour": hour
                           },
                           days=days,
                           form=form)
Beispiel #22
0
def create_booking():
    form = BookingForm()
    form['csrf_token'].data = request.cookies['csrf_token']
    print()
    if form.validate_on_submit():
        booking = Booking(book_date=form.data['book_date'],
                          book_start_time=form.data['book_start_time'],
                          book_end_time=form.data['book_end_time'],
                          user_id=form.data['user_id'],
                          service_id=form.data['service_id'])
    db.session.add(booking)
    db.session.commit()
    newbooking = Booking.query.filter_by(id=booking.id).join(Aircraft).one()
    return to_booking(newbooking)
Beispiel #23
0
def index(start=None, end=None):
    """Lists all bookings"""
    if start is None:
        start = date.today()
    if end is None:
        end = date.today() + timedelta(days=30)
    b = Booking.select().where((Booking.startTime > start)
                               & (Booking.startTime < end)
                               & (Booking.isCanceled == False))
    bookings = prefetch(b, BookingRoom, Room)
    return render_template('bookings/index.html',
                           bookings=bookings,
                           start=start,
                           end=end)
Beispiel #24
0
def CreateBooking(request):
    print("Request is : ", request.json)
    if not request.json:
        return jsonify({'message': 'No input data provided '}), 400
    content = request.get_json()
    schema = BookingSchema()
    bookingData = schema.load(content)
    newAsset = bookingData.data
    a = Booking(**newAsset)
    db.session.add(a)
    try:
        db.session.commit()
        return jsonify({"sucess": True})
    except IntegrityError:
        return jsonify({"sucess": False})
        db.session.rollback()
Beispiel #25
0
def booking(teacher_id):
    teacher = db.session.query(Teacher).get_or_404(teacher_id)
    form = BookingForm()
    
    if form.validate_on_submit():
        weekday_ru = request.args.get('day')
        time = request.args.get('time')
        weekday_slug = next(
            (day_en for day_en, day_ru in RU_DAYS.items() if weekday_ru == day_ru),
            None
        )

        booking = Booking(
            username=form.name.data,
            phone=form.phone.data,
            weekday=weekday_ru,
            time=time
        )

        teacher_schedule = json.loads(teacher.schedule)
        teacher_schedule[weekday_slug][time] = False
        teacher.schedule = json.dumps(teacher_schedule)
        teacher.bookings.append(booking)
        db.session.add(teacher)
        db.session.add(booking)
        db.session.commit()

        context = {
            'name': booking.username,
            'phone': booking.phone,
            'lesson_day':  booking.weekday ,
            'lesson_time': booking.time,
            'subject': 'trial',
            'subject_description': 'Пробное занятие'
        }
        return redirect(url_for('sent', context=json.dumps(context)))

    context = {
        'teacher': teacher,
        'lesson_day': RU_DAYS[request.args.get('day')],
        'lesson_time': request.args.get('time')
    }

    return render_template('booking.html', form=form, **context)
Beispiel #26
0
def create_booking():
    if not request.json or not 'book_id' in request.json or not 'user_id' in request.json or not 'start_date' in request.json or not 'end_date' in request.json:
        abort(400)
    u = User.query.get(int(request.json['user_id']))
    b_id = request.json['book_id']
    if not u or not b_id:
        abort(500)
    book_id_api = requests.get("http://63.34.166.57:8080/book/id/{0}".format(b_id))
    if book_id_api.status_code != 200:
        abort(500)
    book_id = book_id_api.json()
    check = Booking.query.filter(and_(Booking.book_id == book_id["id"], Booking.start_date <= request.json["end_date"], request.json["start_date"] <= Booking.end_date)).all()
    print(check, file=sys.stderr)
    if check:
        return jsonify({'message': 'Booking overlap.'}), 200
    b = Booking(book_id=book_id["id"], booker=u, start_date=request.json["start_date"], end_date=request.json["end_date"])
    db.session.add(b)
    db.session.commit()
    return jsonify({'message': 'Booking completed.'}), 201
Beispiel #27
0
def contactindex(cid, includeCanceled=True, start=None, end=None):
    """List all bookings for a contact"""
    contact = Contact.select().where(Contact.id == cid).get()
    if start is None:
        start = date.today()
    if end is None:
        end = date.today() + timedelta(days=30)
    b = (Booking.select(Booking).where(
        Booking.contact == contact).where((Booking.startTime > start)
                                          & (Booking.endTime < end)))
    if not includeCanceled:
        b = b.where(Booking.isCanceled == False)
    bookings = prefetch(b, BookingRoom, Room, Contact)
    return render_template('bookings/contactIndex.html',
                           bookings=bookings,
                           start=start,
                           end=end,
                           includeCanceled=includeCanceled,
                           contact=contact)
Beispiel #28
0
def check_bookings_of_user_room_when(user_id,
                                     room_id,
                                     when,
                                     status='approved'):
    assert status in ['approved', 'pending', 'denied']
    # print(when)
    # print(status)
    # print('user_id', user_id)
    # print('room_id', room_id)
    query = Booking.select().join(Room).where((Booking.who == user_id)
                                              & (Room.id == room_id)
                                              & (Booking.when == when)
                                              & (Booking.status == status))
    count = query.count()
    # print(count)
    # if count > 0:
    #     print('peow')
    #     print(query[0].status)
    assert count in [0, 1]
    return bool(count)
Beispiel #29
0
def create_booking(**kwargs):
    required_params = ['slot_id', 'consultation_with', 'additional_note', 'reason']
    if 'DC=techlab' not in kwargs['cas:distinguishedName']:
        abort(401, "Unauthorized to access this resource")
    if not request.json:
        abort(400, "Request should be in JSON format")
    if not all(param in request.json for param in required_params):
        abort(400, "One or more required fields not found")

    # validate if any of the request param is empty
    for key in required_params:
        if request.json[key] is None or request.json[key] == "":
            abort(400, "One or more required param is empty")

    # validate if the provided slot id is not booked
    if Booking.query.filter_by(slot_id=request.json['slot_id']).first():
        abort(409, "Slot is already booked")

    slot = Slot.query.filter_by(id=request.json['slot_id'], status='Available'). \
        first_or_404(description='invalid slot_id supplied')

    bookings = Booking.query.filter_by(student_sam_account_name=kwargs['cas:sAMAccountName']).all()

    # for booking in bookings:
    #     if slot.datetime == Slot.query.filter_by(id=booking.slot_id).first().datetime:
    #         abort(409, "Student can not book two slots at same time")
    #
    # if (slot.datetime - datetime.now()).seconds <= 1:
    #     abort(409, "slot booking time already passed")

    new_booking = Booking.deserialize(request.json)
    new_booking.student_sam_account_name = kwargs['cas:sAMAccountName']
    new_booking.status = "Booked"
    new_booking.booking_datetime = datetime.now()

    slot.status = "Booked"
    slot.booking_slots.append(new_booking)
    db.session.add(new_booking)
    db.session.commit()

    return jsonify({"message": "Booking has been added successfully"}), 201
Beispiel #30
0
def test_json(data):
    data = json.loads(data)
    try:
        b = Booking(id=data['id'],
                    user_id=data['user_id'],
                    vehicle_model_id=data['vehicle_model_id'],
                    package_id=data['package_id'],
                    travel_type_id=data['travel_type_id'],
                    from_area_id=data['from_area_id'],
                    to_area_id=data['to_area_id'],
                    from_city_id=data['from_city_id'],
                    to_city_id=data['to_city_id'],
                    from_date=data['from_date'],
                    to_date=data['to_date'],
                    online_booking=data['online_booking'],
                    mobile_site_booking=data['mobile_site_booking'],
                    booking_created=data['booking_created'],
                    from_lat=data['from_lat'],
                    from_long=data['from_long'],
                    to_lat=data['to_lat'],
                    to_long=data['to_long'],
                    Car_Cancellation=data['Car_Cancellation'])
        db.session.add(b)
        db.session.commit()
        # log succesful addition
        emit('my_response', {'success': True, 'id': data['id']})
    except KeyError:
        # log data with exception
        emit('my_response', {
            'success': False,
            'id': data['id'],
            'cause': 'Unrecognised attribute'
        })
    except:
        # log data
        emit('my_response', {
            'success': False,
            'id': data['id'],
            'cause': 'Unknows error'
        })