예제 #1
0
    def handle(self, *args, **options):
        with open(os.path.join(settings.BASE_DIR, 'app.json'),
                  encoding='utf-8') as file:
            reader = json.load(file)

            for i in reader:
                if i['model'] == 'app.car':
                    new_car = Car(brand=i['fields']['brand'],
                                  model=i['fields']['model'])
                    new_car.save()
예제 #2
0
def add_car(current_user):
    json_data = request.get_json()
    json_data['owner_id'] = current_user.id
    json_data['created_at'] = datetime.datetime.utcnow()
    data, error = car_schema.load(json_data)
    if error:
        return response('failed', error, 400)

    car = Car(current_user.id, data)
    car.save()
    data = car_schema.dump(car).data
    return response_for_added_car(car, 201)    
예제 #3
0
def seed():
    "Adds seed data to the database."
    app.logger.info('Seeding database with sample data')
    app.logger.info('Adding cars..')
    db.session.add(
        Car(
            name='BMW M1',
            description='Carrera Digital 132 BMW M1 Procar Lotus Martini Mario Andretti Nr.1 1979',
            order_number='30814',
            image_link='https://slotcardatenbank.de/car/30814_1851/2120305396.jpeg'
        )
    )
    db.session.add(
        Car(
            name='Porsche 911 GT3 RSR',
            description='Carrera Digital 132 Porsche 911 GT3 RSR Lechner Racing Carrera Race Taxi',
            order_number='30828',
            image_link='https://slotcardatenbank.de/car/30828_2253/895352019.jpeg'
        )
    )
    db.session.add(
        Car(
            name='Mercedes-AMG GT3',
            description='Carrera Digital 132 Mercedes-AMG GT3 AKKA ASP Nr.87',
            order_number='30846',
            image_link='https://slotcardatenbank.de/car/30846_2200/1938848144.jpeg'
        )
    )
    db.session.add(
        Car(
            name='Mercedes-Benz SLS Polizei',
            description='Carrera Digital 132 Mercedes-Benz SLS AMG Polizei',
            order_number='30793',
            image_link='https://slotcardatenbank.de/car/30793_1847/1929172378.jpeg'
        )
    )
    db.session.add(
        Car(
            name='Chevrolet Corvette C7.R',
            description='Carrera Digital 132 Chevrolet Corvette C7.R Corvette Racing Nr.3',
            order_number='30701',
            image_link='https://slotcardatenbank.de/car/30701_874/58602446.jpeg'
        )
    )

    app.logger.info('Registering Racers..')
    db.session.add(Racer(name='Mika'))
    db.session.add(Racer(name='Papa'))

    db.session.commit()
    app.logger.info('..finished')
예제 #4
0
    def setUpTestData(cls):
        cls.manufacturer = Manufacturer(name="Volkswagen")
        cls.manufacturer.save()
        cls.car = Car(manufacturer=cls.manufacturer, name="Golf")
        cls.second_car = Car(manufacturer=cls.manufacturer, name="Passat")
        cls.car.save()
        cls.second_car.save()

        # Adding 3 rates for golf and 2 rates for passat
        for _ in range(3):
            cls.rate = Rate(car=cls.car, rating=4)
            cls.rate.save()
        for _ in range(2):
            cls.rate = Rate(car=cls.second_car, rating=2)
            cls.rate.save()
예제 #5
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('map'))
    form = RegisterForm()
    if form.validate_on_submit():
        u = User(first_name=str(form.firstName.data), last_name=str(form.lastName.data), email=str(form.email.data),
                 contact_number=str(form.contactNumber.data), gender=str(form.gender.data), home_address=str(form.street.data),
                 home_city=str(form.city.data), home_state=str(form.state.data), gender_preferred=str(form.genderPreferred.data))
        u.set_password(str(form.password.data))

        if form.work.data == 'ballDrive':
            u.work_address = '2330 Ball Drive'
            u.work_city = 'St. Louis'
            u.work_state = 'MO'
        elif form.work.data == 'riderTrail':
            u.work_address = '3470 Rider Trail'
            u.work_city = 'Earth City'
            u.work_state = 'MO'
        else:
            u.work_address = '11432 Lackland Rd'
            u.work_city = 'St. Louis'
            u.work_state = 'MO'
        
        if form.car.data == 'yes':
            c = Car(email=str(form.email.data), num_seats=str(form.numberOfSeats.data), mpg=str(form.mpg.data), manufacturer=str(form.manufacturer.data),
                    model=str(form.model.data), license_plate_num=str(form.number.data))
            db.session.add(c)
            u.cars = [c]

        db.session.add(u)
        db.session.commit()

        return redirect(url_for('login'))
    return render_template('register.html', form=form)
예제 #6
0
 def _tuple_to_model(self, c):
     return Car(
         vin=c.Vin,
         price=c.UsedVehiclePrice,
         autopilot=c.AutoPilot,
         badge=c.Badge,
         battery=c.Battery,
         config_id=c.ConfigId,
         decor=c.Decor,
         destination_handling_fee=c.DestinationHandlingFee or 0,
         discount=c.Discount or 0,
         drive_train=c.DriveTrain,
         metro_id=c.MetroId,
         model=c.Model,
         model_variant=c.ModelVariant,
         odometer=c.Odometer,
         odometer_type=c.OdometerType,
         option_code_list=c.OptionCodeList,
         option_code_list_with_price=c.OptionCodeListWithPrice,
         ownership_transfer_count=c.OwnerShipTransferCount or 0,
         paint=c.Paint,
         range=c.Range,
         roof=c.Roof,
         title_status=c.TitleStatus,
         title_sub_status=c.TitleSubStatus or '',
         trade_in_type=c.TradeInType or '',
         year=c.Year,
         is_autopilot=c.isAutopilot,
         is_first_registration_date=c.isFirstRegistrationDate,
         is_panoramic=c.isPanoramic,
         is_premium=c.isPremium,
         country_code=self.country_code,
     )
예제 #7
0
def import_file():
    config_name = os.getenv('FLASK_CONFIG')
    app = create_app(config_name)
    app.app_context().push()

    with open('test3.json') as json_file:
        data = json.load(json_file)
        try:
            for data_row in data:
                vin = data_row['c'][0]['v']
                print(f'importing {vin}')
                if vin_generator.is_valid_vin(vin):
                    car_model = data_row['c'][4]['v']
                    opt_code = data_row['c'][5]['v']
                    ship_to = data_row['c'][6]['v']
                    sold_to = data_row['c'][7]['v']
                    address = data_row['c'][8]['v']
                    zip_code = data_row['c'][9]['v']
                    ext_color = data_row['c'][10]['v']
                    int_color = data_row['c'][11]['v']
                    created = data_row['c'][12]['v']
                    car = Car(vin, ext_color, int_color, car_model, opt_code,
                              sold_to, ship_to)
                    dealer = Dealer(ship_to, address, zip_code)
                    repository.create_dealer(dealer)
                    repository.create_car(car)
        except InvalidRequestError as requestError:
            print(requestError)
        except:
            print(f'failed with {sys.exc_info()[0]}')
예제 #8
0
def create_auto():

    context = None
    index = 'create_auto.html'

    if request.method == 'POST':
        # пришел запрос с методом POST (нажата кнопка ввода)
        # получаем название авто = значение поля input с атрибутом name="name_auto"
        name_auto = request.form['name_auto']
        # получаем описание = значение поля input с атрибутом name="describe"
        describe = request.form['describe']
        # получаем стоимость аренды = значение поля input с атрибутом name="rent_price"
        rent_price = request.form['rent_price']

        # получаем трансмиссию
        if request.form['transmission'] == "1":
            transmission = True  #bool
        else:
            transmission = False

        # Получаем 4 фото нашего авто
        img_url = request.form['img_url']
        img_url2 = request.form['img_url2']
        img_url3 = request.form['img_url3']
        img_url4 = request.form['img_url4']

        # добавляем данные полученные из полей формы в БД
        db.session.add(
            Car(name_auto=name_auto,
                describe=describe,
                rent_price=rent_price,
                transmission=transmission,
                img_url=img_url,
                img_url2=img_url2,
                img_url3=img_url3,
                img_url4=img_url4))

        # сохранить изменения в БД
        db.session.commit()

        # заполняем словарь контекста
        context = {
            'index': index,
            'method': 'POST',
            'name_auto': name_auto,
            'describe': describe,
            'rent_price': rent_price,
            'transmission': transmission,
        }

    elif request.method == 'GET':
        # пришел запрос с методом GET - открыта страница
        # просто передается в контекст имя метода
        context = {
            'index': index,
            'method': 'GET',
        }

    return render_template('layout.html', **context)
예제 #9
0
 def post(self):
     data = request.get_json()
     owners = Owner.query.all()
     owner = Owner(first_name='', second_name=0, last_name='')
     for g in owners:
         if data['owner'] == g.first_name:
             owner = g
     if owner.first_name == '':
         return {'success': False}
     s = Car(manufacturer=data['manufacturer'],
             model=data['model'],
             color=data['color'],
             car_id=data['car_id'])
     s.owner = owner
     db.session.add(s)
     db.session.commit()
     return {'success': True}
예제 #10
0
	def __init__(self, user_cars, *args, **kwargs):
		super(UserAddCarForm, self).__init__(*args, **kwargs)
		user_cars = [(car.id, car.get_name()) for car in user_cars]
		choices = Car.choices()
		for car in user_cars:
			if car in choices:
				choices.remove(car)
		self.car.choices = choices
예제 #11
0
    def test_response_fix(self):
        manufacturer = Manufacturer(name="Volkswagen")
        car = Car(manufacturer=manufacturer, name="Golf")
        serialized_car = CarSerializer(car)
        fixed_response = fix_response(serialized_car)

        assert "manufacturer" not in fixed_response.keys()
        assert fixed_response["make"] == "Volkswagen"
예제 #12
0
def seed_cars():

    demo = Car(user_id=1,
               api_id=21374,
               make="Chevrolet",
               model="Equinox AWD",
               year=2005,
               miles_to_refuel=350,
               mpg=30)  # noqa
    mark = Car(user_id=1,
               api_id=29658,
               make="Honda",
               model="Accord",
               year=2010,
               miles_to_refuel=350,
               mpg=30)  # noqa
    ryan = Car(user_id=1,
               api_id=29823,
               make="BMW",
               model="128ci Convertible",
               year=2010,
               miles_to_refuel=350,
               mpg=30)  # noqa
    brandon = Car(user_id=1,
                  api_id=38911,
                  make="Volkswagen",
                  model="Beetle",
                  year=2018,
                  miles_to_refuel=350,
                  mpg=30)  # noqa
    alycia = Car(user_id=1,
                 api_id=39506,
                 make="Buick",
                 model="Regal",
                 year=2018,
                 miles_to_refuel=350,
                 mpg=30)  # noqa

    db.session.add(demo)
    db.session.add(mark)
    db.session.add(ryan)
    db.session.add(brandon)
    db.session.add(alycia)

    db.session.commit()
예제 #13
0
def addcar(request):
    token = request.session.get('token')
    goodid = request.GET.get('goodid')
    number = request.GET.get('number')
    print(goodid)
    if token:
        user = User.objects.get(token=token)
        good = Goods.objects.get(pk=goodid)
        # cart = Car()
        # cart.user=user
        # cart.good=good
        # cart.number=int(number)
        # cart.save()
        carts = Car.objects.filter(user=user).filter(good=good)

        if carts.exists():  # 存在
            cart = carts.first()
            cart.number = cart.number + int(number)
            cart.save()
        else:  # 不存在
            cart = Car()
            cart.user = user
            cart.good = good
            cart.number = int(number)
            cart.save()

        return JsonResponse({'status': 1})

    else:
        data = {}
        data['msg'] = '请登录后操作!'
        data['status'] = -1
        return JsonResponse(data)
예제 #14
0
def delete_car(current_user, car_id):
    car = Car.get_car_by_id(car_id)
    if not car:
        return response('failed', 'car not found', 404)
    data = cars_schema.dump(car).data
    if data.get('owner_id') != current_user.id:
            return response('failed', 'It\'s not your car', 400)
    car.delete()

    return response('success', 'car deleted', 204)
예제 #15
0
def post_car(user_id):
    data = request.json
    car = Car(user_id=user_id,
              api_id=data['apiId'],
              make=data['make'],
              model=data['model'],
              year=data['year'],
              mpg=data['mpg'],
              miles_to_refuel=int(data['mpg']) * int(data['tankSize']))
    try:
        db.session.add(car)
        db.session.commit()
        car_json = jsonify({'cars': normalize(car.to_dict())})
        return car_json
    except SQLAlchemyError as e:
        error = str(e.__dict__['orig'])
        print(error)
        db.session.rollback()
        return {'errors': ['An error occurred while creating data']}, 500
예제 #16
0
    def car_get():
        """
        Gets a record based on parameters supplied to the endpoint. Returns first suitable found object based on params
        Endpoint URL: /car/get
        :return: JSON of an object or exception status
        """
        if request.method == "GET":
            if request.args is None:
                return jsonify({
                    "status_code": 400,
                    "message": "Invalid request"
                })

            try:
                params = {}  # list of params that we will search by
                # Check if any of the parameters are being passed and then validate them
                if "id" in request.args.keys():
                    params['id'] = helpers.validate_int(
                        request.args.get('id'), 'id')
                if "make" in request.args.keys():
                    params['make'] = helpers.validate_string(
                        request.args.get('make'), 'make')
                if "model" in request.args.keys():
                    params['model'] = helpers.validate_string(
                        request.args.get('model'), 'model')
                if "year" in request.args.keys():
                    params['year'] = helpers.validate_year(
                        request.args.get('year'))
                if "assigned_type" in request.args.keys():
                    params['assigned_type'] = helpers.validate_int(
                        request.args.get('assigned_type'), 'assigned_type')
                if "assigned_id" in request.args.keys():
                    params['assigned_id'] = helpers.validate_int(
                        request.args.get('assigned_id'), 'assigned_id')

                # If no allowed params were passed on - invalidate the request
                if not params:
                    raise Exception({
                        "status_code": 400,
                        "message": "Invalid request"
                    })

                # Get the object based on the given parameters
                car = Car.get(params)
                if not car:
                    raise Exception({
                        "status_code": 404,
                        "message": "Car not found"
                    })
                return jsonify(car.serialize())
            except Exception as e:
                return jsonify({
                    "status_code": e.args[0]['status_code'],
                    "message": e.args[0]['message']
                })
예제 #17
0
def scrape_vin(vin):
    MODEL = "MODEL/OPT.CODE"
    EXT_COLOR = "EXTERIOR COLOR"
    INT_COLOR = "INTERIOR COLOR"
    VIN = "VEHICLE ID NUMBER"
    PORT = "PORT OF ENTRY"
    SOLD_TO = "Sold To"
    SHIP_TO = "Ship To"
    url = f'https://www.kia.com/us/services/en/windowsticker/load/{vin}'
    MODEL_YEAR = "Model Year"
    r = requests.get(url)
    f = io.BytesIO(r.content)
    p = PyPDF2.PdfFileReader(f)
    pdf_text = p.getPage(0).extractText()
    start = 0
    end = pdf_text.index(MODEL)
    car_description = pdf_text[start:end]

    start = end + len(MODEL) + 1
    end = pdf_text.index(EXT_COLOR)
    vin_code = [x.strip() for x in pdf_text[start:end].split('/')]
    model_code = vin_code[0]
    opt_code = vin_code[1]

    start = end + len(EXT_COLOR) + 1
    end = pdf_text.index(INT_COLOR)
    ext_color = pdf_text[start:end]

    start = end + len(INT_COLOR) + 1
    end = pdf_text.index(VIN)
    int_color = pdf_text[start:end]

    start = end + len(VIN) + 1
    end = pdf_text.index(PORT)
    vin = pdf_text[start:end]

    start = pdf_text.index(SOLD_TO) + len(SOLD_TO) + 2
    end = pdf_text.index(SHIP_TO)
    sold_to = pdf_text[start:end]

    start = end + len(SHIP_TO) + 2
    end = start + 5
    ship_to = pdf_text[start:end]
    dealer_address = sold_to.replace(ship_to, '')
    zip = dealer_address[len(dealer_address) - 5:]

    #start = pdf_text.index(MODEL_YEAR) + len(MODEL_YEAR) + 1
    #end = pdf_text.index(MODEL_YEAR)
    model_year = "2021"

    car = Car(vin, ext_color, int_color, model_code, opt_code, ship_to,
              ship_to, model_year)
    dealer = Dealer(ship_to, dealer_address, zip)
    car_model = CarModel(model_code, car_description)
    return car, dealer, car_model
예제 #18
0
    def car_create():
        """
        Creates a record based on params supplied
        Endpoint URL: /car/create
        :return: JSON successful message or exception response
        """
        if request.method == "POST":
            if request.data is None:
                return jsonify({
                    "status_code": 400,
                    "message": "Invalid request"
                })
            request_data = request.data

            try:
                # Find and validate required parameters in order to create car record
                make = helpers.check_missing('list', request_data, 'make')
                make = helpers.validate_string(make, 'make')
                model = helpers.check_missing('list', request_data, 'model')
                model = helpers.validate_string(model, 'model')
                year = helpers.check_missing('list', request_data, 'year')
                year = helpers.validate_year(year)
                assigned_type = helpers.check_missing('list', request_data,
                                                      'assigned_type')
                assigned_id = helpers.check_missing('list', request_data,
                                                    'assigned_id')
                assigned_id = helpers.validate_int(assigned_id, 'assigned_id')

                # Validate the assigned type and id, more logic for assigning in a helper function
                assigned_type, assigned_id = helpers.validate_assigning(
                    assigned_type, assigned_id)

                # Create object and save it in the database
                car = Car(make, model, year, assigned_type, assigned_id)
                car.save()
                return jsonify({"status_code": 201, "message": "Car created"})
            except Exception as e:
                return jsonify({
                    "status_code": e.args[0]['status_code'],
                    "message": e.args[0]['message']
                })
예제 #19
0
def create_car():
    CarForm.add_fields()
    form = CarForm()
    if form.validate_on_submit():
        car = Car()
        # Сколько языков заполнено столько и создаем
        langs = Language.query.all()
        for key in form.data:
            if key in [lang.code for lang in langs]:
                lang = [lang for lang in langs if lang.code == key]
                car.names.append(
                    CarLanguage(name=form.data[key], language=lang[0]))
        car.year = int(form.year.data)
        db.session.add(car)
        db.session.commit()
        flash('You successfuly create new car')
        return redirect(url_for('.cars'))

    return render_template('admin/create_car.html',
                           title='Create new Car',
                           form=form)
예제 #20
0
def add_car():
    if (not request.json or not 'brand' in request.json
            or not 'model' in request.json or not 'dealer' in request.json
            or not 'price' in request.json or not 'color' in request.json):
        return make_response(jsonify({'error': 'Incorrect Request'}), 400)
    else:
        new_car = Car(brand=request.json['brand'],
                      model=request.json['model'],
                      price=int(request.json['price']),
                      vendor_id=int(request.json['dealer']),
                      color=request.json['color'])
        if 'year_built' in request.json:
            new_car.year_built = int(request.json['year_built'])
        if 'mileage' in request.json:
            new_car.mileage = int(request.json['mileage'])
        db.session.add(new_car)
        db.session.commit()
        sale = Sale(car=new_car.id,
                    dealer=new_car.vendor_id,
                    price=new_car.price)
        db.session.add(sale)
        db.session.commit()
        return make_response(jsonify({'result': 'Created Successfully'}), 201)
def RegisterCar():
    form = AddVehicle()
    if form.validate_on_submit():
        car = Car(user=current_user.user,
                  car_vin=form.car_vin.data,
                  make=form.make.data,
                  model=form.model.data,
                  color=form.color.data,
                  mileage=form.mileage.data)
        db.session.add(car)
        db.session.commit()
        flash('You have added a car to use in our App!')
        return redirect(url_for('index'))
    return render_template('addVehicle.html', title='Add Vehicle', form=form)
예제 #22
0
파일: routes.py 프로젝트: skorbut/trackday
def register():
    form = CarRegistrationForm()
    if form.validate_on_submit():
        car = Car(name=form.name.data,
                  description=form.description.data,
                  order_number=form.order_number.data,
                  image_link=form.image_link.data)
        db.session.add(car)
        db.session.commit()
        flash(_l('New car added to car park'))
        return redirect(url_for('index'))
    return render_template('car_registration.html',
                           title='Neues Auto registrieren',
                           form=form)
예제 #23
0
def create_car():
    form = CreateCarForm()
    if form.validate_on_submit():
        car = Car(brand=form.brand.data,
                  model=form.model.data,
                  color=form.color.data,
                  owner=current_user)
        db.session.add(car)
        db.session.commit()
        flash(_('Your car has been created. Find it in your profile'))
        return redirect(url_for('main.index'))
    return render_template('main/create_car.html',
                           title='Create Car',
                           form=form)
예제 #24
0
def update_car(current_user, car_id):
    if request.content_type == 'application/json' :
        req_data = request.get_json()
        car = Car.get_car_by_id(car_id)
        if not car:
            return response('failed', 'car not found', 404)
        data = cars_schema.dump(car).data
        if data.get('owner_id') != current_user.id:
            return response('failed', 'It\'s not your car', 400)
        data, error = cars_schema.load(req_data, partial=True)
        if error:
            return response('failed', error, 400)
        car.update(data)
        data = cars_schema.dump(car).data
        return response_for_get_cars(data)
예제 #25
0
파일: views.py 프로젝트: ld121/SanFu
def addcart(request):
    # 拿到token
    token = request.session.get('token')
    # 根据token在缓存中找到对应用户
    if token:
        #获取对应用户
        userid = cache.get(token)
        user = User.objects.get(pk=userid)
        #获取对应商品信息
        goodsid = request.GET.get('goodsid')
        goods = Goods.objects.get(pk=goodsid)
        # 获取商品数量
        numb = request.GET.get('numb')
        # 获取选择的是购物车还是立即购买
        shopway = request.GET.get('shopway')
        #判断商品是否已经存在购物车中
        carts = Car.objects.filter(user=user).filter(goods=goods)

        if carts.exists():
            if shopway:
                cart = carts.first()
                cart.number = cart.number + int(numb)
                cart.isdelete = False
                cart.save()

        else:
            cart = Car()
            cart.user = user
            cart.goods = goods
            cart.number = numb
            cart.save()
        response_data = {
            'status':1,
            'msg':'添加购物车成功'
        }
        return JsonResponse(response_data)

    else:
        response_data = {
            'status': -1,
            'msg': '请登录再操作'
        }
        return JsonResponse(response_data)
예제 #26
0
def create_auto():
    
    context = None

    if request.method == 'POST':
        
        name_auto = request.form['name']
        rent_price = request.form['price']
        description = request.form['description']
        transmission = True if request.form['transmission'] == " ДА " else False
        img_url = request.form['img_url']
        img_url2 = request.form['img_url2']
        img_url3 = request.form['img_url3']
        img_url4 = request.form['img_url4']

        db.session.add(Car(name_auto = name_auto, rent_price = rent_price, description = description,
         transmission = transmission, img_url = img_url, img_url2 = img_url2, img_url3 = img_url3, img_url4 = img_url4))
        db.session.commit()

        context = {'method': 'POST', 
                'name': name_auto,
                'price': rent_price, 
                'description': description,
                'transmission': transmission,
                'img_url': img_url,
                'img_url2': img_url2,
                'img_url3': img_url3,
                'img_url4': img_url4,
                }
        
    

    elif request.method == 'GET':

        context = {
            'method': 'GET',
        }

    
    return render_template('create_auto.html', **context)
예제 #27
0
def cars(count=100):
    fake = Faker()
    i = 0
    user_count = User.query.count()
    langs = Language.query.all()
    car_names_len = len(car_names)
    while i < int(count):
        u = User.query.offset(randint(0, user_count - 1)).first()
        c = Car()
        c.year = randint(1970, datetime.now().year)
        c.timestamp = fake.past_date()
        c.users.append(u)
        for lang in langs:
            if lang.code == 'en':
                c.set_name(lang, car_names[randint(0, car_names_len - 1)][0])
            elif lang.code == 'ru':
                c.set_name(lang, car_names[randint(0, car_names_len - 1)][1])
        db.session.add(c)
        try:
            db.session.commit()
            i += 1
        except IntegrityError:
            db.session.rollback()
        print('{} fake cars were successfully created.'.format(i))
예제 #28
0
    def car_delete():
        """
        Deletes a record based on the id
        Endpoint URL: /car/delete
        :return: JSON successful message or exception response
        """
        if request.method == "DELETE":
            if request.args is None:
                return jsonify({
                    "status_code": 400,
                    "message": "Invalid request"
                })

            try:
                # Validate id parameter passed
                id = helpers.check_missing('args', request, 'id')
                id = helpers.validate_int(id, 'id')

                # Find the object to delete
                params = {"id": id}
                car = Car.get(params)

                # Return 404 if not found the object to delete
                if not car:
                    return jsonify({
                        "status_code": 404,
                        "message": "Car not found"
                    })

                # Delete object and return successful message
                car.delete()
                return jsonify({"status_code": 200, "message": "Car deleted"})
            except Exception as e:
                return jsonify({
                    "status_code": e.args[0]['status_code'],
                    "message": e.args[0]['message']
                })
예제 #29
0
    def car_update():
        """
        Updates a record based on id supplied
        Endpoint URL: /car/update
        :return: JSON successful message or exception response
        """
        if request.method == "PUT":
            if request.data is None:
                return jsonify({
                    "status_code": 400,
                    "message": "Invalid request"
                })
            request_data = request.data

            try:
                # Validate id parameter passed
                id = helpers.check_missing('list', request_data, 'id')
                id = helpers.validate_int(id, 'id')

                # Find the object to update
                params = {"id": id}
                car = Car.get(params)

                # Return 404 if not found the object to update
                if not car:
                    raise Exception({
                        "status_code": 404,
                        "message": "Car not found"
                    })

                # Find and validate any allowed parameters
                if "make" in request_data.keys():
                    car.make = helpers.validate_string(request_data['make'],
                                                       'make')
                if "model" in request_data.keys():
                    car.model = helpers.validate_string(
                        request_data['model'], 'model')
                if "year" in request.data.keys():
                    car.year = helpers.validate_year(request_data['year'])

                # Logic to enforce assigned type and id to be passed on and validated together
                if "assigned_type" in request_data.keys(
                ) and not "assigned_id" in request_data.keys():
                    raise Exception({
                        "status_code": 400,
                        "message": "Missing assigned_id"
                    })
                elif "assigned_id" in request_data.keys(
                ) and not "assigned_type" in request_data.keys():
                    raise Exception({
                        "status_code": 400,
                        "message": "Missing assigned_type"
                    })
                elif set(
                    ("assigned_type", "assigned_id")) <= request_data.keys():
                    assigned_type, assigned_id = helpers.validate_assigning(
                        request_data['assigned_type'],
                        request_data['assigned_id'])
                    car.assigned_type = assigned_type
                    car.assigned_id = assigned_id

                # Save an object and return successful message
                car.save()
                return jsonify({
                    "status_code": 200,
                    "message": "Car record was updated"
                })
            except Exception as e:
                return jsonify({
                    "status_code": e.args[0]['status_code'],
                    "message": e.args[0]['message']
                })
예제 #30
0
def save_destination(form, destination=None, new=True):
    # PHOTOS
    try:
        request_featured_photo = request.files['featured_photo']
    except KeyError:
        request_featured_photo = False

    if request_featured_photo:
        if new:
            photo_folder_name = form.title.data + '-' + secrets.token_hex(16)
            featured_photo_with_folder = images.save(
                request.files['featured_photo'], folder=photo_folder_name)
            featured_photo = featured_photo_with_folder.split('/')[1]
            featured_photo_filename = featured_photo.split('.')[0]
            featured_photo_extension = featured_photo.split('.')[-1]
            photo_dir = os.path.join(
                current_app.config["UPLOADED_IMAGES_DEST"], photo_folder_name)

            photo_folder_url = images.url(featured_photo_with_folder).split(
                featured_photo)[0]

            current_app.q.enqueue(create_image_set, photo_dir, featured_photo)
        else:
            # Bruke tidligere skapt folder, og hente featured_photo fra form:
            photo_folder_name = destination.photo_folder_url.split(
                '/static/uploads/images/'
            )[-1]  # http://127.0.0.1:5000/static/uploads/images/Oskarshamn-7296b6784120247d3125ace582cdc17e/
            featured_photo_with_folder = images.save(
                request.files['featured_photo'], folder=photo_folder_name)
            featured_photo = featured_photo_with_folder.split('/')[1]
            featured_photo_filename = featured_photo.split('.')[0]
            featured_photo_extension = featured_photo.split('.')[-1]
            photo_dir = os.path.join(
                current_app.config["UPLOADED_IMAGES_DEST"], photo_folder_name
            )  # samma struktur som photo_dir: app/static/uploads/images/Oskarshamn-7296b6784120247d3125ace582cdc17e/
            # photo_folder_url = images.url(featured_photo_with_folder).split(featured_photo)[0]
            # Sende til enqueue
            current_app.q.enqueue(create_image_set, photo_dir, featured_photo)
            # Oppdatere befintlig destination med url/fil/extension
            # - Gjørs nedan

    # COUNTRY & CONTINENT
    country = pycountry_convert.country_alpha2_to_country_name(
        form.country.data)

    continent_code = pycountry_convert.country_alpha2_to_continent_code(
        form.country.data)
    continents = {
        'AF': 'Africa',
        'AN': 'Antarctica',
        'AS': 'Asia',
        'EU': 'Europe',
        'NA': 'North America',
        'OC': 'Oceania',
        'SA': 'South America'
    }
    continent = continents[continent_code]

    # Add new destination
    if new:
        d = Destination(title=form.title.data,
                        country=country,
                        continent=continent,
                        weather_ltd=form.weather_ltd.data,
                        weather_lng=form.weather_lng.data,
                        photo_folder_url=photo_folder_url,
                        featured_photo_filename=featured_photo_filename,
                        featured_photo_extension=featured_photo_extension,
                        description=form.description.data,
                        author=current_user)
        db.session.add(d)
        db.session.commit()
    else:
        destination.title = form.title.data
        destination.country = country
        destination.continent = continent
        destination.weather_ltd = form.weather_ltd.data
        destination.weather_ltd = form.weather_lng.data
        # destination.photo_folder_url = photo_folder_url  # trenger ikke oppdatere denne
        if request_featured_photo:
            destination.featured_photo_filename = featured_photo_filename
        if request_featured_photo:
            destination.featured_photo_extension = featured_photo_extension
        destination.description = form.description.data
        # edited by ??
        db.session.commit()

    if new:
        d = Destination.query.order_by(Destination.id.desc()).first()
    else:
        d = destination

    # Additional photos
    if request.files.getlist('additional_photos'):
        additional_photos_object = []
        for photo in request.files.getlist('additional_photos'):
            photo_folder_name = d.photo_folder_url.split(
                '/static/uploads/images/')[-1]
            additional_photo_folder_name = photo_folder_name + 'additional_photos'
            additional_photo_with_folder = images.save(
                photo, folder=additional_photo_folder_name)
            additional_photo = additional_photo_with_folder.split('/')[2]
            additional_photo_filename = additional_photo.split('.')[0]
            additional_photo_extension = additional_photo.split('.')[-1]
            photo_dir = os.path.join(
                current_app.config["UPLOADED_IMAGES_DEST"],
                additional_photo_folder_name)

            current_app.q.enqueue(create_image_set, photo_dir,
                                  additional_photo)

            additional_photos_object.append(
                AdditionalPhotos(
                    additional_photo_filename=additional_photo_filename,
                    additional_photo_extension=additional_photo_extension,
                    destination_id=d.id))
        db.session.bulk_save_objects(additional_photos_object)

    # COST
    cost_form_currency = form.cost_form_currency.data
    if cost_form_currency != 'EUR':  # EUR on default
        # Getting rate from ratesAPI
        payload = {'base': cost_form_currency, 'symbols': 'EUR'}
        api_currency_data = requests.get('https://api.ratesapi.io/api/latest',
                                         params=payload)

        if api_currency_data.status_code == 200:
            json_api_currency_data = api_currency_data.json()
            conversion_rate = json_api_currency_data['rates']['EUR']

            cost_form_currency = 'EUR'

            beer_at_establishment = Decimal(
                conversion_rate) * form.beer_at_establishment.data  # required
            coffee_at_establishment = Decimal(
                conversion_rate
            ) * form.coffee_at_establishment.data  # required
            restaurant_inexpensive_meal = Decimal(
                conversion_rate
            ) * form.restaurant_inexpensive_meal.data  # required
            groceries_one_week = Decimal(
                conversion_rate) * form.groceries_one_week.data  # required
            car_rent_one_week = \
                (Decimal(conversion_rate) * form.car_rent_one_week.data) if (type(form.car_rent_one_week.data) == Decimal) \
                else 0
            gas_one_liter = \
                (Decimal(conversion_rate) * form.gas_one_liter.data) if (type(form.gas_one_liter.data) == Decimal) else 0
            km_per_day = \
                (Decimal(conversion_rate) * form.km_per_day.data) if (type(form.km_per_day.data) == Decimal) else 0
            tent_per_day = \
                (Decimal(conversion_rate) * form.tent_per_day.data) if (type(form.tent_per_day.data) == Decimal) else None
            van_per_day = \
                (Decimal(conversion_rate) * form.van_per_day.data) if (type(form.van_per_day.data) == Decimal) else None
            camping_per_day = \
                (Decimal(conversion_rate) * form.camping_per_day.data) if (type(form.camping_per_day.data) == Decimal) \
                else None
            hostel_per_day = \
                (Decimal(conversion_rate) * form.hostel_per_day.data) if (type(form.hostel_per_day.data) == Decimal) \
                else None
            apartment_per_day = \
                (Decimal(conversion_rate) * form.apartment_per_day.data) if (type(form.apartment_per_day.data) == Decimal) \
                else None
            house_per_day = \
                (Decimal(conversion_rate) * form.house_per_day.data) if (type(form.house_per_day.data) == Decimal) else None
            hotel_per_day = \
                        (Decimal(conversion_rate) * form.hotel_per_day.data) if (type(form.hotel_per_day.data) == Decimal) else None
        else:
            beer_at_establishment = form.beer_at_establishment.data  # required
            coffee_at_establishment = form.coffee_at_establishment.data  # required
            restaurant_inexpensive_meal = form.restaurant_inexpensive_meal.data  # required
            groceries_one_week = form.groceries_one_week.data  # required
            car_rent_one_week = form.car_rent_one_week.data if (type(form.car_rent_one_week.data) == Decimal) \
                else 0
            gas_one_liter = form.gas_one_liter.data if (type(
                form.gas_one_liter.data) == Decimal) else 0
            km_per_day = form.km_per_day.data if (type(form.km_per_day.data)
                                                  == Decimal) else 0
            tent_per_day = form.tent_per_day.data if (type(
                form.tent_per_day.data) == Decimal) else None
            van_per_day = form.van_per_day.data if (type(form.van_per_day.data)
                                                    == Decimal) else None
            camping_per_day = form.camping_per_day.data if (type(
                form.camping_per_day.data) == Decimal) else None
            hostel_per_day = form.hostel_per_day.data if (type(
                form.hostel_per_day.data) == Decimal) else None
            apartment_per_day = form.apartment_per_day.data if (type(form.apartment_per_day.data) == Decimal) \
                else None
            house_per_day = form.house_per_day.data if (type(
                form.house_per_day.data) == Decimal) else None
            hotel_per_day = form.hotel_per_day.data if (type(
                form.hotel_per_day.data) == Decimal) else None
    else:
        beer_at_establishment = form.beer_at_establishment.data  # required
        coffee_at_establishment = form.coffee_at_establishment.data  # required
        restaurant_inexpensive_meal = form.restaurant_inexpensive_meal.data  # required
        groceries_one_week = form.groceries_one_week.data  # required
        car_rent_one_week = form.car_rent_one_week.data if (type(
            form.car_rent_one_week.data) == Decimal) else 0
        gas_one_liter = form.gas_one_liter.data if (type(
            form.gas_one_liter.data) == Decimal) else 0
        km_per_day = form.km_per_day.data if (type(form.km_per_day.data)
                                              == Decimal) else 0
        tent_per_day = form.tent_per_day.data if (type(form.tent_per_day.data)
                                                  == Decimal) else None
        van_per_day = form.van_per_day.data if (type(form.van_per_day.data)
                                                == Decimal) else None
        camping_per_day = form.camping_per_day.data if (type(
            form.camping_per_day.data) == Decimal) else None
        hostel_per_day = form.hostel_per_day.data if (type(
            form.hostel_per_day.data) == Decimal) else None
        apartment_per_day = form.apartment_per_day.data if (type(
            form.apartment_per_day.data) == Decimal) else None
        house_per_day = form.house_per_day.data if (type(
            form.house_per_day.data) == Decimal) else None
        hotel_per_day = form.hotel_per_day.data if (type(
            form.hotel_per_day.data) == Decimal) else None

    accomodations_form_data = {
        "tent_per_day": tent_per_day,
        "van_per_day": van_per_day,
        "camping_per_day": camping_per_day,
        "hostel_per_day": hostel_per_day,
        "apartment_per_day": apartment_per_day,
        "house_per_day": house_per_day,
        "hotel_per_day": hotel_per_day
    }

    for key in list(accomodations_form_data
                    ):  # Makes a list of al the keys in the dict
        if accomodations_form_data[key] is None:
            del accomodations_form_data[key]

    if accomodations_form_data:  # Checking so it's not empty
        cheapest_accomodation = min(accomodations_form_data,
                                    key=accomodations_form_data.get)
    else:  # if it is empty
        accomodations_form_data = {'no_info': 0}
        cheapest_accomodation = 'no_info'

    avg_weekly_cost = \
        3 * beer_at_establishment + \
        3 * coffee_at_establishment + \
        2 * restaurant_inexpensive_meal + \
        1 * groceries_one_week + \
        1 * car_rent_one_week + \
        7 * gas_one_liter * km_per_day + \
        7 * accomodations_form_data[cheapest_accomodation]

    avg_weekly_cost_rounded = int(avg_weekly_cost)

    if new:
        cost = Cost(
            cost_form_currency=cost_form_currency,
            beer_at_establishment=beer_at_establishment,
            coffee_at_establishment=coffee_at_establishment,
            restaurant_inexpensive_meal=restaurant_inexpensive_meal,
            groceries_one_week=groceries_one_week,
            car_rent_one_week=car_rent_one_week,
            gas_one_liter=gas_one_liter,
            km_per_day=km_per_day,
            tent_per_day=tent_per_day,
            van_per_day=van_per_day,
            camping_per_day=camping_per_day,
            hostel_per_day=hostel_per_day,
            apartment_per_day=apartment_per_day,
            house_per_day=house_per_day,
            hotel_per_day=hotel_per_day,
            accomodation_used_for_avg_weekly_cost=cheapest_accomodation,
            avg_weekly_cost=avg_weekly_cost_rounded,
            destination_id=d.id)
        db.session.add(cost)
    else:
        cost = Cost.query.filter(Cost.destination_id == d.id).first()
        cost.beer_at_establishment = beer_at_establishment
        cost.cost_form_currency = cost_form_currency
        cost.coffee_at_establishment = coffee_at_establishment
        cost.restaurant_inexpensive_meal = restaurant_inexpensive_meal
        cost.groceries_one_week = groceries_one_week
        cost.car_rent_one_week = car_rent_one_week
        cost.gas_one_liter = gas_one_liter
        cost.km_per_day = km_per_day
        cost.tent_per_day = tent_per_day
        cost.van_per_day = van_per_day
        cost.camping_per_day = camping_per_day
        cost.hostel_per_day = hostel_per_day
        cost.apartment_per_day = apartment_per_day
        cost.house_per_day = house_per_day
        cost.hotel_per_day = hotel_per_day
        cost.accomodation_used_for_avg_weekly_cost = cheapest_accomodation
        cost.avg_weekly_cost = avg_weekly_cost_rounded

    # ROUTES
    if new:
        routes = Routes(traditional=form.traditional.data,
                        sport=form.sport.data,
                        bouldering=form.bouldering.data,
                        main_discipline=form.main_discipline.data,
                        easy_routes=form.easy_routes.data,
                        intermediate_routes=form.intermediate_routes.data,
                        hard_routes=form.hard_routes.data,
                        very_hard_routes=form.very_hard_routes.data,
                        total_routes=form.total_routes.data,
                        total_trad=form.total_trad.data,
                        total_sport=form.total_sport.data,
                        total_boulders=form.total_boulders.data,
                        destination_id=d.id)
        db.session.add(routes)
    else:
        routes = Routes.query.filter(Routes.destination_id == d.id).first()
        routes.traditional = form.traditional.data
        routes.sport = form.sport.data
        routes.bouldering = form.bouldering.data
        routes.main_discipline = form.main_discipline.data
        routes.easy_routes = form.easy_routes.data
        routes.intermediate_routes = form.intermediate_routes.data
        routes.hard_routes = form.hard_routes.data
        routes.very_hard_routes = form.very_hard_routes.data
        routes.total_routes = form.total_routes.data
        routes.total_trad = form.total_trad.data
        routes.total_sport = form.total_sport.data
        routes.total_boulders = form.total_boulders.data
        # db.session.commit()  # her?

    # MONTHS
    if new:
        months = Months(january=form.january.data,
                        february=form.february.data,
                        march=form.march.data,
                        april=form.april.data,
                        may=form.may.data,
                        june=form.june.data,
                        july=form.july.data,
                        august=form.august.data,
                        september=form.september.data,
                        october=form.october.data,
                        november=form.november.data,
                        december=form.december.data,
                        destination_id=d.id)
        db.session.add(months)
    else:
        months = Months.query.filter(Months.destination_id == d.id).first()
        months.january = form.january.data
        months.february = form.february.data
        months.march = form.march.data
        months.april = form.april.data
        months.may = form.may.data
        months.june = form.june.data
        months.july = form.july.data
        months.august = form.august.data
        months.september = form.september.data
        months.october = form.october.data
        months.november = form.november.data
        months.december = form.december.data

    # ACCOMODATION
    if new:
        accomodation = Accomodation(tent=form.tent.data,
                                    van=form.van.data,
                                    hostel=form.hostel.data,
                                    camping=form.camping.data,
                                    apartment=form.apartment.data,
                                    house=form.house.data,
                                    hotel=form.hotel.data,
                                    destination_id=d.id)
        db.session.add(accomodation)
    else:
        accomodation = Accomodation.query.filter(
            Accomodation.destination_id == d.id).first()
        accomodation.tent = form.tent.data
        accomodation.van = form.van.data
        accomodation.hostel = form.hostel.data
        accomodation.camping = form.camping.data
        accomodation.apartment = form.apartment.data
        accomodation.house = form.house.data
        accomodation.hotel = form.hotel.data

    # APPROACH
    if new:
        approach = Approach(easy=form.easy.data,
                            moderate=form.moderate.data,
                            hardcore=form.hardcore.data,
                            destination_id=d.id)
        db.session.add(approach)
    else:
        approach = Approach.query.filter(
            Approach.destination_id == d.id).first()
        approach.easy = form.easy.data
        approach.moderate = form.moderate.data
        approach.hardcore = form.hardcore.data

    # CAR
    if new:
        car = Car(
            not_needed=form.not_needed.data,
            good_to_have=form.good_to_have.data,
            must_have=form.must_have.data,
            # rent_scooter_locally=form.rent_scooter_locally.data,
            # rent_car_locally=form.rent_car_locally.data,
            destination_id=d.id)
        db.session.add(car)
    else:
        car = Car.query.filter(Car.destination_id == d.id).first()
        car.not_needed = form.not_needed.data
        car.good_to_have = form.good_to_have.data
        car.must_have = form.must_have.data
        # car.rent_scooter_locally = form.rent_scooter_locally.data,
        # car.rent_car_locally = form.rent_car_locally.data

    db.session.commit()
    return True  # Hvordan returnere False hvis den failer?