def compute_details(self): last_seen = self.data_dict.get('last_seen', None) if last_seen: last_seen = parse(last_seen) name = self.data_dict.get('name') brand = self.data_dict.get('brand') price = int(self.data_dict.get('price', -1)) year = int(self.data_dict.get('year', -1)) damage = self.data_dict.get('damage') image = self.data_dict.get('image') car_id = self.data_dict.get('id') if not last_seen: self.errors.append("Last seen is a required field.") if not name: self.errors.append("Name is a required field.") if not brand: self.errors.append("Brand is a required field.") if price is None: self.errors.append("You must specify a price") elif price < 0: self.errors.append("Price must be non-negative.") if year is None: self.errors.append("You must specify a year") elif year < 0: self.errors.append("Year must be non-negative.") if not self.errors: car = Car(brand, name, price, year, damage, last_seen, image, car_id) self.car = car
def add_car(cls, car: Car): session = DbSessionFactory.create_session() db_car = Car() db_car.last_seen = parse(car.last_seen) db_car.brand = car.brand db_car.image = car.image if car.image else random.choice( cls.__fake_image_url) db_car.damage = car.damage db_car.year = int(car.year) db_car.price = int(car.price) db_car.name = car.name session.add(db_car) session.commit() return db_car
def create_auto(request: Request): try: car_data = request.json_body car = Car.from_dict(car_data) except: return Response(status=400, body='Could not parse your post as JSON.') # TODO: Validate try: car = Repository.add_car(car) return Response(status=201, json_body=car) except: return Response(status=400, body='Could not save car.')
def __load_data(cls): if cls.__car_data: return file = os.path.join(os.path.dirname(__file__), 'opel.csv') with open(file, 'r', encoding='utf-8') as fin: # brand,name,price,year,damage,last_seen reader = csv.DictReader(fin) for row in reader: key = Repository.generate_id() row['id'] = key row['image'] = random.choice(cls.__fake_image_url) cls.__car_data[key] = Car(**row) # Converting this to cars is kinda slow, # 100 records is enough to get started with. if len(cls.__car_data) > 100: break
def update_auto(request: Request): car_id = request.matchdict.get('car_id') car = Repository.car_by_id(car_id) if car_id == '__first__': car_id = Repository.all_cars()[0].id if not car: msg = "The car with id '{}' was not found.".format(car_id) return Response(status=404, json_body={'error': msg}) try: car_data = request.json_body car = Car.from_dict(car_data) except: return Response(status=400, body='Could not parse your post as JSON.') # TODO: Validate try: Repository.update_car(car) return Response(status=204, body='Car updated successfully.') except: return Response(status=400, body='Could not update car.')