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 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.")
def setUp(self): car = Car() car.make = "Avensis" car.save() self.car = car self.id = car.pk
def save_data_in_db(data_list): """将数据保持到数据库中""" _befor_str = "productPriceReadable-" for data in data_list: # 获取汽车详情url url = data.find_all('a', href=True)[0]['href'] link = 'http://mall.autohome.com.cn' + url # 获取汽车价格信息 __tag = url.split('/')[2].split('-')[0] befor_price = data.find(id=_befor_str+__tag) if data.find(id=_befor_str+__tag): befor_price = data.find(id=_befor_str+__tag).text else: befor_price = '' after_price = _get_after_price(link) # 获取汽车产品名和规格 car_title = data.find('div', class_='carbox-title')['title'].split(' ', 1) logo = car_title[0] model = car_title[1] # 获取汽车购买方案 plan = data.find('div', class_='carbox-tip')['title'] # 获取汽车购买次数 purchased = data.find('div', class_='carbox-number').span.text # 开始保存数据 car = Car(logo, model, befor_price, after_price, plan, purchased, link) car.save() return True
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 __getMatchingCars(self, searchQuery): matchingCars = [] for i in range(len(Car.attributesAsList()) - 1): matchingCars.extend( self.__getCarsByFilterParam(Car.attributesAsList()[i], searchQuery)) return matchingCars
async def update_car(request): car_data = await request.json() try: if car_data.get('VIN'): raise InvalidQueryError('Field VIN is Unchanged') Car.objects(VIN=request.match_info['vin']).update(**car_data) return web.json_response({'msg': 'Car updated'}, status=201) except Exception as e: return web.json_response({'msg': str(e)}, status=400)
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 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 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 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 mutate(root, info, car): if not car.car_id: car.car_id = len(CarModel.objects) + 1 brand = BrandModel.objects.get(brand_id=car.brand) car_model = CarModel( name = car.name, brand = brand.id, car_id = car.car_id ) car_model.save() return createModel(car=car_model)
def addNewCar(request): try: model = request.GET.get('model') maker = request.GET.get('maker') manufYear = request.GET.get('manuf_year') car = Car(carModel=model, carMaker=maker, carManufactureYear=manufYear) car.save() info = {} info['success'] = True return HttpResponse(json.dumps(info), content_type="application/json") except Exception as e: err = {} err['success'] = False err['message'] = str(e.message) + str(e) return HttpResponseBadRequest(json.dumps(err), content_type="application/json")
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 get(self): # get request parameters parameters = request.args # extract parameters from request brand = parameters.get("brand", None) ext_color = parameters.get("extcolor", None) int_color = parameters.get("intcolor", None) year = parameters.get("year", None) transmission = parameters.get("trans", None) query = Car.select() # select all cars # update query due to request parameters if brand is not None: query = query.where(Car.brand == brand) if ext_color is not None: query = query.where(Car.ext_color == ext_color) if int_color is not None: query = query.where(Car.int_color == int_color) if year is not None: query = query.where(Car.year == year) if transmission is not None: query = query.where(Car.transmission == transmission) # return list of desired cars as JSON Object return jsonify(list(query.dicts()))
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 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 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
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 __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])
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 get(self): cars = Car.select() query = [] for car in cars: query.append(car.dictionary()) return {'data': query, 'message': '', 'status': 'success'}
def post(self): logger = logging.getLogger('app.post-admin-published') data = parser.parse_args() try: user = User.get(id=int(get_jwt_identity())) if user.account_type != 'admin': return {}, 401 car = Car.get(id=int(data['car_id'])) car.published = False if data['published'] == 'True': car.published = True car.save() if car.published: return { 'data': '', 'message': 'Car {} has been published'.format(car.name), 'status': 'success' } return { 'data': '', 'message': 'Car {} has been removed from the published cars'.format( car.name), 'status': 'success' } except Exception as e: print str(e) logger.error(e) return {'data': '', 'message': 'An error occur', 'status': 'error'}
async def delete(request): try: car = Car.objects(VIN=request.match_info['vin']) if not car.delete(): raise InvalidQueryError('Unknown car with this VIN') return web.json_response({'msg': 'Car deleted'}, status=204) except Exception as e: return web.json_response({'error': str(e)}, status=400)
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 get(self): logger = logging.getLogger('app.get-car-') cars = [ car.dictionary() for car in Car.select().where(Car.flagged == True) ] return {'data': cars, 'message': '', 'status': 'success'}
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 get(self, id): try: car = Car.get(id=int(id)) return send_from_directory(UPLOAD_FOLDER, car.pics) except Exception as e: return { 'data': '', 'message': 'Image not found', 'status': 'error' }
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 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 save(self): data = self.cleaned_data car_data = Car(name = data['name'], image= data['image']) car_data.save() return True
def test_basic(self): # Save up the number of connected signals so that we can check at the # end that all the signals we register get properly unregistered (#9989) pre_signals = ( len(signals.pre_save.receivers), len(signals.post_save.receivers), len(signals.pre_delete.receivers), len(signals.post_delete.receivers), ) data = [] def pre_save_test(signal, sender, instance, **kwargs): data.append( (instance, kwargs.get("raw", False)) ) signals.pre_save.connect(pre_save_test) def post_save_test(signal, sender, instance, **kwargs): data.append( (instance, kwargs.get("created"), kwargs.get("raw", False)) ) signals.post_save.connect(post_save_test) def pre_delete_test(signal, sender, instance, **kwargs): data.append( (instance, instance.id is None) ) signals.pre_delete.connect(pre_delete_test) post_delete_test = PostDeleteHandler(data) signals.post_delete.connect(post_delete_test) # throw a decorator syntax receiver into the mix @receiver(signals.pre_save) def pre_save_decorator_test(signal, sender, instance, **kwargs): data.append(instance) @receiver(signals.pre_save, sender=Car) def pre_save_decorator_sender_test(signal, sender, instance, **kwargs): data.append(instance) p1 = Person(first_name="John", last_name="Smith") self.assertEqual(data, []) p1.save() self.assertEqual(data, [ (p1, False), p1, (p1, True, False), ]) data[:] = [] p1.first_name = "Tom" p1.save() self.assertEqual(data, [ (p1, False), p1, (p1, False, False), ]) data[:] = [] # Car signal (sender defined) c1 = Car(make="Volkswagon", model="Passat") c1.save() self.assertEqual(data, [ (c1, False), c1, c1, (c1, True, False), ]) data[:] = [] # Calling an internal method purely so that we can trigger a "raw" save. p1.save_base(raw=True) self.assertEqual(data, [ (p1, True), p1, (p1, False, True), ]) data[:] = [] p1.delete() self.assertEqual(data, [ (p1, False), (p1, False), ]) data[:] = [] p2 = Person(first_name="James", last_name="Jones") p2.id = 99999 p2.save() self.assertEqual(data, [ (p2, False), p2, (p2, True, False), ]) data[:] = [] p2.id = 99998 p2.save() self.assertEqual(data, [ (p2, False), p2, (p2, True, False), ]) data[:] = [] p2.delete() self.assertEqual(data, [ (p2, False), (p2, False) ]) self.assertQuerysetEqual( Person.objects.all(), [ "James Jones", ], unicode ) signals.post_delete.disconnect(post_delete_test) signals.pre_delete.disconnect(pre_delete_test) signals.post_save.disconnect(post_save_test) signals.pre_save.disconnect(pre_save_test) signals.pre_save.disconnect(pre_save_decorator_test) signals.pre_save.disconnect(pre_save_decorator_sender_test, sender=Car) # Check that all our signals got disconnected properly. post_signals = ( len(signals.pre_save.receivers), len(signals.post_save.receivers), len(signals.pre_delete.receivers), len(signals.post_delete.receivers), ) self.assertEqual(pre_signals, post_signals)
def parse_cars(info): cars = [] if u"Car" in info: inf = info[u"Car"] if u"@Number" in inf: car = Car() car.number = inf[u"@Number"] car.car_type = info[u"@Type"] car.tariff = info["Tariff"] car.places = inf[u"Places"] cars.append(car) else: for i in inf: car = Car() car.number = i[u"@Number"] car.car_type = info[u"@Type"] car.tariff = info[u"Tariff"] car.places = i[u"Places"] cars.append(car) else: for elem in info: inf = elem[u"Car"] if u"@Number" in inf: car = Car() car.number = inf[u"@Number"] car.car_type = elem[u"@Type"] car.tariff = elem[u"Tariff"] car.places = inf[u"Places"] cars.append(car) else: for i in inf: car = Car() car.number = i[u"@Number"] car.car_type = elem["@Type"] car.tariff = elem[u"Tariff"] car.places = i[u"Places"] cars.append(car) return cars