Ejemplo n.º 1
0
Archivo: news.py Proyecto: deti/boss
    def publish(self, news, publish):
        """
        Publishes and unpublishes news with specified id

        :param news: News' id
        :param Bool publish: what to do with news - publish or unpublish
        :return dict news_info: News' info

        **Example**::

            {"news_info":
                {"news_id": 1,
                 "subject": "test subject",
                 "body": "test body",
                 "deleted": None,
                 "published": 2015-06-15T16:24:47
                }
            }
        """
        if news.deleted:
            raise errors.RemovedNews()
        news.publish(publish)
        if publish:
            self.send_email_with_news(news.subject, news.body)
        return {"news_info": display(news)}
Ejemplo n.º 2
0
    def publish(self, news, publish):
        """
        Publishes and unpublishes news with specified id

        :param news: News' id
        :param Bool publish: what to do with news - publish or unpublish
        :return dict news_info: News' info

        **Example**::

            {"news_info":
                {"news_id": 1,
                 "subject": "test subject",
                 "body": "test body",
                 "deleted": None,
                 "published": 2015-06-15T16:24:47
                }
            }
        """
        if news.deleted:
            raise errors.RemovedNews()
        news.publish(publish)
        if publish:
            self.send_email_with_news(news.subject, news.body)
        return {"news_info": display(news)}
Ejemplo n.º 3
0
    def login(self, email, password, return_user_info=False):
        """
        Auth user by email and password. This method setup cookie which can be used in next requests.

        :param Email email: User Email_.
        :param str password: User password (flat text).
        :param Bool return_user_info: Return user info of logged user.

        :return dict user_info: User info

        **Example**::

            {
                "user_info": {
                    {"name": "Super Admin",
                     "deleted": null,
                     "email": "*****@*****.**",
                     "role": {'localized_name': {'en': 'Administrator', 'ru': 'Администратор'},
                              'role_id': 'admin'}
                     "created": "2015-04-24T11:14:22"}
                }
            }

        """
        new_token, user_info = User.login(email, password)
        setattr(local_properties, 'user_token', new_token)
        cookie_flags = {"httponly": True}
        if conf.api.secure_cookie and not conf.test:
            cookie_flags["secure"] = True
        bottle.response.set_cookie(ADMIN_TOKEN_NAME, new_token.id, path="/", **cookie_flags)
        user_info = display(user_info) if return_user_info else {}
        return {"user_info": user_info}
Ejemplo n.º 4
0
Archivo: news.py Proyecto: deti/boss
    def update_news(self, news, all_parameters, subject=None, body=None):
        """
        Updates news with specified subject and body

        :param news: News' id
        :param subject: subject to update
        :param body: body to update
        :return dict news_info: News' info

        **Example**::

            {"news_info":
                {"news_id": 1,
                 "subject": "test subject",
                 "body": "test body",
                 "deleted": None,
                 "published": None
                }
            }

        """
        if news.deleted:
            raise errors.RemovedNews()
        all_parameters.pop('news', None)
        news.update(all_parameters)
        return {"news_info": display(news)}
Ejemplo n.º 5
0
    def update_news(self, news, all_parameters, subject=None, body=None):
        """
        Updates news with specified subject and body

        :param news: News' id
        :param subject: subject to update
        :param body: body to update
        :return dict news_info: News' info

        **Example**::

            {"news_info":
                {"news_id": 1,
                 "subject": "test subject",
                 "body": "test body",
                 "deleted": None,
                 "published": None
                }
            }

        """
        if news.deleted:
            raise errors.RemovedNews()
        all_parameters.pop('news', None)
        news.update(all_parameters)
        return {"news_info": display(news)}
Ejemplo n.º 6
0
 def display(self, short=True):
     res = super().display(short)
     res["account"] = self.account_dict()
     res["currency"] = self.tariff.currency
     res["tariff_id"] = self.tariff_id
     auto_report_task = ScheduledTask.get_by_customer(self.customer_id, self.AUTO_REPORT_TASK)
     res["withdraw_date"] = auto_report_task.next_scheduled if auto_report_task else None
     res["detailed_info"] = self.info.display(short) if self.info else {}
     res["promo_code"] = display(PromoCode.get_by_customer_id(self.customer_id))
     return res
Ejemplo n.º 7
0
    def make_default(self, tariff):
        """
        Make tariff default

        :param ID tariff: Tariff ID

        :return dict tariff_info: Returns dict with tariff description.

        """
        tariff.make_default()
        return {"tariff_info": display(tariff)}
Ejemplo n.º 8
0
Archivo: service.py Proyecto: deti/boss
    def immutable(self, service):
        """
        Make service immutable.

        :param Id service: Service Id.
        :return dict service_info: Dict as returned
        by :obj:`GET /0/service/\<service\>/ <view.GET /0/service/\<service\>>`
        """
        service.mark_immutable()

        return {"service_info": display(service)}
Ejemplo n.º 9
0
    def get_default(self):
        """
        Get description of default tariff

        :return dict tariff_info: Returns dict with tariff description.

        """
        tariff = Tariff.get_default().first()
        if not tariff:
            raise errors.TariffNotFound()
        return {"tariff_info": display(tariff)}
Ejemplo n.º 10
0
    def immutable(self, service):
        """
        Make service immutable.

        :param Id service: Service Id.
        :return dict service_info: Dict as returned
        by :obj:`GET /0/service/\<service\>/ <view.GET /0/service/\<service\>>`
        """
        service.mark_immutable()

        return {"service_info": display(service)}
Ejemplo n.º 11
0
    def immutable(self, token, tariff):
        """
        Update tariff.

        :param Id tariff: Tariff Id.
        :return dict tariff_info: Dict as returned by :obj:`GET /0/tariff/\<tariff\>/ <view.GET /0/tariff/\<tariff\>>`
        """
        if tariff.mark_immutable():
            TariffHistory.create(TariffHistory.EVENT_IMMUTABLE, token.user_id, tariff)

        return {"tariff_info": display(tariff)}
Ejemplo n.º 12
0
Archivo: service.py Proyecto: deti/boss
    def new_vm(self, flavor_id, vcpus, ram, disk, localized_name, network=None, description=None):
        """
        Add new flavor service.

        Parameters must be sent as json object.

        :param LocalizedName localized_name: Dict with name localization. en is mandatory key
                ``{"en": "Name", "ru": "\u0418\u043c\u044f"}``
        :param LocalizedName description: Dict with localized description. (Not mandatory)
        :param flavor_id: Flavor name
        :param vcpus: Number of flavor's vcpus
        :param ram: flavor's RAM amount
        :param disk: flavor's disk size
        :param network: flavor's network

        **Example**::

            {"service_info":
                {
                    "mutable": true,
                    "localized_name": {
                        "ru": "\u0424\u043b\u0430\u0432\u043e\u0440 TestFlavor",
                        "en": "Flavor TestFlavor"
                    },
                    "deleted": null,
                    "measure": {
                        "localized_name": {
                            "ru": "\u0447\u0430\u0441",
                            "en": "hour"
                        },
                        "measure_type": "time",
                        "measure_id": "hour"
                    },
                    "category": {
                        "localized_name": {
                            "ru": "\u0412\u0438\u0440\u0442\u0443\u0430\u043b\u044c\u043d\u044b\u0435 \u043c\u0430\u0448\u0438\u043d\u044b",
                            "en": "Virtual server"
                        },
                        "category_id": "vm"
                    },
                    "service_id": 1,
                    "description": {}
                }
            }

        """
        flavor_info = dict(flavor_id=flavor_id, vcpus=vcpus, ram=ram, disk=disk, network=network)
        mutable = True
        if self.check_flavor_existence(flavor_info):
            mutable = False
        flavor = Service.create_vm(localized_name, description, flavor_info, mutable)
        return {"service_info": display(flavor)}
Ejemplo n.º 13
0
    def fetch_tariff_history_list(self, tariff, date_before=None, date_after=None):
        """
        Returns list of changes for tariff

        :param ID tariff: Tariff ID
        :param Date date_before: Returns events which were happened before this date
        :param Date date_after: Returns events which were happened after this date

        :return List tariff_history_list: tariff operations list.

        """

        return {"tariff_history": display(tariff.get_history(date_before, date_after), short=True)}
Ejemplo n.º 14
0
    def get_others_info(self, user_id):
        """
        returns user info

        :param user user_id: user id

        :return dict user_info: the dict has the same structure as result of
                                method :obj:`get /0/user/me/ <view.get /0/user/me>`
        """
        user = User.get_by_id(user_id)
        if user is None:
            raise errors.UserNotFound()
        return {"user_info": display(user)}
Ejemplo n.º 15
0
    def paginate_services(services, limit, page):
        services = display(services)
        total = len(services)

        paginated_list = services[(page - 1) * limit:page * limit]

        res = {
            'per_page': limit,
            'total': total,
            'page': page,
            'items': paginated_list
        }
        return res
Ejemplo n.º 16
0
Archivo: service.py Proyecto: deti/boss
    def paginate_services(services, limit, page):
        services = display(services)
        total = len(services)

        paginated_list = services[(page - 1) * limit:page * limit]

        res = {
            'per_page': limit,
            'total': total,
            'page': page,
            'items': paginated_list
        }
        return res
Ejemplo n.º 17
0
def homepage():
    """Geeft de homepagina weer."""

    # Als de gebruiker via POST kwam.
    if request.method == "POST":

        # Naar approute comment gaan als er op comment geklikt is.
        if request.form.get("comment"):
            session["image_id"] = request.form.get("comment")
            return redirect(url_for("comment"))

        # Foto's weergeven.
        else:
            pictures = model.display()
            get_comment = model.get_comments()
            return render_template("homepage.html", images=pictures, comments=get_comment)

    # Als de gebruiker via GET de route bereikt heeft.
    else:
        pictures = model.display()
        get_comment = model.get_comments()
        return render_template("homepage.html", images=pictures, comments=get_comment)
Ejemplo n.º 18
0
    def fetch_tariff_history_item(self, tariff, history):
        """
        Returns list of changes for tariff

        :param ID tariff: Tariff ID

        :return List tariff_history_list: Changes list for the tariff

        """
        history = tariff.history.filter(TariffHistory.history_id == history).first()
        if not history:
            raise errors.TariffHistoryNotFound()

        return {"tariff_history_info": display(history, short=False)}
Ejemplo n.º 19
0
Archivo: service.py Proyecto: deti/boss
    def service_category_list(self):
        """
        Returns list of categories with localized names

        :return list category_list: List of dict with category

        **Example**::

             {"category_list": [
                {"category_id": "net", "localized_name": {"ru": "Сеть", "en": "Network"}},
                {"category_id": "storage", "localized_name": {"ru": "Хранение данных", "en": "Storage"}},
                {"category_id": "vm", "localized_name": {"ru": "Виртуальные машины", "en": "Virtual machine"}},
                {"category_id": "custom", "localized_name": {"ru": "Дополнительные", "en": "Custom"}}]}

        """
        return {"category_list": display(Category.list().values())}
Ejemplo n.º 20
0
    def service_category_list(self):
        """
        Returns list of categories with localized names

        :return list category_list: List of dict with category

        **Example**::

             {"category_list": [
                {"category_id": "net", "localized_name": {"ru": "Сеть", "en": "Network"}},
                {"category_id": "storage", "localized_name": {"ru": "Хранение данных", "en": "Storage"}},
                {"category_id": "vm", "localized_name": {"ru": "Виртуальные машины", "en": "Virtual machine"}},
                {"category_id": "custom", "localized_name": {"ru": "Дополнительные", "en": "Custom"}}]}

        """
        return {"category_list": display(Category.list().values())}
Ejemplo n.º 21
0
    def measure_list(self, measure_type=None):
        """
        Returns list of measures

        :param String measure_type: Return measures only specified type. It can be "time", "quant" or 'time_quant'
        :return list measure_list: List of dict with measure info

        **Example**::

            {
                "measure_list": [
                   {"measure_type": "time", "localized_name": {"ru": "час", "en": "hour"}, "measure_id": "hour"},
                   {"measure_type": "time", "localized_name": {"ru": "месяц", "en": "month"}, "measure_id": "month"}
                ]
            }
        """
        return {"measure_list": display(Measure.list(measure_type))}
Ejemplo n.º 22
0
Archivo: service.py Proyecto: deti/boss
    def measure_list(self, measure_type=None):
        """
        Returns list of measures

        :param String measure_type: Return measures only specified type. It can be "time", "quant" or 'time_quant'
        :return list measure_list: List of dict with measure info

        **Example**::

            {
                "measure_list": [
                   {"measure_type": "time", "localized_name": {"ru": "час", "en": "hour"}, "measure_id": "hour"},
                   {"measure_type": "time", "localized_name": {"ru": "месяц", "en": "month"}, "measure_id": "month"}
                ]
            }
        """
        return {"measure_list": display(Measure.list(measure_type))}
Ejemplo n.º 23
0
Archivo: service.py Proyecto: deti/boss
    def update_custom(self, service, localized_name=None, description=None, measure=None):
        """
        Update custom service. (only custom services can be updated)

        Parameters must be sent as json object.

        :param Id service: Service Id
        :param LocalizedName localized_name: Dict with name localization. en is mandatory key
                ``{"en": "Name", "ru": "\u0418\u043c\u044f"}``
        :param LocalizedName description: Dict with localized description.
        :param Measure measure: Measure id. Only time measure is possible.

        :return dict service_info: Dict as returned by
                                  :obj:`GET /0/service/\<service\>/ <view.GET /0/service/\<service\>>`
        """
        updated = service.update_custom(localized_name, description, measure)

        return {"service_info": display(service)}
Ejemplo n.º 24
0
Archivo: service.py Proyecto: deti/boss
    def get_service(self, service_id):
        """
        Return service description

        :param Id service_id: Service Id

        :return dict service_info: Dict with service parameters

        **Example**::

            {
              "service_info": {
                "service_id": "storage.volume",
                "measure": {
                  "measure_type": "time_quant",
                  "measure_id": "gigabyte*month",
                  "localized_name": {
                    "ru": "Гб*месяц",
                    "en": "Gb*month"
                  }
                },
                "category": {
                  "localized_name": {
                    "ru": "Хранение данных",
                    "en": "Storage"
                  },
                  "category_id": "storage"
                },
                "localized_name": {
                  "ru": "Диск",
                  "en": "Volume"
                }
              }
            }

        """

        service = Service.get_by_id(service_id)
        if not service:
            raise errors.ServiceNotFound()

        return {"service_info": display(service)}
Ejemplo n.º 25
0
    def new_custom_service(self, localized_name, measure, description=None):
        """
        Add new custom service.

        Parameters must be sent as json object.

        :param LocalizedName localized_name: Dict with name localization. en is mandatory key
                ``{"en": "Name", "ru": "\u0418\u043c\u044f"}``
        :param LocalizedName description: Dict with localized description. (Not mandatory)
        :param Measure measure: Measure id. Only time measure is possible.

        **Example**::

            {"service_info":
                {
                    "mutable": true,
                    "localized_name": {
                        "ru": "",
                        "en": "Test Custom Service"
                    },
                    "deleted": null,
                    "measure": {
                        "localized_name": {
                            "ru": "\u0447\u0430\u0441",
                            "en": "hour"
                        },
                        "measure_type": "time",
                        "measure_id": "hour"
                    },
                    "category": {
                        'localized_name':
                            {'ru': 'Дополнительные', 'en': 'Custom'},
                            'category_id': 'custom'
                        },
                    "service_id": 1,
                    "description": {}
                }
            }

        """
        service = Service.create_custom(localized_name, measure, description)
        return {"service_info": display(service)}
Ejemplo n.º 26
0
Archivo: service.py Proyecto: deti/boss
    def new_custom_service(self, localized_name, measure, description=None):
        """
        Add new custom service.

        Parameters must be sent as json object.

        :param LocalizedName localized_name: Dict with name localization. en is mandatory key
                ``{"en": "Name", "ru": "\u0418\u043c\u044f"}``
        :param LocalizedName description: Dict with localized description. (Not mandatory)
        :param Measure measure: Measure id. Only time measure is possible.

        **Example**::

            {"service_info":
                {
                    "mutable": true,
                    "localized_name": {
                        "ru": "",
                        "en": "Test Custom Service"
                    },
                    "deleted": null,
                    "measure": {
                        "localized_name": {
                            "ru": "\u0447\u0430\u0441",
                            "en": "hour"
                        },
                        "measure_type": "time",
                        "measure_id": "hour"
                    },
                    "category": {
                        'localized_name':
                            {'ru': 'Дополнительные', 'en': 'Custom'},
                            'category_id': 'custom'
                        },
                    "service_id": 1,
                    "description": {}
                }
            }

        """
        service = Service.create_custom(localized_name, measure, description)
        return {"service_info": display(service)}
Ejemplo n.º 27
0
    def get_service(self, service_id):
        """
        Return service description

        :param Id service_id: Service Id

        :return dict service_info: Dict with service parameters

        **Example**::

            {
              "service_info": {
                "service_id": "storage.volume",
                "measure": {
                  "measure_type": "time_quant",
                  "measure_id": "gigabyte*month",
                  "localized_name": {
                    "ru": "Гб*месяц",
                    "en": "Gb*month"
                  }
                },
                "category": {
                  "localized_name": {
                    "ru": "Хранение данных",
                    "en": "Storage"
                  },
                  "category_id": "storage"
                },
                "localized_name": {
                  "ru": "Диск",
                  "en": "Volume"
                }
              }
            }

        """

        service = Service.get_by_id(service_id)
        if not service:
            raise errors.ServiceNotFound()

        return {"service_info": display(service)}
Ejemplo n.º 28
0
    def new_tariff(self, token, localized_name, description, currency,
                   services=None, parent_id=None, all_parameters=None):
        """
        Create new tariff.

        Parameters must be sent as json object.

        :param LocalizedName localized_name: Dict with name localization. en is mandatory key
                ``{"en": "Name", "ru": "\u0418\u043c\u044f"}``
        :param str description: Tariff description
        :param str currency: Currency code
        :param TariffId parent_id: Parent tariff id
        :param list services: List services and its prices

            **Example of list**::

                    services: [
                        {
                            "service_id": "m1.small",
                            "price": "12.23"
                        },
                        {
                            "service_id": "m1.medium",
                            "price": "21.32"
                        }
                    ]
                }

        :return dict tariff_info: Dict as returned by :obj:`GET /0/tariff/\<tariff\>/ <view.GET /0/tariff/\<tariff\>>`
        """
        if parent_id:
            parent = Tariff.get_by_id(parent_id)
            if not parent:
                raise errors.TariffNotFound()
            if parent.currency != currency:
                raise errors.ParentTariffCurrency()

        created = Tariff.create_tariff(**all_parameters)
        TariffHistory.create(TariffHistory.EVENT_CREATE, token.user_id, created)
        return {"tariff_info": display(created)}
Ejemplo n.º 29
0
    def create_news(self, subject, body):
        """
        Creates news

        :param subject: News' subject
        :param body: News' body
        :return dict news_info: News' info

        **Example**::

            {"news_info":
                {"news_id": 1,
                 "subject": "test subject",
                 "body": "test body",
                 "deleted": None,
                 "published": None
                }
            }

        """
        news = News.create_news(subject, body)
        return {"news_info": display(news)}
Ejemplo n.º 30
0
    def new_user(self, token, email, role, password=None, name=None):
        """
        Registration of new user.

        :param Email email: User email (Email_);
        :param str password: User Password. If the it is empty then the password
                             recovery email will be sent to the email.
        :param str role: User role.
        :param str name: User display name [optional]

        :returns dict user_info: User info.

        **Example**::

            {
                "user_info": {
                    {"name": "Super Admin",
                     "deleted": null,
                     "email": "*****@*****.**",
                     "role": {'localized_name': {'en': 'Administrator', 'ru': 'Администратор'},
                              'role_id': 'admin'}
                     "created": "2015-04-24T11:14:22"}
                }
            }

        """
        if not Role.validate(token.role, role):
            raise errors.UserInvalidRole()

        if token.role != Role.ADMIN and token.role == role:
            # user can administrate only users with low priority
            raise errors.UserInvalidRole()

        user_info = User.new_user(email, password, role, name=name)

        if not password:
            self.send_password_reset_email(email, request_base_url(), for_new_user=True)

        return {"user_info": display(user_info)}
Ejemplo n.º 31
0
Archivo: news.py Proyecto: deti/boss
    def create_news(self, subject, body):
        """
        Creates news

        :param subject: News' subject
        :param body: News' body
        :return dict news_info: News' info

        **Example**::

            {"news_info":
                {"news_id": 1,
                 "subject": "test subject",
                 "body": "test body",
                 "deleted": None,
                 "published": None
                }
            }

        """
        news = News.create_news(subject, body)
        return {"news_info": display(news)}
Ejemplo n.º 32
0
    def update_tariff(self, token, tariff, localized_name=None, description=None,
                      currency=None, services=None, all_parameters=None):
        """
        Update tariff.

        Parameters must be sent as json object.

        :param Id tariff: Tariff Id.
        :param LocalizedName localized_name: Dict with name localization. en is mandatory key
                ``{"en": "Name", "ru": "\u0418\u043c\u044f"}``
        :param str description: Tariff description.
        :param str currency: Currency.
        :param list services: List services and its prices

        :return dict tariff_info: Dict as returned by :obj:`GET /0/tariff/\<tariff\>/ <view.GET /0/tariff/\<tariff\>>`
        """
        all_parameters.pop("tariff")
        updated = tariff.update(**all_parameters)
        if updated:
            TariffHistory.create(TariffHistory.EVENT_UPDATE, token.user_id, tariff)

        return {"tariff_info": display(tariff)}
Ejemplo n.º 33
0
    def update_custom(self,
                      service,
                      localized_name=None,
                      description=None,
                      measure=None):
        """
        Update custom service. (only custom services can be updated)

        Parameters must be sent as json object.

        :param Id service: Service Id
        :param LocalizedName localized_name: Dict with name localization. en is mandatory key
                ``{"en": "Name", "ru": "\u0418\u043c\u044f"}``
        :param LocalizedName description: Dict with localized description.
        :param Measure measure: Measure id. Only time measure is possible.

        :return dict service_info: Dict as returned by
                                  :obj:`GET /0/service/\<service\>/ <view.GET /0/service/\<service\>>`
        """
        updated = service.update_custom(localized_name, description, measure)

        return {"service_info": display(service)}
Ejemplo n.º 34
0
    def update_vm(self,
                  token,
                  service,
                  localized_name=None,
                  description=None,
                  flavor_id=None,
                  vcpus=None,
                  ram=None,
                  disk=None,
                  network=None):
        """
        Update Flavor.

        Parameters must be sent as json object.

        :param ServiceId service: Service Id
        :param LocalizedName localized_name: Dict with name localization. en is mandatory key
                ``{"en": "Name", "ru": "\u0418\u043c\u044f"}``
        :param LocalizedName description: Dict with localized description.
        :param flavor_id: Flavor name
        :param vcpus: Number of flavor's vcpus
        :param ram: flavor's RAM amount
        :param disk: flavor's disk size
        :param network: flavor's network

        :return dict service_info: Dict as returned by
                                  :obj:`GET /0/service/\<service\>/ <view.GET /0/service/\<service\>>`
        """
        flavor_info = dict(flavor_id=flavor_id,
                           vcpus=vcpus,
                           ram=ram,
                           disk=disk,
                           network=network)
        service.update_vm(localized_name, description, flavor_info)

        return {"service_info": display(service)}
Ejemplo n.º 35
0
Archivo: service.py Proyecto: deti/boss
    def update_vm(self, token, service, localized_name=None, description=None,
                  flavor_id=None, vcpus=None, ram=None, disk=None, network=None):
        """
        Update Flavor.

        Parameters must be sent as json object.

        :param ServiceId service: Service Id
        :param LocalizedName localized_name: Dict with name localization. en is mandatory key
                ``{"en": "Name", "ru": "\u0418\u043c\u044f"}``
        :param LocalizedName description: Dict with localized description.
        :param flavor_id: Flavor name
        :param vcpus: Number of flavor's vcpus
        :param ram: flavor's RAM amount
        :param disk: flavor's disk size
        :param network: flavor's network

        :return dict service_info: Dict as returned by
                                  :obj:`GET /0/service/\<service\>/ <view.GET /0/service/\<service\>>`
        """
        flavor_info = dict(flavor_id=flavor_id, vcpus=vcpus, ram=ram, disk=disk, network=network)
        service.update_vm(localized_name, description, flavor_info)

        return {"service_info": display(service)}
Ejemplo n.º 36
0
    def get_info(self, token):
        """
        Return user info of current user.

        :return dict user_info: User info

        **Example**::

            {
                "user_info": {
                    {"name": "Super Admin",
                     "deleted": null,
                     "email": "*****@*****.**",
                     "role": {'localized_name': {'en': 'Administrator', 'ru': 'Администратор'},
                              'role_id': 'admin'}
                     "created": "2015-04-24T11:14:22"}
                }
            }
        """
        user = User.get_by_id(token.user_id)
        if user is None:
            logbook.debug("User not found by id {}", token.user_id)
            raise errors.UserInvalidToken()
        return {"user_info": display(user)}
Ejemplo n.º 37
0
 def paginated_list(pagination, short_display=False):
     from model import display
     return {"total": pagination.total, "page": pagination.page, "per_page": pagination.per_page,
             "items": display(pagination.items, short_display)}
Ejemplo n.º 38
0
def game_loop():
    current_username = ''
    condition = True
    while 1:
        user_choice = view.log_or_sign()
        user_choice = user_choice.lower()
        log_in = ['l', 'login']
        create_ = ['c', 'create']
        exit_ = ['e', 'exit']
        accept_input = log_in     \
                      +create_     \
                      +exit_
        if user_choice in accept_input:
            if user_choice in log_in:
                (user_name, password) = view.log_menu()
                current_username = user_name
                has_account = model.log_in(user_name, password)
                if has_account:
                    break
                else:
                    print('WRONG LOGIN INFORMATION. TRY AGAIN')
                    import time
                    time.sleep(3)
            elif user_choice in exit_:
                condition = False
                break
                os.system('clear')
            elif user_choice in create_:
                #(new_user,new_password,new_funds) = view.create_menu()
                #       new_user = input("username:"******"password:"******"""INSERT INTO user(
                        username,
                        password,
                        current_balance
                    ) VALUES(?,?,?
                    )""", newuser)
                connection.commit()
                cursor.close()
                connection.close()

                print("You have signed up!")
                import time
                time.sleep(3)

    while condition:
        fund_inputs = ['f', 'fund']
        buy_inputs = ['b', 'buy']
        sell_inputs = ['s', 'sell']
        lookup_inputs = ['l', 'lookup']
        quote_inputs = ['q', 'quote']
        display_inputs = ['d', 'display']
        exit_inputs = ['e', 'exit']
        acceptable_inputs = fund_inputs    \
                            +buy_inputs    \
                            +sell_inputs   \
                            +lookup_inputs \
                            +quote_inputs  \
                            +display_inputs \
                            +exit_inputs
        user_input = view.main_menu()
        if user_input in acceptable_inputs:
            if user_input in fund_inputs:
                confirmation, fund_amount = view.fund_menu(
                )  #TODO add fund_menu to view
                if confirmation:
                    return_balance = model.fund(
                        fund_amount, current_username)  #TODO add fund to model
                    print("Your current balance is: $%.2f" % (return_balance))
                else:
                    print("You entered a invalid input. Please try again.")
            elif user_input in buy_inputs:
                (ticker_symbol, trade_volume) = view.buy_menu()
                confirmation_message, return_list = model.buy(
                    current_username, ticker_symbol, trade_volume)
                if confirmation_message == True:
                    yes = ['y', 'yes']
                    no = ['n', 'no']
                    choice = input(
                        "You have enough money. Would you like to buy this stock?\n[y] Yes\n[n] No\n"
                    )
                    if choice in yes:
                        model.buy_db(return_list)
                    else:
                        print("Returning to main menu.")
                else:
                    print("You do not have enough money to buy this stock.")
            elif user_input in sell_inputs:
                (ticker_symbol, trade_volume) = view.sell_menu()
                confirmation_message, return_list = model.sell(
                    current_username, ticker_symbol, trade_volume)  #TODO
                if confirmation_message == True:
                    yes = ['y', 'yes']
                    no = ['n', 'no']
                    choice = input(
                        "You have enough shares to sell. Would you like to sell this stock?\n[y] Yes\n[n] No\n"
                    )
                    if choice.lower() in yes:
                        model.sell_db(return_list)  #TODO
                    else:
                        print("Returning to main menu.")
                else:
                    print("You do not have enough shares to sell.")

            elif user_input in lookup_inputs:
                company_name = view.lookup_menu()
                print(model.lookup_ticker_symbol(company_name))
            elif user_input in quote_inputs:
                #TODO
                ticker_symbol = view.quote_menu()
                print(model.quote_last_price(ticker_symbol))
                #import time
                #time.sleep(5)
            elif user_input in display_inputs:
                model.display(current_username)
            elif user_input in exit_inputs:
                os.system('clear')
                break
            else:
                #catches huge error
                #should contain a fallback function
                pass
        else:
            pass
        model.updateHoldings()
        import time
        time.sleep(3)
Ejemplo n.º 39
0
    def fetch_tariff(self, tariff):
        """
        Returns tariff info

        :param ID tariff: Tariff ID
        :return dict tariff_info: Returns dict with tariff description.

        **Example**::

              "tariff_info": {
                "services": [
                  {
                    "price": "12.23",
                    "default": false,
                    "service": {
                      "service_id": "m1.small",
                      "category": {
                        "category_id": "vm",
                        "localized_name": {
                          "ru": "\u0412\u0438\u0440\u0442\u0443\u0430\u043b\u044c\u043d\u044b\u0435 \u043c\u0430\u0448\u0438\u043d\u044b",
                          "en": "Virtual machine"
                        }
                      },
                      "measure": {
                        "localized_name": {
                          "ru": "\u0447\u0430\u0441",
                          "en": "hour"
                        },
                        "measure_id": "hour",
                        "measure_type": "time"
                      },
                      "localized_name": {
                        "en": "m1.small",
                        "ru": "m1.small"
                      }
                    }
                  },
                  {
                    "price": "23.45",
                    "service": {
                      "service_id": "m1.medium",
                      "category": {
                        "category_id": "vm",
                        "localized_name": {
                          "ru": "\u0412\u0438\u0440\u0442\u0443\u0430\u043b\u044c\u043d\u044b\u0435 \u043c\u0430\u0448\u0438\u043d\u044b",
                          "en": "Virtual machine"
                        }
                      },
                      "measure": {
                        "localized_name": {
                          "ru": "\u0447\u0430\u0441",
                          "en": "hour"
                        },
                        "measure_id": "hour",
                        "measure_type": "time"
                      },
                      "localized_name": {
                        "en": "m1.medium",
                        "ru": "m1.medium"
                      }
                    }
                  }
                ],
                "deleted": null,
                "parent_id": null,
                "localized_name": {
                  "en": "Tariff Begin",
                  "ru": "\u0422\u0430\u0440\u0438\u0444\u0444 \u0411\u0435\u0433\u0438\u043d"
                },
                "created": "2015-05-26T18:09:02+00:00",
                "description": "\u0416\u0443\u0442\u043a\u043e \u0434\u043e\u0440\u043e\u0433\u043e\u0439 \u0442\u0430\u0440\u0438\u0444\u0444",
                "tariff_id": 1,
                "mutable": true,
                "currency": "rub"
              }
            }
        """
        # , expand_references_in_list=Tariff.expand_references_in_list
        return {"tariff_info": display(tariff)}
Ejemplo n.º 40
0
    def new_vm(self,
               flavor_id,
               vcpus,
               ram,
               disk,
               localized_name,
               network=None,
               description=None):
        """
        Add new flavor service.

        Parameters must be sent as json object.

        :param LocalizedName localized_name: Dict with name localization. en is mandatory key
                ``{"en": "Name", "ru": "\u0418\u043c\u044f"}``
        :param LocalizedName description: Dict with localized description. (Not mandatory)
        :param flavor_id: Flavor name
        :param vcpus: Number of flavor's vcpus
        :param ram: flavor's RAM amount
        :param disk: flavor's disk size
        :param network: flavor's network

        **Example**::

            {"service_info":
                {
                    "mutable": true,
                    "localized_name": {
                        "ru": "\u0424\u043b\u0430\u0432\u043e\u0440 TestFlavor",
                        "en": "Flavor TestFlavor"
                    },
                    "deleted": null,
                    "measure": {
                        "localized_name": {
                            "ru": "\u0447\u0430\u0441",
                            "en": "hour"
                        },
                        "measure_type": "time",
                        "measure_id": "hour"
                    },
                    "category": {
                        "localized_name": {
                            "ru": "\u0412\u0438\u0440\u0442\u0443\u0430\u043b\u044c\u043d\u044b\u0435 \u043c\u0430\u0448\u0438\u043d\u044b",
                            "en": "Virtual server"
                        },
                        "category_id": "vm"
                    },
                    "service_id": 1,
                    "description": {}
                }
            }

        """
        flavor_info = dict(flavor_id=flavor_id,
                           vcpus=vcpus,
                           ram=ram,
                           disk=disk,
                           network=network)
        mutable = True
        if self.check_flavor_existence(flavor_info):
            mutable = False
        flavor = Service.create_vm(localized_name, description, flavor_info,
                                   mutable)
        return {"service_info": display(flavor)}
Ejemplo n.º 41
0
 def update_user_common(user, all_parameters):
     if not all_parameters:
         raise errors.NothingForUpdate()
     user.update(all_parameters)
     return {"user_info": display(user)}