Ejemplo n.º 1
0
    def products_category():
        """ 상품 카테고리 list
        Author:  
            Chae hyun Kim
        Returns: 
            - 200: { "message"   : "SUCCESS"
                     "result"    : {
                        "data"       : category_list,
                        "totalCount" : 2차 카테고리 총 갯수
                        }
                    }
        """
        connection = None
        try:
            connection = connect_db()
            produts_category_service = ProductService()
            category_list = produts_category_service.products_category(
                connection)

            return category_list

        except Exception as e:
            if connection:
                connection.rollback
            raise e
        finally:
            if connection:
                connection.close()
Ejemplo n.º 2
0
    def get_question_open():
        """ [서비스] 제품 상세페이지에서 질문 올릴 때 질문유형 선택 드롭박스
        Author:
            Ji Yoon Lee
        Args:
            - token(str): 로그인 user의 token이 header에 담겨 들어와 로그인 유효성 검사를 거침
        Returns:
            - 200 :  
                { 
                    'message': 'SUCCESS',
                    'result': {
                        'data': 질문 유형 목록
                    }
                }
            - 400: "요청에 실패하였습니다"
        Note:
            회원만 질문을 남길 수 있음
        """
        connection = None
        try:
            connection = connect_db()
            if connection:
                product_service = ProductService()
                type_list = product_service.get_question_open(connection)

                return type_list

        except Exception as e:
            if connection:
                connection.rollback()
            raise ApiException(400, REQUEST_FAILED)

        finally:
            if connection:
                connection.close()
Ejemplo n.º 3
0
    def product_detail(product_id):
        """ [서비스] 제품 상세페이지 제품정보 가져오기
        Author:
            Ji Yoon Lee
        Args:
            - product_id (path parameter)
        Returns:
            - 200 :  
                { 
                    'message': 'SUCCESS',
                    'result': {
                        'product': 상품정보
                    }
                }
            - 400: "요청에 실패하였습니다"
        """
        connection = None
        try:
            connection = connect_db()
            if connection:
                product_service = ProductService()

                product_detail = product_service.get_product_detail(
                    product_id, connection)

            return product_detail

        except Exception as e:
            if connection:
                connection.rollback()
            raise ApiException(400, REQUEST_FAILED)

        finally:
            if connection:
                connection.close()
Ejemplo n.º 4
0
    def patch(*args):
        data = request.json

        for row in data:
            # product_id가 없을 때
            if row.get("product_id") is None:
                raise InvalidParamError(NOT_EXIST_PRODUCT_ID, 400)

            # product_id가 숫자가 아닐 때
            if type(row.get("product_id")) is not int:
                raise InvalidParamError(INVALID_PRODUCT_ID, 400)

        product_service = ProductService()
        connection = None

        try:
            connection = connect_db()
            result = product_service.update_product_list(connection, data)
            return jsonify({"data": result})

        except Exception as e:
            connection.rollback()
            raise e

        finally:
            if connection is not None:
                connection.close()
Ejemplo n.º 5
0
    def post_product_qna():
        """ [서비스] 제품 상세페이지에서 질문 등록
        Author:
            Ji Yoon Lee
        Args:
            - token(str): 로그인 user의 token이 header에 담겨 들어와 로그인 유효성 검사를 거침
            - body(dict): 'questionType', 'content', 'isPrivate'(비공개글일시), 'productId'
        Returns:
            - 200 :  
                { 
                    'message': 'SUCCESS',
                    'result': {
                        'data': {
                            등록된 질문 id,
                            질문 로그 id
                        }
                    }
                }
            - 400: '요청에 실패하였습니다', 필수 parameter 미입력시 '** 정보를 입력해 주세요'
            - 401: '로그인이 필요합니다'
        """
        connection = None
        try:
            user_id = g.token_info['user_id']
            data = request.json

            if user_id is None:
                raise ApiException(401, LOGIN_REQUIRED)
            if 'questionType' not in data:
                raise ApiException(400, SELECT_QUESTION_TYPE)
            if 'content' not in data:
                raise ApiException(400, CONTENT_MISSING)
            if 'productId' not in data:
                raise ApiException(400, PRODUCT_INFO_MISSING)

            connection = connect_db()
            question_info = {
                'question_type_id': data['questionType'],
                'contents': data['content'],
                'is_private': data.get('isPrivate', 1),
                'product_id': data['productId'],
                'user_id': user_id
            }

            product_service = ProductService()
            product_qna = product_service.post_product_qna(
                question_info, connection)
            connection.commit()

            return product_qna

        except ApiException as e:
            if connection:
                connection.rollback()
            raise ApiException(400, REQUEST_FAILED)

        finally:
            if connection:
                connection.close()
Ejemplo n.º 6
0
    def get_product_qna(product_id):
        """ [서비스] 제품 상세페이지에서 해당 상품 관련 질문 답변
        Author:
            Ji Yoon Lee
        Args:
            - token(str): 로그인 user의 token이 header에 담겨 들어와 로그인 유효성 검사를 거침
            - product_id (path parameter)
            - limit(int): 한 페이지에 보여질 게시물 수 (질문기준 갯수)
            - offset(int): 페이지 이동 시, 몇번째 게시물부터 보여줄 지
        Returns:
            - 200 :  
                { 
                    'message': 'SUCCESS',
                    'result': {
                        'data': {
                            질문 정보,
                            답변 정보(답변 있을시)
                        }
                    }
                }
            - 400: 존재하지 않는 상품의 경로로 들어온 경우 '잘못된 경로입니다'
        Note:
            - token 유무 상관없이 제품 상페페이지 접근 가능.
            - 단, token이 있고 해당 유저가 상품 질문을 남긴 경우, 자신이 등록한 글과 해당 답변은 열람 가능
            - 글 등록시 공개로 등록된 글은 본인의 글 아니여도 누구나 열람 가능
            - 자신의 아이디와 판매자의 브랜드 이름은 공개
            - 다른 회원이 올린 비공개 게시물은 아이디 부분 비공개처리 
        """
        connection = None
        try:
            # 회원인지 비회원인지 확인. 회원이라면 회원 특정.
            if "token_info" in g:
                user_id = g.token_info["user_id"]
            else:
                user_id = None

            info = {
                'user_id': user_id,
                'product_id': product_id,
                'limit': int(request.args.get("limit", 5)),
                'offset': int(request.args.get("offset", 0))
            }

            connection = connect_db()

            if connection:
                product_service = ProductService()
                product_qna = product_service.get_product_qna(info, connection)

                return product_qna

        except Exception as e:
            if connection:
                connection.rollback()
            raise ApiException(400, WRONG_URI_PATH)

        finally:
            if connection:
                connection.close()
Ejemplo n.º 7
0
    def products_list():
        """ products list
        Author:  
            Chae hyun Kim
        Args:    
            - query parameter : 필요할 경우 category의 id, limit과 offset 조건을 query paramter로 받는다
        Returns: 
            - 200: { 
                        "message" : "SUCCESS",
                        "result"  : {
                            "data" : product list,
                            "totalCount" : 상품 총 갯수
                        }
                    }
        Note:    
            - filtering 조건으로 category의 id가 query parameter를 통해 들어올 경우 해당 조건에 해당하는 product list로 결과 반환
        """
        MINIMUM_CATEGORY_NUMBER = 4
        MAXIMUM_CATEGORY_NUMBER = 5
        connection = None
        try:
            connection = connect_db()
            products_service = ProductService()
            page_condition = {}
            category = request.args.get('category', None)
            limit = request.args.get('limit', None)
            offset = request.args.get('offset', None)

            # filtering 조건으로 들어올 category의 값이 허용 범위를 넘었을 경우 에러 반환
            if category is not None:
                if int(category) < MINIMUM_CATEGORY_NUMBER or int(
                        category) > MAXIMUM_CATEGORY_NUMBER:
                    raise ApiException(404, INVALID_FILTER_CONDITION)
                page_condition['category'] = category

            # "더보기"를 누르기 전 limit 조건이 들어오지 않았을 경우 기본으로 30으로 지정
            if limit is None:
                page_condition['limit'] = 30
            else:
                page_condition['limit'] = int(limit)

            # "더보기"를 누르기 전 offset 조건이 들어오지 않았을 경우 기본으로 0으로 지정
            if offset is None:
                page_condition['offset'] = 0
            else:
                page_condition['offset'] = int(offset)

            product_list = products_service.products_list(
                connection, page_condition)

            return product_list

        except Exception as e:
            if connection:
                connection.rollback
            raise e
        finally:
            if connection:
                connection.close()
Ejemplo n.º 8
0
def store_rating():
    rating_dict = request.form.to_dict(flat=False)
    print(request.form)
    try:
        ProductService.store_rating(rating_dict)
        return "success"
    except KeyError:
        return "failure"
Ejemplo n.º 9
0
def delete():
    productService = ProductService()

    productId = request.args.get("id")
    if productId is None:
        return ("forbidden", 403)

    result = json.dumps({"successful": productService.delete(productId)})

    productService.dispose()
    return (result, 200)
Ejemplo n.º 10
0
    def post(self, valid: ValidRequest):
        data = valid.get_form()
        data["account_id"] = g.account_info.get("account_id")
        data["account_type"] = g.account_info.get("account_type")

        # json 형태로 오는 options 따로 변수 선언 후 제거
        options = literal_eval(data["options"])
        del data["options"]

        main_image_file = request.files.get("main_image_file")
        image_files = request.files.getlist("image_files")

        if data["account_type"] not in [
                MASTER_ACCOUNT_TYPE, SELLER_ACCOUNT_TYPE
        ]:
            raise UnauthorizedError(UNAUTHORIZED, 401)

        product_service = ProductService()
        image_service = ImageService()
        connection = None
        s3_connection = None
        image_urls = []

        try:
            connection = connect_db()
            s3_connection = connect_s3()

            # 상품 등록
            data = product_service.insert_new_product(connection, data,
                                                      options)

            # 메인 이미지 S3 등록
            image_urls.append(
                image_service.image_upload(s3_connection, main_image_file))

            # 다른 이미지 S3 등록
            for image_file in image_files:
                image_urls.append(
                    image_service.image_upload(s3_connection, image_file))

            product_service.insert_new_product_images(connection, data,
                                                      image_urls)

            connection.commit()
            return jsonify({"message": "success"})

        except Exception as e:
            connection.rollback()
            raise e

        finally:
            if connection is not None:
                connection.close()
Ejemplo n.º 11
0
    def get(self, valid: ValidRequest):
        """어드민 상품 관리 리스트

        Author:
            이서진

        Returns:
            - 200:
                "data": {
                    "count": 상품 리스트 총 개수
                    "products": [
                        {
                            "created_at": 상품 등록 시간,
                            "discount_start_time": 상품 할인 시작 시간,
                            "discount_end_time": 상품 할인 끝 시간,
                            "discount_rate": 상품 할인율,
                            "image_url": 상품 대표 이미지 주소,
                            "is_displayed": 진열 여부,
                            "is_sold": 판매 여부,
                            "name": 상품 이름,
                            "price": 가격,
                            "product_code": 상품 코드,
                            "product_number": 상품 번호,
                            "seller_category": 셀러 속성
                        }
                    ]
                }
            - 400: validate param 오류
        """

        filters = valid.get_params()
        filters["account_id"] = g.account_info.get("account_id")
        filters["account_type"] = g.account_info.get("account_type")

        if filters["account_type"] not in [
                MASTER_ACCOUNT_TYPE, SELLER_ACCOUNT_TYPE
        ]:
            raise UnauthorizedError(UNAUTHORIZED, 401)

        product_service = ProductService()
        connection = None

        try:
            connection = connect_db()
            result = product_service.get_product_list(connection, filters)
            return jsonify({"data": result})

        except Exception as e:
            raise e

        finally:
            if connection is not None:
                connection.close()
Ejemplo n.º 12
0
def find():
    productService = ProductService()

    productId = request.args.get("id")
    if productId is None:
        return None

    product = productService.find(productId)
    result = json.dumps(product.dicted())

    productService.dispose()

    return (result, 200)
Ejemplo n.º 13
0
def modify():
    productService = ProductService()

    flag = False

    try:
        product = Product.dict2Obj(json.loads(request.data))
        flag = productService.modify(product)
    except:
        return ("forbidden", 403)

    result = json.dumps({"successful": flag})

    productService.dispose()
    return (result, 200)
    def apply_rule(self):
        ipad = ProductService().get_product('ipd')
        ipad_count = self.shopping_cart.products.count(ipad)
        if ipad_count > 4:
            self.shopping_cart.total -= ipad_count * (ipad.price - 499.99)

        return self.shopping_cart
Ejemplo n.º 15
0
def create_app(test_config=None):
    app = Flask(__name__)
    app.config['JSON_AS_ASCII'] = False

    CORS(app)

    if test_config is None:
        app.config.from_pyfile("config.py")
    else:
        app.config.update(test_config)

    product_dao = ProductDao()
    seller_dao = SellerDao()
    order_dao = OrderDao()
    user_dao = UserDao()
    coupon_dao = CouponDao()
    event_dao = EventDao()

    services = Services

    services.product_service = ProductService(product_dao, app.config)
    services.seller_service = SellerService(seller_dao, app.config)
    services.order_service = OrderService(order_dao, app.config)
    services.user_service = UserService(user_dao, app.config)
    services.coupon_service = CouponService(coupon_dao, app.config)
    services.event_service = EventService(event_dao, app.config)

    create_endpoints(app, services)

    return app
Ejemplo n.º 16
0
def findWarning():
    productService = ProductService()

    num = request.args.get("num")
    if num is None:
        return None

    products = productService.findWarning(int(num))

    result = []
    for product in products:
        result.append(product.dicted())

    productService.dispose()

    return (json.dumps(result), 200)
Ejemplo n.º 17
0
def create_app(test_config=None):
    app = Flask(__name__)
    app.json_encoder = CustomEncoder
    CORS(app, resources={r'*': {'origins': '*'}})
    if test_config is None:
        app.config.from_pyfile('config.py')
    else:
        app.config.update(test_config)

    #persistence layer

    account_dao = AccountDao()
    seller_dao = SellerDao()
    order_dao = OrderDao()
    product_dao = ProductDao()

    #business layer
    account_service = AccountService(account_dao, config)
    seller_service = SellerService(seller_dao, config)
    order_service = OrderService(order_dao)
    product_service = ProductService(product_dao)

    #presentation layer(엔드포인트 생성)
    app.register_blueprint(create_account_endpoints(account_service))
    app.register_blueprint(create_seller_endpoints(seller_service))
    app.register_blueprint(create_order_endpoints(order_service))

    app.register_blueprint(create_product_endpoints(product_service))

    return app
Ejemplo n.º 18
0
    def apply_rule(self):
        macbook_pro = ProductService().get_product('mbp')
        macbook_pro_count = self.shopping_cart.products.count(macbook_pro)

        vga_adapter = ProductService().get_product('vga')
        vga_count = self.shopping_cart.products.count(vga_adapter)

        if macbook_pro_count >= 1:
            # if vga adapters are already added, apply price discount
            if vga_count >= macbook_pro_count:
                self.shopping_cart.total -= macbook_pro_count * vga_adapter.price
            # if vga adapter numbers are not matching macbook pro numbers, add more
            elif vga_count < macbook_pro_count:
                self.shopping_cart.total -= vga_count * vga_adapter.price
                for _ in range(macbook_pro_count - vga_count):
                    self.shopping_cart.products.append(vga_adapter)
        return self.shopping_cart
Ejemplo n.º 19
0
    def get(*args, seller_category_id, product_category_id=None):
        filters = dict(request.args)
        filters["seller_category_id"] = seller_category_id
        filters["product_category_id"] = product_category_id

        product_service = ProductService()
        connection = None

        try:
            connection = connect_db()
            result = product_service.get_product_category_list(connection, filters)
            return jsonify({"data": result})

        except Exception as e:
            raise e

        finally:
            if connection is not None:
                connection.close()
Ejemplo n.º 20
0
def create_app(test_config=None):

    def get_session():
        session = Session()
        return session

    app = Flask(__name__)

    CORS(app, resources={r'*': {'origins': '*'}})

    @app.errorhandler(Exception)
    def handle_invalid_usage(error):
        if isinstance(error, InvalidRequest):
            return {'message': str(error)}, 400
        else:
            response = jsonify(error)
            response.status_code = error.status_code
            return response

    from contextlib import suppress
    from flask.json import JSONEncoder  
    
    class MyJSONEncoder(JSONEncoder):
        def default(self, obj):
            # Optional: convert datetime objects to ISO format
            with suppress(AttributeError):
                return obj.isoformat()
            return dict(obj)

    app.json_encoder = MyJSONEncoder

    if test_config is None:
        app.config.from_pyfile("config.py")
    else:
        app.config.update(test_config)

    database = create_engine(app.config['DB_URL'], encoding='utf-8', max_overflow=0)
    Session = sessionmaker(bind=database, autocommit=False)

    # Persistence Layer
    seller_dao = SellerDao()
    product_dao = ProductDao()
    order_dao = OrderDao()

    # Business Layer
    services = Services
    services.seller_service = SellerService(seller_dao, app.config)
    services.product_service = ProductService(product_dao)
    services.order_service = OrderService(order_dao, seller_dao)

    seller_endpoints(app, services, get_session)
    product_endpoints(app, services, get_session)
    order_endpoints(app, services, get_session)

    return app
Ejemplo n.º 21
0
    def apply_rule(self):
        apple_tv = ProductService().get_product('atv')
        apple_tv_count = self.shopping_cart.products.count(apple_tv)
        if apple_tv_count >= 3:
            # get the number of 3 for 2 sets of apple tv
            sets_applied_discount = (apple_tv_count - apple_tv_count % 3) / 3
            # apply discount to the sets, one apply tv for free in each set
            discount = sets_applied_discount * apple_tv.price
            self.shopping_cart.total -= discount

        return self.shopping_cart
Ejemplo n.º 22
0
    def get_other_products():
        """ [서비스] 판매자의 다른상품 5개 추천
        Author:
            Ji Yoon Lee
        Args:
            - query string: 'sellerId', 'productId'
        Returns:
            - 200 :  
                { 
                    'message': 'SUCCESS',
                    'result': {
                        'data': {
                            상품정보
                        }
                    }
                }
            - 400: '요청에 실패하였습니다', 필수 parameter 미입력시 '** 정보를 입력해 주세요'
        """
        connection = None
        try:
            info = {
                "seller_id": int(request.args['sellerId']),
                "product_id": int(request.args['productId'])
            }

            connection = connect_db()
            if connection:
                product_service = ProductService()
                products_list = product_service.get_other_products(
                    info, connection)

                return products_list

        except Exception as e:
            if connection:
                connection.rollback()
            raise ApiException(400, REQUEST_FAILED)

        finally:
            if connection:
                connection.close()
Ejemplo n.º 23
0
def create_app(test_config=None):
    """
    Returns :
        생성된 플라스크 앱 객체
    Authors :
        [email protected](김기욱)
        [email protected](김태하)
    History :
        2020-10-11 : Caching 구현
        2020-10-02 : ASCCI형식 False로 변경(김기욱)
        2020-09-17 : 초기 생성(김기욱 김태하)
    """

    app = Flask(__name__)
    app.config['JSON_AS_ASCII'] = False

    app.config['CACHE_TYPE'] = 'simple'
    cache.init_app(app)

    #SetUp CORS
    CORS(app)

    #SetUp config
    if test_config is None:
        app.config.from_pyfile('config.py')
    else:
        app.config.update(test_config)

    #SetUp Persistence Layer
    product_dao = ProductDao()
    search_dao = SearchDao()
    user_dao = UserDao()
    question_dao = QuestionDao()
    coupon_dao = CouponDao()
    purchase_dao = PurchaseDao()

    #SetUp Business Layer
    services = Services
    services.product_service = ProductService(product_dao)
    services.user_service = UserService(user_dao)
    services.question_service = QuestionService(question_dao)
    services.coupon_service = CouponService(coupon_dao)
    services.search_service = SearchService(search_dao)
    services.purchase_service = PurchaseService(purchase_dao)

    #SetUp Presentation Layer
    create_endpoints(app, services)

    return app
Ejemplo n.º 24
0
def create_app(test_config=None):
    app = Flask(__name__)

    if test_config is None:
        app.config.from_pyfile('config.py')
    else:
        app.config.update(test_config)

    # pool size : 1000, max_overflow=100 인 QueuePool로 DB 연결 설정
    database = create_engine(app.config['DB_URL'],
                             encoding='utf-8',
                             pool_size=1000,
                             max_overflow=100,
                             poolclass=QueuePool)

    # database engin와 연동된 session maker 생성, connection 필요시마다 session instance 생성
    Session = sessionmaker(bind=database)

    # CORS 설정
    CORS(app, resources={r'*': {'origins': '*'}})

    # Persistence layer
    order_dao = OrderDao()
    user_dao = UserDao()
    seller_dao = SellerDao()
    product_dao = ProductDao()
    qna_dao = QnADao()
    review_dao = ReviewDao()
    coupon_dao = CouponDao()

    # Business layer
    order_service = OrderService(order_dao)
    user_service = UserService(user_dao)
    seller_service = SellerService(seller_dao)
    product_service = ProductService(product_dao)
    qna_service = QnAService(qna_dao)
    review_service = ReviewService(review_dao)
    coupon_service = CouponService(coupon_dao)

    # Presentation layer
    app.register_blueprint(create_order_endpoints(order_service, Session))
    app.register_blueprint(create_user_endpoints(user_service, Session))
    app.register_blueprint(create_seller_endpoints(seller_service, Session))
    app.register_blueprint(create_product_endpoints(product_service, Session))
    app.register_blueprint(create_qna_endpoints(qna_service, Session))
    app.register_blueprint(create_review_endpoints(review_service, Session))
    app.register_blueprint(create_coupon_endpoints(coupon_service, Session))

    return app
Ejemplo n.º 25
0
    def get(*args):
        """메인 상품 리스트

        Author:
            이서진

        Returns:
            200: {
            }
        """

        filters = {
            "offset": int(request.args.get("offset", 0)),
            "limit": int(request.args.get("limit", 30))
        }

        if filters.get("offset") < 0:
            filters["offset"] = 0

        if filters.get("limit") < 1:
            filters["limit"] = 1

        product_service = ProductService()
        connection = None

        try:
            connection = connect_db()
            result = product_service.get_product_list(connection, filters)
            return jsonify({"data": result})

        except Exception as e:
            raise e

        finally:
            if connection is not None:
                connection.close()
Ejemplo n.º 26
0
def create_app(test_config=None):
    app = Flask(__name__)

    if test_config is None:
        app.config.from_pyfile("config.py")
    else:
        app.config.update(test_config)

    # DB 연결
    database = create_engine(
        app.config["DB_URL"],
        encoding="utf-8",
        pool_size=1000,
        max_overflow=100,
        poolclass=QueuePool,
    )

    # database와 연동된 session maker 생성, connection 필요시마다 session instace 생성
    Session = sessionmaker(bind=database)

    # CORS 설정
    CORS(app, resources={r"*": {"origins": "*"}})

    # Persistance layer
    user_dao = UserDao()
    product_dao = ProductDao()
    qna_dao = QnaDao()
    order_dao = OrderDao()
    review_dao = ReviewDao()
    event_dao = EventDao()

    # Business layer
    user_service = UserService(user_dao)
    product_service = ProductService(product_dao)
    qna_service = QnaService(qna_dao)
    order_service = OrderService(order_dao)
    review_service = ReviewService(review_dao)
    event_service = EventService(event_dao)

    # Presentation layer
    app.register_blueprint(create_user_endpoints(user_service, Session))
    app.register_blueprint(create_product_endpoints(product_service, Session))
    app.register_blueprint(create_qna_endpoints(qna_service, Session))
    app.register_blueprint(create_order_endpoints(order_service, Session))
    app.register_blueprint(create_review_endpoints(review_service, Session))
    app.register_blueprint(create_event_endpoints(event_service, Session))

    return app
Ejemplo n.º 27
0
def create_app():
    """

    Returns :
        생성된 플라스크 앱 객체

    Authors :
        [email protected]  (손수정)
        [email protected] (이곤호)

    History :
        2020-08-19 ([email protected])  : 초기 생성
        2020-08-25 ([email protected]) : AdminProduct 관련 추가
    """

    app = Flask(__name__)
    app.json_encoder = CustomJSONEncoder

    #CORS 설정
    CORS(app)

    #config 설정
    app.config.from_pyfile("config.py")

    # DAO 생성
    user_dao = UserDao()
    order_dao = OrderDao()
    product_dao = ProductDao()

    # Service 생성
    user_service = UserService(user_dao)
    order_service = OrderService(order_dao)
    product_service = ProductService(product_dao)

    # view blueprint 등록
    app.register_blueprint(create_user_endpoints(user_service))
    app.register_blueprint(create_admin_user_endpoints(user_service))
    app.register_blueprint(create_admin_order_endpoints(order_service))
    app.register_blueprint(service_product_endpoint(product_service))
    app.register_blueprint(create_admin_product_endpoints(product_service))
    app.register_blueprint(create_service_order_endpoints(order_service))

    return app
Ejemplo n.º 28
0
def index():
    productService = ProductService()

    currentIndex = request.args.get("page")
    if currentIndex is None:
        return ("forbidden", 403)

    lastIndex = math.ceil(productService.count() / float(pageSize))

    products = productService.list(int(currentIndex) - 1, pageSize)

    result = []
    for product in products:
        result.append(product.dicted())

    result = json.dumps({
        "currentIndex": currentIndex,
        "lastIndex": lastIndex,
        "products": result
    })

    productService.dispose()
    return (result, 200)
def show_product(id):
    service = ProductService()
    product = service.find_one(id)
    print(product)
    return render_template("view.html", product=product)
def list_products():
    service = ProductService()
    products = service.find_all()
    return render_template("catalog.html", prodocts=products)