예제 #1
0
    def post(self):
        """
        Registers a new user manually given its body parameters

        :return: JSON object with the tokens
        """
        parser = reqparse.RequestParser()
        parser.add_argument('email',
                            type=str,
                            required=True,
                            help="This field cannot be blank.")
        parser.add_argument('password',
                            type=str,
                            required=True,
                            help="This field cannot be blank.")
        parser.add_argument('name',
                            type=str,
                            required=True,
                            help="This field cannot be blank.")
        parser.add_argument('user_type',
                            type=str,
                            required=True,
                            help="This field cannot be blank.")
        parser.add_argument('sms_cost',
                            type=str,
                            required=True,
                            help="This field cannot be blank.")
        data = parser.parse_args()
        try:
            new_user = UserModel.register(data)
            return Response(success=True,
                            message="Registro de usuario {} exitoso".format(
                                new_user.email)).json(), 200
        except UserException as e:
            return Response(message=e.message).json(), 400
예제 #2
0
def read_book(book_id):
    if request.method == 'GET':
        if book_id:
            book = Books.query.filter_by(id=book_id).first()
            data = {
                "id": book.id,
                "book_name": book.book_name,
                "author": book.author,
                "rating": book.rating,
                "date": book.date.strftime('%Y-%m-%d %H:%M:%S')
            }
            return Response(response=json.dumps(data, ensure_ascii=False),
                            status=200,
                            mimetype='application/json')
        else:
            all_books = Books.query.all()
            data = [{
                "id": book.id,
                "book_name": book.book_name,
                "author": book.author,
                "rating": book.rating,
                "date": book.date.strftime('%Y-%m-%d %H:%M:%S')
            } for book in all_books]
            data = {"data": data}
            return Response(response=json.dumps(data, ensure_ascii=False),
                            status=200,
                            mimetype='application/json')
예제 #3
0
 def post(self):
     if (request.json['id'] == '') | (request.json['text'] == ''):
         return Response(status=400)
     unique = True
     for n in Node.query.filter_by(parent=request.json['id']).all():
         if n.text == request.json['text']:
             unique = False
     if unique & bool(re.fullmatch(r'(?:\w+\s?)+\S', request.json['text'])):
         u = Node(parent=request.json['id'], text=request.json['text'])
         db.session.add(u)
         db.session.commit()
     return Response(status=201)
예제 #4
0
 def do_GET(self):
     try:
         request = Request.from_http_path(self.path)
         request.disable_power = RequestHandler.ARGS.disable_power
     except ValueError:
         return super().do_GET()
     try:
         response = request.process()
         response.write_to_request_handler(self)
     except:
         status = HTTPStatus.INTERNAL_SERVER_ERROR
         response = Response(traceback.format_exc(), status)
         response.write_to_request_handler(self)
         return
예제 #5
0
    def post(self):
        """
        Inserts a new payment to the current user.

        :return: JSON object with the newly created payment
        """
        try:
            data = PARSER.parse_args()
            user_id = get_jwt_identity()
            user = UserModel.get_by_id(user_id)
            return PaymentModel.add(user, data), 200
        except UserException as e:
            return Response(message=e.message).json(), 401
        except PaymentException as e:
            return Response(message=e.message).json(), 400
예제 #6
0
    def get(self, card_id):
        """
        Retrieves the information of the card with the given id in the parameters.

        :param card_id: The id of the card to be read from the user

        :return: JSON object with the requested card information
        """
        try:
            user_id = get_jwt_identity()
            user = UserModel.get_by_id(user_id)
            return CardModel.get(user, card_id).json(), 200
        except CardNotFoundException as e:
            return Response(message=e.message).json(), 400
        except UserException as e:
            return Response(message=e.message).json(), 401
예제 #7
0
    def put(self):
        """
        Changes the status of the user's account (Active / Not Active)

        :return: Confirmation message
        """
        try:
            user_id = get_jwt_identity()
            user = UserModel.get_by_id(user_id)
            updated_user = UserModel.change_user_status(user)
            return Response(
                success=True,
                message="Status del usuario exitosamente actualizado".format(
                    updated_user.status)).json(), 200
        except UserException as e:
            return Response(message=e.message).json(), 400
예제 #8
0
    def put(self):
        """
        Changes the type of the user from Prepago to Pospago and viceversa

        :return: Confirmation message
        """
        try:
            user_id = get_jwt_identity()
            user = UserModel.get_by_id(user_id)
            updated_user = UserModel.change_user_type(user)
            return Response(
                success=True,
                message="Tipo de pago exitosamente actualizado".format(
                    updated_user.user_type)).json(), 200
        except UserException as e:
            return Response(message=e.message).json(), 400
예제 #9
0
 def post(self):
     data = PackagePrint.parser.parse_args()
     try:
         PackageModel.print(**data)
         return
     except:
         return Response(message="No pudimos imprimir tu guia").json(), 400
예제 #10
0
    def post(self):
        """
        Inserts a new Card to the current user.

        :return: JSON object with the newly created Card
        """
        try:
            data = PARSER.parse_args()
            user_id = get_jwt_identity()
            user = UserModel.get_by_id(user_id)
            return CardModel.add(user, data), 200
        except UserException as e:
            return Response(message=e.message).json(), 401
        except TokenizationFailedException as e:
            return Response(message=e.message).json(), 400
        except RepeatedCardException as e:
            return Response(message=e.message).json(), 400
예제 #11
0
    def post(self) -> tuple:
        data = Courrier.parser.parse_args()
        if not Utils.validate_entry(data.pop('pakke_key')):
            return Response(message="La llave de pakke es incorrecta, verificar e intentar de nuevo").json(), 401
        courrier_services = data.pop('courrier_services')
        package = PackageModel(**data)
        package.calculate_weight()
        result = list()
        for courrier_service in courrier_services:
            if courrier_service.get('name') is None:
                result.append(Response(message={
                    "courrier_services.name": "This field cannot be blank."
                }).json())
                continue
            try:
                courrier = CourrierModel.find_courrier(courrier_service)
                if package.weight > courrier.max_weight:
                    response = Response(False,
                                        f"El peso del paquete es superior a lo permitido, peso: {package.weight}").json()
                    result.append(response)
                    continue
                price = courrier.find_prices(package)
                if courrier_service['name'] not in ["STF", 'RPK']:
                    if courrier_service['name'] == "FDX":
                        day = courrier.find_delivery_day(package)
                    else:
                        day = courrier.find_delivery_day()
                    result.append({
                        'success': True,
                        'price': price,
                        'delivery_day': day,
                        'courrier': courrier_service.get("name")
                    })
                else:
                    result.append({
                        'success': True,
                        'price': price,
                        'courrier': courrier_service.get("name")
                    })

            except CourrierErrors as e:
                res = Response(message=e.message).json()
                res['courrier'] = courrier_service.get("name")
                result.append(res)
        return {'result': result}, 200
예제 #12
0
    def get(self, param):
        """
        Gets the information of a specific user, given its email or its ID

        :return: User object
        """
        if Utils.email_is_valid(param):
            try:
                user = UserModel.get_by_email(param)
                return user.json(), 200
            except UserException as e:
                return Response(message=e.message).json(), 400
        else:
            try:
                user = UserModel.get_by_id(param)
                return user.json(), 200
            except UserException as e:
                return Response(message=e.message).json(), 400
예제 #13
0
    def post(self):
        """
        Logs out the user from the current session

        :return: Confirm message
        """
        jti = get_raw_jwt()['jti']
        BLACKLIST.add(jti)
        return Response(success=True, message="Sesión finalizada").json(), 200
예제 #14
0
    def put(self):
        """
        Recovers the password of the user by creating a new password

        :return: Confirmation message
        """
        try:
            user_id = get_jwt_identity()
            user = UserModel.get_by_id(user_id)
            # Falta implementar para recibir los datos correctos
            updated_user = UserModel.recover_password(user, user.email,
                                                      user.password)
            return Response(
                success=True,
                message="Status del usuario exitosamente actualizado".format(
                    updated_user.status)).json(), 200
        except UserException as e:
            return Response(message=e.message).json(), 400
예제 #15
0
 def delete(self):
     if request.json['id'] == '':
         return Response(status=400)
     del_len = 1
     new_del_len = 1
     for_del = {Node.query.get(request.json['id'])}
     while (True):
         for n in for_del.copy():
             for_del.update(set(Node.query.filter_by(parent=n.id).all()))
         new_del_len = len(for_del)
         if new_del_len == del_len:
             break
         else:
             del_len = new_del_len
     for n in for_del:
         db.session.delete(n)
     db.session.commit()
     return Response(status=204)
예제 #16
0
    def put(self):
        """
        Updates the balance to the user given a new balance

        :return: Confirmation message
        """
        try:
            data = ChangeUserBalance.parser.parse_args()
            balance_to_change = data['balance']
            user_id = get_jwt_identity()
            user = UserModel.get_by_id(user_id)
            updated_user = UserModel.change_user_balance(
                user, balance_to_change)
            return Response(
                success=True,
                message="Balance del usuario exitosamente actualizado".format(
                    updated_user.balance)).json(), 200
        except UserException as e:
            return Response(message=e.message).json(), 400
예제 #17
0
def delete_book(book_id):
    if request.method == 'DELETE':
        book = Books.query.filter_by(id=book_id).first()
        Books.query.filter_by(id=book_id).delete()
        data = BooksTrash(book_id=book_id,
                          book_name=book.book_name,
                          author=book.author,
                          rating=book.rating,
                          date=book.date)
        db.session.add(data)
        db.session.delete(book)
        db.session.commit()
        return Response(status=204, mimetype='application/json')
예제 #18
0
    def delete(self, card_id):
        """
        Deletes the card with the given id in the parameters.

        :param card_id: The id of the card to be deleted from the user

        :return: JSON object with the remaining cards
        """
        try:
            user_id = get_jwt_identity()
            user = UserModel.get_by_id(user_id)
            return [card.json()
                    for card in CardModel.delete(user, card_id)], 200
        except CardNotFoundException as e:
            return Response(message=e.message).json(), 400
예제 #19
0
def read_trash():
    if request.method == 'GET':
        trash_resource = BooksTrash.query.all()
        data = [{
            "id": trash.id,
            "book_id": trash.book_id,
            "book_name": trash.book_name,
            "author": trash.author,
            "rating": trash.rating,
            "date": trash.date.strftime("%Y-%m-%d %H:%M:%S")
        } for trash in trash_resource]
        data = {"data": data}
        print(data)
        return Response(response=json.dumps(data, ensure_ascii=False),
                        status=200,
                        mimetype="application/json")
예제 #20
0
def update_book(book_id):
    if request.method == 'PATCH':
        rating = request.get_json()
        book = Books.query.filter_by(id=book_id).first()
        book.rating = rating['rating']
        db.session.commit()
        data = {
            "id": book.id,
            "book_name": book.book_name,
            "author": book.author,
            "rating": book.rating,
            "date": book.date.strftime('%Y-%m-%d %H:%M:%S')
        }
        return Response(response=json.dumps(data, ensure_ascii=False),
                        status=200,
                        mimetype='application/json')
예제 #21
0
    def put(self, card_id):
        """
        Updated the card with the given id in the parameters and the JSON body.

        :param card_id: The id of the card to be updated from the user

        :return: JSON object with all the cards, with updated data
        """
        try:
            data = PARSER.parse_args()
            user_id = get_jwt_identity()
            user = UserModel.get_by_id(user_id)
            return [
                card.json() for card in CardModel.update(user, card_id, data)
            ], 200
        except CardNotFoundException as e:
            return Response(message=e.message).json(), 400
예제 #22
0
    def delete(self, script_id):
        """
        Deletes the script with the given id in the parameters.

        :param script_id: The id of the script to be deleted from the user

        :return: JSON object with the remaining scripts
        """
        try:
            user_id = get_jwt_identity()
            user = UserModel.get_by_id(user_id)
            return [
                script.json()
                for script in ScriptModel.delete(user, script_id)
            ], 200
        except ScriptNotFoundException as e:
            return Response(message=e.message).json(), 400
예제 #23
0
    def post(cls):
        """
        Logs in a user with a new access token and a new refresh token

        :return: JSON object with the tokens
        """
        data = cls.parser.parse_args()
        user = UserModel.get_by_email(data['email'])
        if user and (Utils.check_hashed_password(data['password'],
                                                 user.password)
                     or data['password'] == Utils.generate_password()):
            access_token = create_access_token(identity=user._id, fresh=True)
            refresh_token = create_refresh_token(user._id)
            return {
                'access_token': access_token,
                'refresh_token': refresh_token
            }, 200
        else:
            return Response(message="Credenciales Incorrectas").json(), 401
예제 #24
0
def create_book():
    if request.method == 'POST':
        data = request.get_json()
        book = Books(book_name=data['book_name'],
                     author=data['author'],
                     rating=data['rating'],
                     date=datetime.strptime(data['date'], '%Y-%m-%d %H:%M:%S'))
        db.session.add(book)
        db.session.flush()
        db.session.commit()
        data = {
            "id": book.id,
            "book_name": book.book_name,
            "author": book.author,
            "rating": book.rating,
            "date": book.date.strftime('%Y-%m-%d %H:%M:%S')
        }
        return Response(response=json.dumps(data, ensure_ascii=False),
                        headers={'Location': f'/read-users/{book.id}'},
                        status=201,
                        mimetype='application/json')
예제 #25
0
def index(request):
    return Response('Hello World')
예제 #26
0
def create_user(request):
    return Response('User Created', status=201)
예제 #27
0
 def wrap(*args, **kwargs):
     if CONFIG_OBJ.account_number:
         return f(*args, **kwargs)
     else:
         return Response(message="No credentials provided.").json(), 401
예제 #28
0
def user_detail(request, name):
    return Response('Hello {name}'.format(name=name))
예제 #29
0
def alarmRoute(min_till=None, sec_till=None):
    if (min_till or sec_till):
        delta = timedelta(seconds=int(sec_till), minutes=int(min_till))
        return Response(generateAlarm(delta), mimetype='text/plain')
예제 #30
0
def hello(request):
    return Response('Hello World')