Exemplo n.º 1
0
    def run(self, name):

        # Validate the parameters
        form = ViewAccountForm(name=name)
        if not form.validate():
            self.err(**form.errors)
            return

        # Find the account to view
        account = Account.one(Q.name == form.data['name'])

        # Output details of the account
        output = [("About '{0}':".format(account.name), 'underline_bold_blue')]

        pairs = [('created', account.created), ('modified', account.modified),
                 ('assets', Asset.count(Q.account == account)),
                 ('api_key', account.api_key),
                 ('backend', account.backend.get('backend', 'unknown'))]

        for key in sorted(account.backend.keys()):
            if key == 'backend':
                continue
            pairs.append(('> ' + key, account.backend[key]))

        # Find the longest key so we pad/align values
        width = sorted([len(p[0]) for p in pairs])[-1] + 2

        for pair in pairs:
            pair_str = '- {key:-<{width}} {value}'.format(key=pair[0].ljust(
                width, '-'),
                                                          value=pair[1],
                                                          width=width)
            output.append((pair_str, 'blue'))

        self.out(*output)
Exemplo n.º 2
0
def test_purge_expired_assets(celery_app, test_images):
    # Set the expiry date for all assets to an hour ago
    expires = datetime.now(timezone.utc) - timedelta(seconds=3600)
    expires = time.mktime(expires.timetuple())
    assets = Asset.many()
    for asset in assets:
        asset.expires = expires
        asset.update('modified', 'expires')

    # Call the `purge_expired_assets` task
    task = celery_app.tasks['purge_expired_assets']
    task.apply()

    # Check all the assets where purged
    assert Asset.count() == 0
Exemplo n.º 3
0
def upload():
    """Upload an asset"""

    # Check a file has been provided
    fs = request.files.get('asset')
    if not fs:
        return fail('No `asset` sent.')

    # Validate the parameters
    form = UploadForm(request.values)
    if not form.validate():
        return fail('Invalid request', issues=form.errors)

    # Prep the asset name for
    form_data = form.data

    # Name
    name = form_data['name']
    if not name:
        name = os.path.splitext(fs.filename)[0]
    name = slugify_name(name)

    # Extension
    ext = os.path.splitext(fs.filename)[1].lower()[1:]

    # If there's no extension associated with then see if we can guess it using
    # the imghdr module
    if not ext:
        fs.stream.seek(0)
        ext = imghdr.what(fs.filename, fs.stream.read()) or ''

    # If the file is a recognized image format then attempt to read it as an
    # image otherwise leave it as a file.
    asset_file = fs.stream
    asset_meta = {}
    asset_type = Asset.get_type(ext)
    if asset_type is 'image':
        try:
            asset_file, asset_meta = prep_image(asset_file)
        except IOError as e:
            return fail('File appears to be an image but it cannot be read.')

    # Add basic file information to the asset meta
    asset_meta.update({
        'filename': fs.filename,
        'length': get_file_length(asset_file)
    })

    # Create the asset
    asset = Asset(account=g.account._id,
                  name=name,
                  ext=ext,
                  meta=asset_meta,
                  type=asset_type,
                  variations=[])

    if form_data['expires']:
        asset.expires = form_data['expires']

    # Generate a unique Id for the asset
    asset.uid = generate_uid(6)
    while Asset.count(And(Q.account == g.account, Q.uid == asset.uid)) > 0:
        asset.uid = generate_uid(6)

    # Store the original file
    asset.store_key = Asset.get_store_key(asset)
    backend = g.account.get_backend_instance()
    backend.store(asset_file, asset.store_key)

    # Save the asset
    asset.insert()

    return success(asset.to_json_type())