Ejemplo n.º 1
0
 def get_or_404(self, id, custom_message=None):
     data = self.get(id)
     if data is None:
         if custom_message is not None:
             raise BadRequest('{custom_message}: {id}'.format(
                 custom_message=custom_message, id=str(id)))
         raise BadRequest('Object does not exist: {id}'.format(id=str(id)))
     return data
Ejemplo n.º 2
0
def update(filename):
    if not storage.check_if_object_exists(filename):
        raise BadRequest('File not found')
    file = request.files['file'] if 'file' in request.files else None
    if file is None:
        raise BadRequest('Form data invalid')
    try:
        s3_object = storage.get_object(filename)
        s3_object.upload_fileobj(Fileobj=file,
                                 ExtraArgs={'ContentType': file.mimetype})
    except Exception as e:
        raise ApplicationError(str(e))
    return Response(file['Body'].read(), mimetype=file['ContentType'])
Ejemplo n.º 3
0
def upload_file_to_s3():
    file = request.files['file'] if 'file' in request.files else None
    if file is None:
        raise BadRequest('Form data invalid')
    if file.filename == '':
        raise BadRequest('Logo no selected file')
    if not allowed_file(file.filename):
        raise BadRequest('Extension is not allow')
    filename = get_filename(file.filename)
    try:
        storage.upload_file_obj(file, filename, file.mimetype)
    except Exception as e:
        raise ApplicationError(e)
    return generate_success_response(data={'filename': filename})
Ejemplo n.º 4
0
 def create(self, request, *args, **kwargs):
     """
     上传图片
     """
     img = request.FILES.get('img')
     if isinstance(img, InMemoryUploadedFile) or isinstance(
             img, TemporaryUploadedFile):
         ImageViewSet._img_type = 'file'
     else:
         img = request.data.get('img')
         if isinstance(img, str) and 'base64' in img:
             ImageViewSet._img_type = 'base64'
         else:
             raise BadRequest(HTTP_ERROR_CODE[4001])
     img, img_dir, img_name = self._generate_img_info(request)
     if not os.path.exists(img_dir):
         os.makedirs(img_dir)
     img_path = os.path.join(img_dir, img_name)
     with open(img_path, 'wb+') as img_destination:
         if self._img_type == 'base64':
             img_destination.write(
                 base64.decodebytes(bytes(img, encoding='utf-8')))
         else:
             for chunk in img.readlines():
                 img_destination.write(chunk)
     return Response({'path': img_path.split(settings.MEDIA_ROOT, 1)[-1]},
                     status=status.HTTP_201_CREATED)
Ejemplo n.º 5
0
    def generate(self, avatars, text, usernames, kwargs):
        avatar = BytesIO(http.get_content_raw(avatars[0]))
        try:
            img = image.Image(file=avatar)
        except Exception as e:
            raise BadRequest(f'The image could not be loaded: {e}')

        if img.animation:
            img = img.convert('png')
        img.transform(resize='400x400')

        try:
            multiplier = int(text)
        except ValueError:
            multiplier = 1
        else:
            multiplier = max(min(multiplier, 10), 1)

        img.liquid_rescale(width=int(img.width * 0.5),
                           height=int(img.height * 0.5),
                           delta_x=0.5 * multiplier,
                           rigidity=0)
        img.liquid_rescale(width=int(img.width * 1.5),
                           height=int(img.height * 1.5),
                           delta_x=2 * multiplier,
                           rigidity=0)

        b = BytesIO()
        img.save(file=b)
        b.seek(0)
        img.destroy()
        return send_file(b, mimetype='image/png')
Ejemplo n.º 6
0
 def filter_or_404(self, model, filter, custom_message=None):
     message_error = 'Object does not exist'
     if custom_message is not None and isinstance(custom_message, str):
         message_error = custom_message
     rv = self.find_by_filter(model, filter)
     if len(rv) == 0:
         raise BadRequest(message_error)
     return rv[0]
Ejemplo n.º 7
0
def get_file_from_s3(filename):
    if not storage.check_if_object_exists(filename):
        raise BadRequest('File not found')
    try:
        file = storage.get_object(filename).get()
    except Exception as e:
        raise ApplicationError(str(e))
    return Response(file['Body'].read(), mimetype=file['ContentType'])
Ejemplo n.º 8
0
def get_datetime_param_from_url(request, param_name, default_value):
    datetime_str = request.args.get(param_name, None)
    if datetime_str is None:
        return default_value

    try:
        return parse(datetime_str)
    except ValueError:
        raise BadRequest(f"'{param_name}' has an invalid format datetime")
Ejemplo n.º 9
0
def change_password():
    user_id = get_jwt_identity()
    body = request.data
    user = User.query.get_or_404(user_id)
    if not user.check_password(body['password']):
        raise BadRequest('Password is incorrect')
    user.set_password(body['new_password'])
    db.session.commit()
    return generate_success_response()
Ejemplo n.º 10
0
    def generate(self, avatars, text, usernames, kwargs):
        raise BadRequest(
            "Crab endpoint is disabled on flare's imgen instance. Use trustys crab rave cog or host your own imgen."
        )
        name = uuid.uuid4().hex + '.mp4'

        @after_this_request
        def remove(response):  # pylint: disable=W0612
            try:
                os.remove(name)
            except (FileNotFoundError, OSError, PermissionError):
                pass

            return response

        t = text.upper().replace(', ', ',').split(',')
        if len(t) != 2:
            raise BadRequest(
                'You must submit exactly two strings split by comma')
        if (not t[0] and not t[0].strip()) or (not t[1] and not t[1].strip()):
            raise BadRequest('Cannot render empty text')
        clip = VideoFileClip("assets/crab/template.mp4")
        text = TextClip(t[0], fontsize=48, color='white', font='Symbola')
        text2 = TextClip("____________________", fontsize=48, color='white', font='Verdana')\
            .set_position(("center", 210)).set_duration(15.4)
        text = text.set_position(("center", 200)).set_duration(15.4)
        text3 = TextClip(t[1], fontsize=48, color='white', font='Verdana')\
            .set_position(("center", 270)).set_duration(15.4)

        video = CompositeVideoClip([
            clip,
            text.crossfadein(1),
            text2.crossfadein(1),
            text3.crossfadein(1)
        ]).set_duration(15.4)

        video.write_videofile(name,
                              threads=4,
                              preset='superfast',
                              verbose=False)
        clip.close()
        video.close()
        return send_file(name, mimetype='video/mp4')
Ejemplo n.º 11
0
def login():
    body = request.data
    account = body.copy()
    user = User.query.filter(User.email == account['email'].lower(),
                             User.status != UserStatus.BLOCKED.value).first()
    if not user:
        raise BadRequest(
            'Login failed. Please enter a valid login name and password.')
    if not user.check_password(account['password']):
        raise BadRequest(
            'Login failed. Please enter a valid login name and password.')
    access_token = create_access_token(identity=str(user.id))
    refresh_token = create_refresh_token(identity=str(user.id))
    data = {
        'access_token': access_token,
        'refresh_token': refresh_token,
        'role': user.role
    }
    return generate_success_response(data)
Ejemplo n.º 12
0
def reset_password():
    body = request.data
    user = db.session.query(User).filter_by(
        set_password_code=body['set_password_code']).first()
    if not bool(user):
        raise BadRequest('set password code is not found')
    user.request_forgot_password_at = None
    user.set_password_code = None
    user.set_password(body['password'])
    db.session.commit()
    return generate_success_response()
Ejemplo n.º 13
0
def forgot_password():
    body = request.data
    user = find_user_by_email(body['email'])
    if not user:
        raise BadRequest('email is not found')
    user.request_forgot_password_at = datetime.utcnow()
    user.set_password_code = str(uuid.uuid4())
    db.session.commit()
    reset_link = f'{FRONTEND_ENDPOINT}/reset-password?token={user.set_password_code}'
    send_mail_reset_password(user, reset_link)
    return generate_success_response()
Ejemplo n.º 14
0
def get_user_profile_or_404(user_id):
    user = User.query.filter(User.id == str(user_id),
                             User.status != UserStatus.BLOCKED.value).first()
    if not bool(user):
        raise BadRequest('User not found or is blocked')
    return user
Ejemplo n.º 15
0
def check_is_new_email(email):
    user = find_user_by_email(email)
    if bool(user):
        raise BadRequest('email already exists')
    return
def filename_exist(filename):
    if not storage.check_if_object_exists(filename):
        raise BadRequest('filename not exist')
    return filename
Ejemplo n.º 17
0
def new_password_confirm_must_match(payload):
    if payload['new_password'] != payload['new_password_confirm']:
        raise BadRequest('new password confirm must match')
    return payload
Ejemplo n.º 18
0
 def validate_filename_exist(self, filename):
     if not self.check_if_object_exists(filename):
         raise BadRequest('filename not exist')
     return filename