Beispiel #1
0
    def post(self):
        """
        POST method for adding a new account
        """
        if not request.json:
            return create_error_response(415, "Unsupported media type",
                                         "Request must be JSON")
        try:
            validate(request.json, UserAccount.get_schema())
        except ValidationError as e:
            return create_error_response(400, "Invalid JSON document", str(e))
        try:
            useraccount = UserAccount(
                name=request.json["name"],
                password=request.json["password"],
            )
            pf = Portfolio(timestamp=datetime.now(), value=0.0)
            useraccount.portfolio = pf
            db.session.add(useraccount)
            db.session.add(pf)
            db.session.commit()

        except IntegrityError:
            return create_error_response(
                409, "Already exists",
                "User account with name {} already exists".format(
                    request.json["name"]))

        return Response(status=201,
                        headers={
                            "Location":
                            url_for("api.accountitem",
                                    account=request.json["name"])
                        })
Beispiel #2
0
    def put(self, account):
        """
        PUT method for editing account resource
        """
        single_account = UserAccount.query.filter_by(name=account).first()
        if single_account is None:
            return create_error_response(
                404, "Not found",
                "Account not found by name: {}".format(account))
        if not request.json:
            return create_error_response(415, "Unsupported media type",
                                         "Request content type must be JSON")

        try:
            validate(request.json, UserAccount.get_schema())
        except ValidationError as e:
            return create_error_response(400, "Invalid JSON document", str(e))

        single_account.name = request.json["name"]
        single_account.password = request.json["password"]

        try:
            db.session.commit()
        except IntegrityError:
            db.session.rollback()
            return create_error_response(
                409, "Already exists",
                "Account with given name already exists")

        return Response(status=204, mimetype=MASON)
Beispiel #3
0
    def post(self, account):
        """
        POST method for adding a new cryptocurrency to portfolio
        """
        if not request.json:
            return create_error_response(415, "Unsupported media type")
        try:
            validate(request.json, crypto_portfolio.get_schema())
        except ValidationError as e:
            return create_error_response(400, "Invalid json document", str(e))

        if float(request.json["currencyamount"]) <= 0:
            return create_error_response(400, "Invalid json document",
                                         "Currencyamount must be over zero")

        db_user = UserAccount.query.filter_by(name=account).first()
        db_portfolio = Portfolio.query.filter_by(
            id=db_user.portfolio_id).first()
        db_currency = CryptoCurrency.query.filter_by(
            abbreviation=request.json["currencyname"].upper()).first()
        if db_currency is None:
            return create_error_response(404, "Currency not found")
        pcurrency = crypto_portfolio(
            portfolio=db_portfolio,
            cryptocurrency=db_currency,
            currencyAmount=request.json["currencyamount"])

        try:
            db.session.add(pcurrency)
            db.session.commit()
        except IntegrityError:
            return create_error_response(409, "Already exists")

        # Find all pcurrencies from users portfolio
        db_pcurrencies = crypto_portfolio.query.filter_by(
            portfolio_id=db_portfolio.id).all()

        # Value of all pcurrencies in the portfolio
        total_amount = 0

        for pc in db_pcurrencies:
            coin = CryptoCurrency.query.filter_by(
                id=pc.cryptocurrency_id).first()
            total_amount = total_amount + (pc.currencyAmount * coin.value)

        # Updates the total value of the portfolio
        db_portfolio.value = total_amount
        db.session.commit()

        return Response(status=201,
                        headers={
                            "Location":
                            url_for("api.portfoliocurrency",
                                    account=account,
                                    pcurrency=request.json["currencyname"])
                        })
Beispiel #4
0
    def put(self, account, pcurrency):
        """
        PUT method for editing a portfoliocurrency
        """
        if not request.json:
            return create_error_response(415, "Unsupported media type",
                                         "Request body must be json")
        try:
            validate(request.json, crypto_portfolio.get_schema())
        except ValidationError as e:
            return create_error_response(400, "Invalid json body", str(e))

        if float(request.json["currencyamount"]) < 0:
            return create_error_response(400, "Invalid json body",
                                         "Currencyamount can't be negative")

        # Get the user's portfolio
        db_user = UserAccount.query.filter_by(name=account).first()
        db_portfolio = Portfolio.query.filter_by(
            id=db_user.portfolio_id).first()

        # Get the cryptocurrency
        db_currency = CryptoCurrency.query.filter_by(
            abbreviation=pcurrency.upper()).first()
        if db_currency is None:
            return create_error_response(404, "Currency doesn't exist")

        # Find the pcurrency from users portfolio
        db_pcurrencies = crypto_portfolio.query.filter_by(
            portfolio_id=db_portfolio.id).all()

        # Value of all pcurrencies in the portfolio
        total_amount = 0
        pfolio_currency = None
        for pc in db_pcurrencies:
            if pc.cryptocurrency_id == db_currency.id:
                pfolio_currency = pc
            else:
                coin = CryptoCurrency.query.filter_by(
                    id=pc.cryptocurrency_id).first()
                total_amount = total_amount + (pc.currencyAmount * coin.value)
        if pfolio_currency:
            total_amount = total_amount + request.json["currencyamount"]
            pfolio_currency.currencyAmount = request.json["currencyamount"]

            # Updates the total value of the portfolio
            db_portfolio.value = total_amount
            db.session.commit()
        else:
            return create_error_response(404, "Currency not in portfolio")
        return Response(status=204)
Beispiel #5
0
    def get(self, account, pcurrency):
        """
        GET method for getting a known cryptocurrency from portfolio
        """
        user = UserAccount.query.filter_by(name=account).first()
        if user is None:
            return create_error_response(404, "User not found")
        port = Portfolio.query.filter_by(id=user.portfolio_id).first()

        currency = CryptoCurrency.query.filter_by(
            abbreviation=pcurrency).first()

        if currency is None:
            return create_error_response(404, "Currency not found in system")

        pcurrencies = crypto_portfolio.query.filter_by(
            portfolio_id=port.id).all()
        pfolio_currency = None
        for pc in pcurrencies:
            if pc.cryptocurrency_id == currency.id:
                pfolio_currency = pc
                break
        if pfolio_currency is not None:
            body = CryptoMonitorBuilder(
                id=currency.id,
                name=currency.name,
                abbreviation=currency.abbreviation,
                timestamp=currency.timestamp.isoformat(),
                value=currency.value,
                daily_growth=currency.daily_growth,
                launchDate=currency.launchDate.isoformat(),
                blockchain_length=currency.blockchain_length,
                currencyAmount=pc.currencyAmount)
            body.add_namespace("crymo", LINK_RELATIONS_URL)
            body.add_control(
                "self",
                url_for("api.portfoliocurrency",
                        account=account,
                        pcurrency=pcurrency))
            body.add_control("profile", PCURRENCY_PROFILE)
            body.add_control(
                "collection",
                url_for("api.portfoliocurrencycollection", account=account))
            body.add_control_get_currency_info(currency.abbreviation)
            body.add_control_edit_pcurrency(account=account,
                                            pcurrency=pcurrency)
            body.add_control_delete_pcurrency(account, currency.abbreviation)
            return Response(json.dumps(body), status=200, mimetype=MASON)
        else:
            return create_error_response(404,
                                         "Currency not found in portfolio")
Beispiel #6
0
    def get(self, account):
        """
        GET method for getting single account
        """
        single_account = UserAccount.query.filter_by(name=account).first()
        if single_account is None:
            return create_error_response(
                404, "Not found",
                "Account not found by name: {}".format(account))

        body = CryptoMonitorBuilder(id=single_account.id,
                                    name=single_account.name,
                                    portfolio_id=single_account.portfolio_id,
                                    password=single_account.password)

        body.add_control("self", url_for("api.accountitem", account=account))
        body.add_control("profile", ACCOUNT_PROFILE)
        body.add_control("portfolio",
                         href=url_for("api.portfolioitem",
                                      account=single_account.name))
        body.add_control_all_accounts()
        body.add_control_edit_account(account=account)
        body.add_control_delete_account(account=account)
        body.add_namespace("crymo", LINK_RELATIONS_URL)

        return Response(response=json.dumps(body), status=200, mimetype=MASON)
Beispiel #7
0
    def delete(self, account):
        """
        DELETE method for deleting single account
        """
        single_account = UserAccount.query.filter_by(name=account).first()
        if single_account is None:
            return create_error_response(
                404, "Not found",
                "Account not found by name {}".format(account))
        db.session.delete(single_account)
        db.session.commit()

        return Response(status=204, mimetype=MASON)
Beispiel #8
0
    def delete(self, account, pcurrency):
        """
        DELETE method for removing pcurrency from the user's portfolio 
        """
        # Get the user's portfolio
        db_user = UserAccount.query.filter_by(name=account).first()
        db_portfolio = Portfolio.query.filter_by(
            id=db_user.portfolio_id).first()

        # Get the cryptocurrency
        db_currency = CryptoCurrency.query.filter_by(
            abbreviation=pcurrency).first()

        # Find the pcurrency from users portfolio
        db_pcurrencies = crypto_portfolio.query.filter_by(
            portfolio_id=db_portfolio.id).all()
        for pc in db_pcurrencies:
            if pc.cryptocurrency_id == db_currency.id:
                db.session.delete(pc)
                db.session.commit()

                # Find all pcurrencies from users portfolio
                db_pcurrencies = crypto_portfolio.query.filter_by(
                    portfolio_id=db_portfolio.id).all()

                # Value of all pcurrencies in the portfolio
                total_amount = 0

                for pc in db_pcurrencies:
                    coin = CryptoCurrency.query.filter_by(
                        id=pc.cryptocurrency_id).first()
                    total_amount = total_amount + (pc.currencyAmount *
                                                   coin.value)

                # Updates the total value of the portfolio
                db_portfolio.value = total_amount
                db.session.commit()

                return Response(status=204)
        return create_error_response(404,
                                     "Currency not found in user's portfolio")
Beispiel #9
0
    def get(self, account):
        """
        GET method for getting portfolio
        """
        db_user = UserAccount.query.filter_by(name=account).first()
        if db_user is None:
            return create_error_response(404, "Account doesn't exist")
        db_portfolio = Portfolio.query.filter_by(
            id=db_user.portfolio_id).first()
        body = CryptoMonitorBuilder(
            timestamp=db_portfolio.timestamp.isoformat(),
            value=db_portfolio.value)

        body.add_namespace("crymo", LINK_RELATIONS_URL)
        body.add_control("self",
                         href=url_for("api.portfolioitem",
                                      account=db_user.name))
        body.add_control("up",
                         href=url_for("api.accountitem", account=db_user.name))
        body.add_control_all_pcurrencies(db_user.name)
        body.add_control("profile", PORTFOLIO_PROFILE)
        return Response(response=json.dumps(body), status=200, mimetype=MASON)
Beispiel #10
0
    def get(self, account):
        """ 
        GET method for getting all cryptocurrencies in portfolio
        """
        # Get user
        db_user = UserAccount.query.filter_by(name=account).first()

        if db_user is None:
            return create_error_response(404, "User not found")

        # Get user's portfolio
        db_portfolio = Portfolio.query.filter_by(
            id=db_user.portfolio_id).first()

        # Get portfoliocurrencies
        db_pcurrencies = crypto_portfolio.query.filter_by(
            portfolio_id=db_portfolio.id).all()

        body = CryptoMonitorBuilder(items=[])
        body.add_namespace("crymo", LINK_RELATIONS_URL)
        base_uri = url_for("api.portfoliocurrencycollection", account=account)
        body.add_control("up", url_for("api.portfolioitem", account=account))
        body.add_control("self", base_uri)
        body.add_control_add_pcurrency(account)

        for pc in db_pcurrencies:
            db_currency = CryptoCurrency.query.filter_by(
                id=pc.cryptocurrency_id).first()
            item = CryptoMonitorBuilder(currencyamount=pc.currencyAmount,
                                        currencyname=db_currency.abbreviation)
            item.add_control(
                "self",
                url_for("api.portfoliocurrency",
                        account=account,
                        pcurrency=db_currency.abbreviation))
            item.add_control("profile", PCURRENCY_PROFILE)
            body['items'].append(item)
        return Response(json.dumps(body), status=200, mimetype=MASON)
Beispiel #11
0
    def get(self, currency):
        """
        GET method for getting single cryptocurrency
        """
        currencyitem = CryptoCurrency.query.filter_by(
            abbreviation=currency.upper()).first()
        if currencyitem is None:
            return create_error_response(404, "Currency not in database")

        body = CryptoMonitorBuilder(name=currencyitem.name,
                                    abbreviation=currencyitem.abbreviation,
                                    timestamp=currencyitem.timestamp,
                                    value=currencyitem.value,
                                    daily_growth=currencyitem.daily_growth)

        body.add_namespace("crymo", LINK_RELATIONS_URL)
        body.add_control(
            "self",
            url_for("api.cryptocurrencyitem",
                    currency=currencyitem.abbreviation))
        body.add_control_all_currencies()
        body.add_control_all_accounts()
        body.add_control("profile", CCURRENCY_PROFILE)
        return Response(json.dumps(body, default=str), 200, mimetype=MASON)