예제 #1
0
    def patch(self, account, ad_id):
        """
        Обработчик PATCH-запроса на частичное редактирование объявления.
        :param account: параметры авторизации
        :param ad_id: идентификатор объявления
        :return: response
        """
        seller_id = account['seller_id']
        request_json = request.json
        if not request_json:
            return '', 400

        with db.connection as con:
            service = AdsService(con)
            try:
                service.edit_ad(ad_id, seller_id, request_json)
            except AdPermissionError:
                return '', 403
            except AdDoesNotExistError:
                return '', 404
            except AdExecuteError:
                con.rollback()
                return '', 409
            else:
                return '', 200
예제 #2
0
    def post(self, user):
        """Создание нового объявления"""
        request_json = request.json

        seller_id = user["seller_id"]
        title = request_json.get('title')
        data = datetime.now().strftime("%A, %d. %B %Y %I:%M%p")
        tags = request_json.get("tags")
        car = request_json.get("car")
        colors = car.get("color")
        image = car.get("image")

        with db.connection as connection:

            car_service = CarsService(connection)
            car_id = car_service.create(car)

            color_service = ColorService(connection)
            for color in colors:
                color_service.add_to_car_color(color, car_id)

            image_service = ImageService(connection)
            for image_data in image:
                image_service.update_image(image_data, car_id)

            ads_serivce = AdsService(connection)
            ad_id = ads_serivce.create_ad(seller_id, car_id, title, data)

            tag_service = TagsService(connection)
            for tag in tags:
                tag_service.add_to_ad(tag, ad_id)

        return jsonify(generation_ad_dict(ad_id)), 201
예제 #3
0
    def patch(self, ad_id, user):
        """Частичное редактирование объявления с указанным id"""
        request_json = request.json
        car_data = request_json.get("car")

        with db.connection as connection:

            title = request_json.get("title")
            if title is not None:
                as_service = AdsService(connection)
                as_service.update_ad(ad_id=ad_id, titile=title)

            tags = request_json["tags"]
            tags_service = TagsService(connection)
            for tag in tags:
                tags_service.add_to_ad(tag, ad_id)

            car_service = CarsService(connection)
            car_id = car_service.get_id(ad_id=ad_id)
            try:
                car_service.update(car_id=car_id, data=car_data)
            except CarDoesNotExists:
                car_service.create(car_data)

            colors = car_data.get("colors")
            car_service = ColorService(connection)
            for color in colors:
                car_service.add_to_car_color(color, car_id)

            images = car_data.get("images")
            image_service = ImageService(connection)
            for image in images:
                image_service.update_image(image, car_id)

        return '', 204
예제 #4
0
 def get(self):
     qs = dict(request.args)
     if 'tags' in qs:
         qs['tags'] = qs['tags'].split(',')
     with db.connection as con:
         service = AdsService(con)
         ads = service.get_ads(qs)
         return jsonify(ads)
예제 #5
0
 def get(self):
     """
     Вывести все объявления
     :return: Объявления
     """
     ads_service = AdsService(db.connection)
     ads = ads_service.get_all_ads()
     return jsonify(ads), 200
예제 #6
0
 def get(self, ad_id):
     with db.connection as con:
         service = AdsService(con)
         try:
             ad = service.get_ad(ad_id)
         except AdDoesNotExistError:
             return '', 404
         else:
             return jsonify(ad)
예제 #7
0
    def post(account_id, account):
        if account_id != account['id'] or not account['is_seller']:
            return '', 403

        with db.connection as con:
            request_json = request.json
            service = AdsService(con)
            ad = service.post_ad(request_json, account_id)
            return jsonify(ad), 201
예제 #8
0
 def get(self):
     """
     Обработчик GET-запроса на получение списка объявлений
     с опциональными query string параметрами.
     :return: response
     """
     qs = dict(request.args)
     with db.connection as con:
         service = AdsService(con)
         ads = service.get_ads(qs=qs)
     return jsonify(ads), 200, {'Content-Type': 'application/json'}
예제 #9
0
 def delete(self, ad_id):
     """
         Удалить объявление
     """
     user_id = session.get('user_id')
     if user_id is None:
         return '', 401
     ad_service = AdsService(db.connection)
     if not ad_service.is_ad_belong_user(user_id, ad_id):
         return '', 403
     ad_service.delete_ad(ad_id)
     return '', 200
예제 #10
0
 def get(self, ad_id):
     """
     Обработчик GET-запроса на получение объявления по его id
     :param ad_id: идентификатор объявления
     """
     with db.connection as con:
         service = AdsService(con)
         try:
             ad = service.get_formatted_ad(ad_id)
         except AdDoesNotExistError:
             return '', 404
         else:
             return jsonify(dict(ad))
예제 #11
0
 def get(self, account_id):
     """
     Обработчик GET-запроса на получение списка объявлений
     с опциональными query string параметрами через id пользователя.
     :param account_id:
     :return:
     """
     qs = dict(request.args)
     with db.connection as con:
         service = AdsService(con)
         try:
             ads = service.get_ads(account_id=account_id, qs=qs)
         except SellerDoesNotExistError:
             return '', 404
         else:
             return jsonify(ads), 200, {'Content-Type': 'application/json'}
예제 #12
0
    def delete(self, ad_id, seller):
        seller_id = seller['id']
        with db.connection as con:
            cur = con.execute(f"""
                SELECT ad.seller_id
                FROM ad
                WHERE ad.id={ad_id}
            """)
            result = cur.fetchone()
            if result is None:
                return "", 404
        seller_id_ad = result[0]

        if seller_id != seller_id_ad:
            return '', 403
        service = AdsService(con)
        service.delete_ad(ad_id)
        return "", 204
예제 #13
0
def generation_ad_dict(ad_id: int) -> dict:
    """Формирование словаря представления объявления"""
    with db.connection as connection:
        ad_service = AdsService(connection)
        response = ad_service.read_ad(ad_id)

        car_service = CarsService(connection)
        response["car"] = car_service.read_car(ad_id=ad_id)

        color_service = ColorService(connection)
        response["car"]["color"] = color_service.read_all_color(ad_id=ad_id)

        image_service = ImageService(connection)
        response["car"]["images"] = image_service.read_image(ad_id=ad_id)

        tags_service = TagsService(connection)
        response["tags"] = tags_service.read_tag(ad_id=ad_id)
    return response
예제 #14
0
    def post(self, account, account_id):
        # Проверка соответствия id авторизованного пользователя и запрошенного id
        if account_id != account['account_id']:
            return 403

        seller_id = account['seller_id']
        request_json = request.json
        if not request_json:
            return '', 400

        with db.connection as con:
            service = AdsService(con)
            try:
                ad = service.publish(request_json, seller_id)
            except AdExecuteError:
                con.rollback()
                return '', 409
            else:
                return jsonify(dict(ad)), 201
예제 #15
0
    def post(self, account):
        """
        Обработчик POST-запрса на создание объявления.
        :param account: параметры авторизации
        :return: response
        """
        seller_id = account['seller_id']
        request_json = request.json
        if not request_json:
            return '', 400

        with db.connection as con:
            service = AdsService(con)
            try:
                ad = service.publish(request_json, seller_id)
            except AdExecuteError:
                con.rollback()
                return '', 409
            else:
                return jsonify(dict(ad)), 201
예제 #16
0
    def delete(self, account, ad_id):
        """
        Обраюотчик DELETE-запроса на удаление объявления.
        :param account: параметры авторизации
        :param ad_id: идентификатор
        :return: response
        """
        seller_id = account['seller_id']

        with db.connection as con:
            service = AdsService(con)
            try:
                service.delete_ad(ad_id, seller_id)
            except AdPermissionError:
                return '', 403
            except AdDoesNotExistError:
                return '', 404
            except AdExecuteError:
                con.rollback()
                return '', 409
            else:
                return '', 200
예제 #17
0
 def post(self):
     """Запостить объявление"""
     user_id = session.get('user_id')
     if user_id is None:
         return '', 401
     user_service = UserService(db.connection)
     if not user_service.is_user_a_seller(user_id):
         return 'Пользователь не является продавцом', 403
     request_json = request.json
     ad_title = request_json.get('title')
     car = {
         'make': request_json.get('car').get('make'),
         'model': request_json.get('car').get('model'),
         'mileage': request_json.get('car').get('mileage'),
         'num_owners': request_json.get('car').get('num_owners'),
         'reg_number': request_json.get('car').get('reg_number'),
     }
     car_service = CarService(db.connection)
     new_car = car_service.add_car(car)
     ad_service = AdsService(db.connection)
     new_ad = ad_service.add_ad(ad_title, session.get('user_id'),
                                new_car['id'])
     return jsonify(ad_service.get_ad_by_id(new_ad['id'])), 200
예제 #18
0
    def get(self):
        """Получение списка объявлений"""
        query_seller_id = request.args.get("seller_id")
        query_tags = request.args.get("tags")
        query_make = request.args.get("make")
        query_model = request.args.get("model")

        with db.connection as connection:
            ad_service = AdsService(connection)
            asd_id = ad_service.generation_id(seller_id=query_seller_id)

        ads = [generation_ad_dict(asd_id) for ad_id in asd_id]

        if query_make is not None:
            ads = list(filter(lambda x: x["car"]["make"] == query_make, ads))

        if query_model is not None:
            ads = list(filter(lambda x: x["car"]["make"] == query_make, ads))

        if query_tags is not None:
            query_tags = [tag.strip() for tag in query_tags.split(',')]
            ads = [ad for ad in ads for tag in ad["tags"] if tag in query_tags]

        return jsonify(ads)
예제 #19
0
    def delete(self, ad_id, user):
        """Удаление объявления с указанным id"""
        with db.connection as connection:
            as_service = AdsService(connection)

            try:
                as_service.read_ad(ad_id)
            except AdDoesNotExists:
                pass
            else:
                as_service.delete_ad(ad_id)

            return '', 200
예제 #20
0
 def get(self, user_id):
     ads_service = AdsService(db.connection)
     return jsonify(ads_service.get_all_users_ads(user_id)), 200
예제 #21
0
 def get(self, ad_id):
     """
     Получить объявление по id
     """
     ad_service = AdsService(db.connection)
     return jsonify(ad_service.get_ad_by_id(ad_id)), 200
예제 #22
0
 def get(account_id):
     with db.connection as con:
         service = AdsService(con)
         dict_query = dict(request.args)
         ads = service.get_ads(dict_query=dict_query, account_id=account_id)
         return jsonify(ads)
예제 #23
0
 def get(self):
     with db.connection as con:
         service = AdsService(con)
         qwery = dict(request.args)
         ads = service.get_ads(dict_query=qwery)
         return jsonify(ads)
예제 #24
0
파일: ads.py 프로젝트: intelligent174/Site
 def get(self):
     with db.connection as con:
         service = AdsService(con)
         ads = service.get_ads()
         return jsonify(ads)