def __getCar(self, id): carTuple = db.getObjectById('cars', id)[0] if not carTuple: return None return Car(carTuple[0], carTuple[1], carTuple[2], carTuple[3], carTuple[4], carTuple[5], carTuple[6], carTuple[7], carTuple[8])
class CarPoolTest(unittest.TestCase): __apiController = ApiController() __expectedCar = Car(1, 'Holden Commodore', 'SUV', 'Red', 4, 35.0, 21.0, 13.0, 0) def setUp(self): userId = self.__apiController.requestGet( 'http://localhost:5000/css/api/v1.0/bookings/3')['user']['id'] userDict = self.__apiController.requestGet( 'http://localhost:5000/css/api/v1.0/users/{}'.format(userId)) self.__user = Customer(userId, userDict['username'], userDict['password'], userDict['firstName'], userDict['lastName'], userDict['email'], userDict['faceId']) return super().setUp() def testGetCar(self): self.assertEqual( carPool.getCar(1).asDict(), self.__expectedCar.asDict()) def testLockCar(self): self.assertFalse(carPool.lockCar(self.__user)) def testUnlockCar(self): self.assertFalse(carPool.unlockCar(self.__user))
def cars(): from models import Car if request.method == "GET": res_json = {"cars": []} cars = Car.query.all() for car in cars: res_json["cars"].append({ "make": car.make, "model": car.model, "year": car.year, "id": car.id, "last_updated": car.last_updated.strftime('%d/%m/%Y %H:%M:%S') }) return json.dumps({"res": res_json}) else: make = request.json["make"] model = request.json["model"] year = request.json["year"] chassis_id = request.json["chassis_id"] car_obj = Car(make, model, year, chassis_id, None, None) try: db.session.add(car_obj) db.session.commit() return "", 201 except: db.session.rollback() return "", 500
def detail(): id = request.args.get("id") good = Goods.query.filter(Goods.id == id).first() #热门商品 hot_goods = Goods.query.order_by(Goods.sales_volume.desc()).limit(5).all() # 获取底部相关商品 similar_goods = Goods.query.filter_by(good_type=good.good_type).order_by( Goods.add_time.desc()).limit(5).all() context = { 'good': good, 'hot_goods': hot_goods, 'similar_goods': similar_goods, 'msg': '不能为空' } if request.method == "POST": if current_user.is_authenticated: quantity = request.form.get('quantity') if quantity: prices = float(int(quantity) * float(good.price)) obj = Car(good_num=quantity, all_price=prices, good_car=id, user_car=current_user.id) db.session.add(obj) db.session.commit() return redirect(url_for('car.list')) else: return render_template('home/goods_detail.html', **context) else: flash('请登陆') return redirect('/login') return render_template('home/goods_detail.html', **context)
def store_car_data(cars): """Stores information of all cars into car table.""" # Create a MySQL database connector object and connect mysql_db = MySQLDatabase(database=s.SCHEMA, user=s.USER, password=s.PASSWORD, host=s.HOST, port=s.PORT) mysql_db.connect() for car in cars: # create new car record new_car = Car(brand=car.get("brand"), model=car.get("model"), year=car.get("year"), price=car.get("price"), ext_color=car.get("ext_color"), int_color=car.get("int_color"), transmission=car.get("transmission"), phone=car.get("phone")) new_car.save() # car is stored into database mysql_db.close() print("All data saved successfully.")
async def post(self, request): data = await request.post() car = Car(model=data.get('model'), year=data.get('year')) session.add(car) session.commit() return await self.response_200(response_data=session.query(Car))
def create(): # Create a new instance of our CarForm class using the request.form # object which will get the request method (GET or POST) as the first # parameter form = CarForm(request.form, csrf_enabled=False) # To check if our require fields have been filled out and then create a new # instance of our Car class and its contructor method will take the form # object if form.validate_on_submit(): car = Car(form) # Since, our object has been created; use an INSERT INTO statement to # add the object's properties to our database query = "INSERT INTO `cars` (`name`, `image`, `topspeed`) VALUES (%s, %s, %s)" # query = "INSERT INTO `cars` (`name`, `image`, `topspeed`) VALUES (%s, %s, %d)" value = (car.name, car.image, car.topspeed) mycursor.execute(query, value) mydb.commit() # If the required fields have been filled out add the car to the # database and redirect to the View Cars page with GET data to # display a success message, else go back to the Add Car page with # GET data to display an error message return redirect('/?add=success') else: return redirect('/add-car?add=error')
def createCar(self, params): # construct a car object from the gathered data car = Car(params[0], params[1], params[2], params[3], params[4], params[5], params[6], params[7], params[8]) # update the database with the new car and respond with a confirmation of insertion db.insertObject('cars', Car.attributesAsList(), car.asTuple()) return jsonify({'car': car.asDict()}), 201
def update(): # Then we will create a new instance of our EditCarForm class form = EditCarForm(request.form, csrf_enabled=False) # Retreive the ID of the car which is being updated by accessing the data # attribute of the id attribute of form object which is actually coming # from POST id = form.id.data # To check if our required fields are filled out if form.validate_on_submit(): # Create a new instance of our Car class and its constructor method # which will take the form object car = Car(form) # Since, our object has been created; use an UPDATE statement and # interpolate the ID of the car to find a matching database row query = f"UPDATE `cars` SET name=%s, image=%s, topspeed=%s WHERE id={id}" value = (car.name, car.image, car.topspeed) mycursor.execute(query, value) mydb.commit() # If the required fields have been filled out update the car in the # database and redirect to the View Cars page with GET data to display # a success message return redirect('/?edit=success') else: # The ID of the item needs to be passed back to the edit page so that # it can display the data. return redirect(f"/edit-object?edit=error&id={id}")
def look_for_cars(): grid_cars.setViewMode(QListView.IconMode) grid_cars.setIconSize(QtCore.QSize(128, 128)) cars = [] for file in os.listdir(configs['rvgl_custom_path'] + '/cars/'): if os.path.isdir(configs['rvgl_custom_path'] + '/cars/' + file): car_path = os.path.join(configs['rvgl_custom_path'] + '/gfx/', file) cars.append(Car(file, car_path)) for car in cars: car_img = os.path.join(configs['rvgl_custom_path'], 'cars', car.car_name, 'carbox.bmp') if not os.path.isfile(car_img): car_img = os.path.join(configs['rvgl_custom_path'], 'gfx', 'bot_bat.bmp') item = QListWidgetItem() icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(car_img), QtGui.QIcon.Normal, QtGui.QIcon.Off) item.setIcon(icon) item.setText(car.car_name) grid_cars.addItem(item)
def create_car(): auth_token = request.args.get('access_token') try: keys = bu.decode_auth_token(auth_token) except jwt.ExpiredSignatureError: return jsonify({'message': 'Signature expired. Please log in again.'}), 401 except jwt.InvalidTokenError: return jsonify({'message': 'Invalid token. Please log in again.'}), 401 admin = keys[0] id = keys[1] if admin == 0: return jsonify({'response': "This is not an admin"}), 403 data = request.get_json() if not data: return jsonify({"response": "No input data provided"}), 400 try: result = CarSchema().load(data) except Exception: return jsonify({'response': "Invalid input"}), 403 if db.session.query(Brand.brandId).filter_by(brandId=result["brand_id"]).scalar() is None: return jsonify({'response': "Invalid brand_id found"}), 403 car = Car(brand_id=result["brand_id"], model=result["model"], description=result["description"]) db.session.add(car) db.session.commit() return jsonify({'response': "Success"}), 201
async def cars_list(request): try: result = Car(**await request.json()) result.save() return web.json_response({'msg': 'Saved'}, status=201) except Exception as e: return web.json_response({'msg': str(e)}, status=400)
def process_item(self, item, spider): print 'PROCESSING ITEM {}'.format(item.get('ref')) c = Car(**item) try: c.save() except IntegrityError as ex: pass return item
def getCar(self, id): # locate a car in the database carTuple = db.getObjectById('cars', id)[0] # use data to create a car object then jsonify it's dict return jsonify( Car(carTuple[0], carTuple[1], carTuple[2], carTuple[3], carTuple[4], carTuple[5], carTuple[6], carTuple[7], carTuple[8]).asDict())
def test_distance_driven_is_number(self): test_car = Car("red", 120, "auto", "85", 100) res = test_car.get_distance_driven() # Test that the result is a number self.assertIsInstance(res, int, "Result should be a number") # Test that the result is the correct number (8500) self.assertEqual(res, 8500, "Result should be 8500 (85 x 100)")
def add_car(self, car): """ Добавить автомобиль """ new_car = Car(make=car['make'], model=car['model'], mileage=car['mileage'], num_owners=car['mileage'], reg_number=car['reg_number']) self.session.add(new_car) self.session.commit() return new_car.as_dict()
def getCar(self, id): response = requests.get( 'http://localhost:5000/css/api/v1.0/cars/{}'.format(id)) carDict = json.loads(response.text) return Car(carDict['id'], carDict['make'], carDict['bodyType'], carDict['colour'], carDict['seats'], carDict['location']['x'], carDict['location']['y'], carDict['costPerHour'], carDict['isLocked'])
def test_serialization_returns_correct_string(self): target_json = '{"average_speed": 85, "color": "red", "gear_box": "auto", "hours_driven": 100, "top_speed": 120}' test_car = Car("red", 120, "auto", "85", "100") res = test_car.get_json() self.assertEqual( res, target_json, "Target json should look like this: {}".format(target_json))
def updateCar(self, id, fieldsToUpdate, params): # update the car with the specified id, indicating which fields to update and what to update them to db.updateObject('cars', id, fieldsToUpdate, params) # retrieve the newly updated car and create an object from it's data carTuple = db.getObjectById('cars', id)[0] car = Car(carTuple[0], carTuple[1], carTuple[2], carTuple[3], carTuple[4], carTuple[5], carTuple[6], carTuple[7], carTuple[8]) # jsonify the car to confirm the update return jsonify({'car': car.asDict()})
def add_some_stuff_logic(): # data = data_manager.load_data(Person) # print (data) p1 = Person('james', 'jackson') p2 = Person('Joan', 'Simpson') Person.add(p1) Person.add(p2) Person.save() c1 = Car('Ferrari', 'Sedan') c2 = Car('Peugeot', 'Station') Car.add(c1) Car.add(c2) Car.save() print(Car.show())
def post_add_car(): mfg = request.form.get("mfg") model = request.form.get("model") year = request.form.get("year") year = year if year else 0 color = request.form.get("color") c = Car(mfg=mfg, model=model, year=year, color=color) g.user.cars.append(c) db.session.commit() return redirect('/list_cars')
def post_add_car(): form = CarDetailsForm() if form.validate_on_submit(): mfg = form.mfg.data model = form.model.data year = form.year.data color = form.color.data c = Car(mfg=mfg, model=model, year=year, color=color) db.session.add(c) db.session.commit() return redirect('/list_cars') else: return render_template("car_details.html", form=form)
async def create_from_csv(db: Session = Depends(get_db)): with open('data.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: car = Car() car.hsn = row[0] # Herstellerschlüsselnummer car.hkt = row[1] # Herstellerklartext car.tsn = row[2] # Typschlüsselnummer car.hn = row[3] # Handelsname car.anzahl = row[4] # Anzahl db.add(car) db.commit() return "all good"
def init_db(): brand = Brand(name='Ford', brand_id=1, country='US').save() Brand(name='Ford2', brand_id=2, country='US').save() brand.save() fiesta = Car(brand=brand, name='Fiesta', car_id=1) edge = Car(brand=brand, name='Edge', car_id=2) ecosport = Car(brand=brand, name='Ecosport', car_id=3) ka = Car(brand=brand, name='Ka', car_id=4) flex_counter = 0 gas_counter = 0 for car in [fiesta, edge, ecosport, ka]: flex_counter += 1 gas_counter += 1 car.save() flex_version = Version(price=random.randrange(0, 50000), model=car, name='{name} {fuel} - {year}'.format( name=car.name, fuel='Flex', year=2011, version_id=flex_counter)) gasoline_version = Version(price=random.randrange(0, 50000), model=car, name='{name} {fuel} - {year}'.format( name=car.name, fuel='Gasolina', year=2011, version_id=gas_counter)) flex_version.save() gasoline_version.save()
def add_car(): make = request.json['make'] model = request.json['model'] price = request.json['price'] body_type = request.json['body_type'] color = request.json['color'] image = request.json['image'] mileage = request.json['mileage'] #init cars with info new_car = Car(make, model, price, body_type, color, image, mileage) db.session.add(new_car) db.session.commit() return car_schema.jsonify(new_car)
def create_car(token): body = request.get_json() (color, release, person_name) = (body.get('color'), body.get('release'), body.get('person_name')) person = Person.query.filter(Person.name == person_name).one_or_none() if color is None or release is None or person is None: abort(422) car = Car(release=release, color=color) person.cars.append(car) person.update() return {'cars': [car.json()], 'success': True}
def post(self): current_user = get_jwt_identity() data = car_parser.parse_args() print(current_user, data) # current_user = User.find_by_username(data['username']) new_car = Car( maker=data['maker'], model=data['model'], fuel_type=data['fuelType'], transmission=data['transmission'], description=data['description'], user_id=User.find_by_username(current_user).id ) try: new_car.save_to_db() return { 'message': 'Car {} {} was added. ID: {}'.format(new_car.maker, new_car.model, new_car.id), } except Exception as e: return {'message': 'Something went wrong', 'exception': e}, 500
def post(self): user = get_jwt_identity() data = parser.parse_args() logger = logging.getLogger('app.add-car-get') car = Car() car.name = data['name'] car.price = data['price'] car.description = data['description'] car.brand = data['brand'] car.model = data['model'] d = data['year'].split(',') car.year = date(int(d[0]), int(d[1]), int(d[2])) car.transmission = data['transmission'] car.engine = data['engine'] car.mileage = data['mileage'] car.fuel = data['fuel'] car.drive_train = data['drive_train'] car.car_type = data['type'] print "[*] Add Car: " print data try: car.owner = int(user) #User.get(id=int(user)) #int(data['user'])) car.save() car.add_search() return { 'data': car.dictionary(), 'message': 'Posting saved', 'status': 'success' } except Exception as e: #logger.error(str(e)) traceback.print_exc(file=sys.stdout) return { 'data': '', 'message': 'And error occur please check your fields', 'status': 'error' }
def getCars(self, params=None): cars = [] # with no optional params all cars can be fetched if not params: carTuples = db.getAllObjects('cars') # otherwise only cars matching the params will be fetched else: for param in params: if param not in Car.attributesAsList(): return jsonify({'cars': []}) # get all cars that match the filter carTuples = db.getObjectsByFilter('cars', list(params.keys()), list(params.values())) # contsruct the fetched cars as objects for i in range(len(carTuples)): cars.append( Car(carTuples[i][0], carTuples[i][1], carTuples[i][2], carTuples[i][3], carTuples[i][4], carTuples[i][5], carTuples[i][6], carTuples[i][7], carTuples[i][8])) # jsonify each car object's dict return jsonify(cars=[car.asDict() for car in cars])
def add_car(form): place = form['place'] active = form['active'] mid = form['man'] cplace = form['cnum'][:2] cnumber = form['cnum'][2:] car = Car.query.filter_by(cplace=cplace, cnumber=cnumber).first() if not car: new_car = Car( cid=str(time.time())[:9]+str(random.randint(10, 99)), mid=mid, status=place, active=active, cplace=cplace, cnumber=cnumber ) db.session.add(new_car) else: car.status = place car.active = active db.session.commit() return redirect(url_for('superadd_page'))