示例#1
0
from flask_restplus import Namespace, Resource

from backend.service import ProductService
from backend.util.request.product_list_request import ProductListRequest
from backend.util.response.products_total import ProductTotalResponse
from backend.util.response.error import ErrorResponse
from backend.controller import ErrorHandler, auth_required

productTotalNS = Namespace("Product",
                           description="Product related operations.")

REQUESTMODEL = ProductListRequest.get_model(productTotalNS,
                                            "ProductListRequest")
RESPONSEMODEL = ProductTotalResponse.get_model(productTotalNS,
                                               "ProductTotalResponse")
ERRORMODEL = ErrorResponse.get_model(productTotalNS, "ErrorResponse")


@productTotalNS.route("/total", strict_slashes=False)
class ProductTotalController(Resource):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__productservice = ProductService()

    @auth_required()
    @productTotalNS.doc(security=["token"])
    @productTotalNS.param("payload",
                          description="Required",
                          _in="body",
                          required=True)
    @productTotalNS.expect(REQUESTMODEL)
示例#2
0
import os
from flask import current_app as app
from flask_restplus import Namespace, Resource
from requests import post

from backend.service import CartService
from backend.util.response.cart import CartResponse
from backend.util.response.error import ErrorResponse
from backend.controller import ErrorHandler
from backend.errors.no_content_error import NoContentError


selectAllNS = Namespace("Cart", description="Cart related operations.")

RESPONSEMODEL = CartResponse.get_model(selectAllNS, "CartResponse")
ERRORMODEL = ErrorResponse.get_model(selectAllNS, "ErrorResponse")


@selectAllNS.route("", strict_slashes=False)
class SelectAllController(Resource):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__cartservice = CartService()
        self.__url = app.config["WILLSTORES_WS"]
        self.__headers = {"Authorization": "Bearer %s" % os.getenv("ACCESS_TOKEN")}

    @selectAllNS.response(200, "Success", RESPONSEMODEL)
    @selectAllNS.response(204, "No Content", {})
    @selectAllNS.response(401, "Unauthorized", ERRORMODEL)
    @selectAllNS.response(500, "Unexpected Error", ERRORMODEL)
    @selectAllNS.response(502, "Error while accessing the gateway server", ERRORMODEL)
示例#3
0
文件: order.py 项目: willrp/willbuyer
import os
from flask import current_app as app
from flask_restplus import Namespace, Resource
from flask_login import login_required, current_user
from requests import put

from backend.service import CartService
from backend.util.response.error import ErrorResponse
from backend.controller import ErrorHandler
from backend.errors.no_content_error import NoContentError
from backend.errors.request_error import ValidationError

orderNS = Namespace("Cart", description="Cart related operations.")

ERRORMODEL = ErrorResponse.get_model(orderNS, "ErrorResponse")


@orderNS.route("/order", strict_slashes=False)
class OrderController(Resource):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__cartservice = CartService()
        self.__url = app.config["WILLORDERS_WS"]
        self.__headers = {
            "Authorization": "Bearer %s" % os.getenv("ACCESS_TOKEN")
        }

    @login_required
    @orderNS.doc(security=["login"])
    @orderNS.response(201, description="Created", mask=False)
    @orderNS.response(400, "Bad Request", ERRORMODEL)
示例#4
0
import os
from flask import current_app as app
from flask_restplus import Namespace, Resource
from flask_login import login_required, current_user
from requests import delete

from backend.util.response.error import ErrorResponse
from backend.controller import ErrorHandler


deleteNS = Namespace("Order", description="Order related operations.")

ERRORMODEL = ErrorResponse.get_model(deleteNS, "ErrorResponse")


@deleteNS.route("/delete/<string:slug>", strict_slashes=False)
class DeleteController(Resource):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__url = app.config["WILLORDERS_WS"]
        self.__headers = {"Authorization": "Bearer %s" % os.getenv("ACCESS_TOKEN")}

    @login_required
    @deleteNS.doc(security=["login"])
    @deleteNS.param("slug", description="Order slug", _in="path", required=True)
    @deleteNS.response(200, description="Deleted with success", mask=False)
    @deleteNS.response(400, "Bad Request", ERRORMODEL)
    @deleteNS.response(401, "Unauthorized", ERRORMODEL)
    @deleteNS.response(404, "Not Found", ERRORMODEL)
    @deleteNS.response(500, "Unexpected Error", ERRORMODEL)
    @deleteNS.response(502, "Error while accessing the gateway server", ERRORMODEL)
示例#5
0
from flask_restplus import Namespace, Resource

from backend.service import ProductService
from backend.util.request.product_list_request import ProductListRequest
from backend.util.response.products_list import ProductsListResponse
from backend.util.response.error import ErrorResponse
from backend.controller import ErrorHandler, auth_required


productListNS = Namespace("Product", description="Product related operations.")

REQUESTMODEL = ProductListRequest.get_model(productListNS, "ProductListRequest")
RESPONSEMODEL = ProductsListResponse.get_model(productListNS, "ProductsListResponse")
ERRORMODEL = ErrorResponse.get_model(productListNS, "ErrorResponse")


@productListNS.route("/list", strict_slashes=False)
class ProductListController(Resource):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__productservice = ProductService()

    @auth_required()
    @productListNS.doc(security=["token"])
    @productListNS.param("payload", description="Required", _in="body", required=True)
    @productListNS.expect(REQUESTMODEL)
    @productListNS.response(200, "Success", RESPONSEMODEL)
    @productListNS.response(400, "Bad Request", ERRORMODEL)
    @productListNS.response(401, "Unauthorized", ERRORMODEL)
    @productListNS.response(500, "Unexpected Error", ERRORMODEL)
    @productListNS.response(504, "Error while accessing the gateway server", ERRORMODEL)
示例#6
0
import os
from flask import current_app as app
from flask_restplus import Namespace, Resource
from requests import get, post

from backend.service import CartService
from backend.util.response.cart import CartResponse
from backend.util.response.error import ErrorResponse
from backend.controller import ErrorHandler
from backend.errors.request_error import ValidationError


updateNS = Namespace("Cart", description="Cart related operations.")

RESPONSEMODEL = CartResponse.get_model(updateNS, "CartResponse")
ERRORMODEL = ErrorResponse.get_model(updateNS, "ErrorResponse")


@updateNS.route("/update/<string:item_id>/<int:amount>", strict_slashes=False)
class UpdateController(Resource):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__cartservice = CartService()
        self.__url = app.config["WILLSTORES_WS"]
        self.__headers = {"Authorization": "Bearer %s" % os.getenv("ACCESS_TOKEN")}

    @updateNS.param("item_id", description="Item ID", _in="path", required=True)
    @updateNS.param("amount", description="Amount", _in="path", required=True)
    @updateNS.response(200, "Success", RESPONSEMODEL)
    @updateNS.response(400, "Bad Request", ERRORMODEL)
    @updateNS.response(401, "Unauthorized", ERRORMODEL)
示例#7
0
                    name = user_info["name"]
                    picture = user_info["picture"]
                    user_service.get_create_user(oauth=oauth,
                                                 email=email,
                                                 name=name,
                                                 picture=picture)

                login_user(oauth.user)
                return False
            except Exception:
                return redirect(url_for("frontend.index", error="error"))


loginNS = Namespace("User", description="User authentication with OAuth2.")

ERRORMODEL = ErrorResponse.get_model(loginNS, "ErrorResponse")


@loginNS.route("", strict_slashes=False)
class LoginAuthController(Resource):
    @loginNS.response(302, "Redirect to login URL or index")
    @loginNS.response(500, "Unexpected Error", ERRORMODEL)
    def get(self):
        """User login"""
        try:
            if current_user.is_authenticated is False:
                next_url = request.args.get("next")
                if next_url is not None and is_safe_url(next_url):
                    session["next_url"] = next_url

                return redirect(url_for("google.login"))
示例#8
0
 def __handle_HTTPError(self):
     error_status = self.error.response.status_code
     error_content = ErrorResponse.parse_HTTPError(
         self.error.response.content.decode("utf-8"))
     abort(error_status, error=error_content)
示例#9
0
from flask_restplus import Namespace, Resource

from backend.service import ProductService
from backend.util.request.search_request import SearchRequest
from backend.util.response.search_results import SearchResultsResponse
from backend.util.response.error import ErrorResponse
from backend.controller import ErrorHandler, auth_required

searchNS = Namespace("Search", description="Search related operations.")

REQUESTMODEL = SearchRequest.get_model(searchNS, "SearchRequest")
RESPONSEMODEL = SearchResultsResponse.get_model(searchNS,
                                                "SearchResultsResponse")
ERRORMODEL = ErrorResponse.get_model(searchNS, "ErrorResponse")


@searchNS.route("/<string:query>", strict_slashes=False)
class SearchController(Resource):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__productservice = ProductService()

    @auth_required()
    @searchNS.doc(security=["token"])
    @searchNS.param("query",
                    description="The search query",
                    _in="path",
                    required=True)
    @searchNS.param("payload",
                    description="Optional",
                    _in="body",
示例#10
0
from flask_restplus import Namespace, Resource

from backend.service import ProductService
from backend.util.request.search_products_request import SearchProductsRequest
from backend.util.response.search_products_results import SearchProductsResultsResponse
from backend.util.response.error import ErrorResponse
from backend.controller import ErrorHandler, auth_required


sessionProductsNS = Namespace("Session", description="Session related operations.")

REQUESTMODEL = SearchProductsRequest.get_model(sessionProductsNS, "SearchProductsRequest")
RESPONSEMODEL = SearchProductsResultsResponse.get_model(sessionProductsNS, "SearchProductsResultsResponse")
ERRORMODEL = ErrorResponse.get_model(sessionProductsNS, "ErrorResponse")


@sessionProductsNS.route("/<string:sessionid>/<int:page>", strict_slashes=False)
class SessionProductsController(Resource):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__productservice = ProductService()

    @auth_required()
    @sessionProductsNS.doc(security=["token"])
    @sessionProductsNS.param("sessionid", description="The desired session ID", _in="path", required=True)
    @sessionProductsNS.param("page", description="The search page.", _in="path", required=True)
    @sessionProductsNS.param("payload", description="Optional", _in="body", required=False)
    @sessionProductsNS.expect(REQUESTMODEL)
    @sessionProductsNS.response(200, "Success", RESPONSEMODEL)
    @sessionProductsNS.response(204, "No content", ERRORMODEL)
    @sessionProductsNS.response(400, "Bad Request", ERRORMODEL)
示例#11
0
from flask_restplus import Namespace, Resource

from backend.service import ProductService
from backend.util.response.products_count import ProductsCountResponse
from backend.util.response.error import ErrorResponse
from backend.controller import ErrorHandler, auth_required


startNS = Namespace("Start", description="Initial operations.")

RESPONSEMODEL = ProductsCountResponse.get_model(startNS, "ProductsCountResponse")
ERRORMODEL = ErrorResponse.get_model(startNS, "ErrorResponse")


@startNS.route("", strict_slashes=False)
class StartController(Resource):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__productservice = ProductService()

    @auth_required()
    @startNS.doc(security=["token"])
    @startNS.response(200, "Success", RESPONSEMODEL)
    @startNS.response(401, "Unauthorized", ERRORMODEL)
    @startNS.response(500, "Unexpected Error", ERRORMODEL)
    @startNS.response(504, "Error while accessing the gateway server", ERRORMODEL)
    def get(self):
        """Total products registered."""
        try:
            numproducts = self.__productservice.products_count()
            jsonsend = ProductsCountResponse.marshall_json({"count": numproducts})
示例#12
0
import os
from flask import current_app as app
from flask_restplus import Namespace, Resource
from requests import post

from backend.service import CartService
from backend.util.response.cart import CartResponse
from backend.util.response.error import ErrorResponse
from backend.controller import ErrorHandler
from backend.errors.no_content_error import NoContentError

removeNS = Namespace("Cart", description="Cart related operations.")

RESPONSEMODEL = CartResponse.get_model(removeNS, "CartResponse")
ERRORMODEL = ErrorResponse.get_model(removeNS, "ErrorResponse")


@removeNS.route("/remove/<string:item_id>", strict_slashes=False)
class RemoveController(Resource):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__cartservice = CartService()
        self.__url = app.config["WILLSTORES_WS"]
        self.__headers = {
            "Authorization": "Bearer %s" % os.getenv("ACCESS_TOKEN")
        }

    @removeNS.param("item_id",
                    description="Item ID",
                    _in="path",
                    required=True)
示例#13
0
from flask_restplus import Namespace, Resource
from flask_login import current_user, login_required

from backend.util.response.user import UserResponse
from backend.util.response.error import ErrorResponse
from backend.controller import ErrorHandler

currentNS = Namespace("User", description="User related operations.")

RESPONSEMODEL = UserResponse.get_model(currentNS, "UserResponse")
ERRORMODEL = ErrorResponse.get_model(currentNS, "ErrorResponse")


@currentNS.route("/current", strict_slashes=False)
class CurrentController(Resource):
    @login_required
    @currentNS.doc(security=["login"])
    @currentNS.marshal_with(RESPONSEMODEL,
                            code=200,
                            description="Success",
                            mask=False)
    @currentNS.response(401, "Unauthorized", ERRORMODEL)
    @currentNS.response(500, "Unexpected Error", ERRORMODEL)
    def get(self):
        """Get current (logged in) user"""
        try:
            jsonsend = UserResponse.marshall_json(current_user.to_dict())
            return jsonsend
        except Exception as error:
            return ErrorHandler(error).handle_error()
示例#14
0
from flask_restplus import Namespace, Resource
from flask import current_app as app
from requests import post

from backend.util.request.store.search_request import SearchRequest
from backend.util.response.store.session_results import SessionResultsResponse
from backend.util.response.error import ErrorResponse
from backend.controller import ErrorHandler
from backend.errors.no_content_error import NoContentError

sessionNS = Namespace("Store", description="Store related operations.")

REQUESTMODEL = SearchRequest.get_model(sessionNS, "SearchRequest")
RESPONSEMODEL = SessionResultsResponse.get_model(sessionNS,
                                                 "SessionResultsResponse")
ERRORMODEL = ErrorResponse.get_model(sessionNS, "ErrorResponse")


@sessionNS.route("/session/<string:sessionid>", strict_slashes=False)
class SessionController(Resource):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__url = app.config["WILLSTORES_WS"]
        self.__headers = {
            "Authorization": "Bearer %s" % os.getenv("ACCESS_TOKEN")
        }

    @sessionNS.param("sessionid",
                     description="The desired session ID",
                     _in="path",
                     required=True)
示例#15
0
from flask_restplus import Namespace, Resource

from backend.service import ProductService
from backend.util.request.search_products_request import SearchProductsRequest
from backend.util.response.search_products_results import SearchProductsResultsResponse
from backend.util.response.error import ErrorResponse
from backend.controller import ErrorHandler, auth_required

searchProductsNS = Namespace("Search",
                             description="Search related operations.")

REQUESTMODEL = SearchProductsRequest.get_model(searchProductsNS,
                                               "SearchProductsRequest")
RESPONSEMODEL = SearchProductsResultsResponse.get_model(
    searchProductsNS, "SearchProductsResultsResponse")
ERRORMODEL = ErrorResponse.get_model(searchProductsNS, "ErrorResponse")


@searchProductsNS.route("/<string:query>/<int:page>", strict_slashes=False)
class SearchProductsController(Resource):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__productservice = ProductService()

    @auth_required()
    @searchProductsNS.doc(security=["token"])
    @searchProductsNS.param("query",
                            description="The search query",
                            _in="path",
                            required=True)
    @searchProductsNS.param("page",
示例#16
0
from requests import post

from backend.util.request.store.search_products_request import SearchProductsRequest
from backend.util.response.store.search_products_results import SearchProductsResultsResponse
from backend.util.response.error import ErrorResponse
from backend.controller import ErrorHandler
from backend.errors.no_content_error import NoContentError
from backend.errors.request_error import ValidationError

findProductsNS = Namespace("Store", description="Store related operations.")

REQUESTMODEL = SearchProductsRequest.get_model(findProductsNS,
                                               "SearchProductsRequest")
RESPONSEMODEL = SearchProductsResultsResponse.get_model(
    findProductsNS, "SearchProductsResultsResponse")
ERRORMODEL = ErrorResponse.get_model(findProductsNS, "ErrorResponse")


@findProductsNS.route("/find/<string:ftype>/<string:arg>/<int:page>/",
                      strict_slashes=False)
class FinderProductsController(Resource):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__url = app.config["WILLSTORES_WS"]
        self.__headers = {
            "Authorization": "Bearer %s" % os.getenv("ACCESS_TOKEN")
        }
        self.__finder_types = ["search", "brand", "kind"]

    @findProductsNS.param(
        "ftype",
示例#17
0
import os
from flask import current_app as app
from flask_restplus import Namespace, Resource
from flask_login import login_required, current_user
from requests import get

from backend.util.response.order.order import OrderResponse
from backend.util.response.error import ErrorResponse
from backend.controller import ErrorHandler

selectBySlugNS = Namespace("Order", description="Order related operations.")

RESPONSEMODEL = OrderResponse.get_model(selectBySlugNS, "OrderResponse")
ERRORMODEL = ErrorResponse.get_model(selectBySlugNS, "ErrorResponse")


@selectBySlugNS.route("/<string:slug>", strict_slashes=False)
class SelectBySlugController(Resource):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__url = app.config["WILLORDERS_WS"]
        self.__headers = {
            "Authorization": "Bearer %s" % os.getenv("ACCESS_TOKEN")
        }

    @login_required
    @selectBySlugNS.doc(security=["login"])
    @selectBySlugNS.param("slug",
                          description="Order slug",
                          _in="path",
                          required=True)
示例#18
0
from flask import current_app as app
from requests import post

from backend.util.request.store.search_request import SearchRequest
from backend.util.response.store.search_results import SearchResultsResponse
from backend.util.response.error import ErrorResponse
from backend.controller import ErrorHandler
from backend.errors.no_content_error import NoContentError
from backend.errors.request_error import ValidationError

findNS = Namespace("Store", description="Store related operations.")

REQUESTMODEL = SearchRequest.get_model(findNS, "SearchRequest")
RESPONSEMODEL = SearchResultsResponse.get_model(findNS,
                                                "SearchResultsResponse")
ERRORMODEL = ErrorResponse.get_model(findNS, "ErrorResponse")


@findNS.route("/find/<string:ftype>/<string:arg>/", strict_slashes=False)
class FinderController(Resource):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__url = app.config["WILLSTORES_WS"]
        self.__headers = {
            "Authorization": "Bearer %s" % os.getenv("ACCESS_TOKEN")
        }
        self.__finder_types = ["search", "brand", "kind"]

    @findNS.param(
        "ftype",
        description="The product finder type: 'search', 'kind' or 'brand'",
示例#19
0
from flask_restplus import Namespace, Resource
from flask import current_app as app
from requests import Session

from backend.service import OrderService
from backend.util.request.user_orders import UserOrdersRequest
from backend.util.response.user_orders import UserOrdersResponse
from backend.util.response.error import ErrorResponse
from backend.controller import ErrorHandler, auth_required

selectByUserNS = Namespace("Order", description="Order related operations.")

REQUESTMODEL = UserOrdersRequest.get_model(selectByUserNS, "UserOrdersRequest")
RESPONSEMODEL = UserOrdersResponse.get_model(selectByUserNS,
                                             "UserOrdersResponse")
ERRORMODEL = ErrorResponse.get_model(selectByUserNS, "ErrorResponse")


async def fetch_order(session, url, order):
    req = session.post(
        "%s/api/product/total" % (url),
        json={"item_list": [item.to_dict() for item in order.items]})
    req.raise_for_status()
    processed_order = order.to_dict()
    processed_order.update(req.json())
    return processed_order


async def process_orders(session, url, user_info):
    orders = await asyncio.gather(
        *[fetch_order(session, url, order) for order in user_info["orders"]])