Exemplo n.º 1
0
def artifact_download(request, inline):
    af = get_artifact(request)

    if af.is_bundle:
        if inline:
            raise HTTPBadRequest("Inline view not supported for bundles")
        # We have a bundle. So we need to prepare a zip (unless we already have one)
        disk_name = af.file
        # Locking on a separate file since zipfile did not want to write to the
        # same file we are locking on. It just means that we need to clean up
        # that file at the same time as the main cache file.
        with portalocker.Lock(disk_name + ".lock", timeout=300, check_interval=1):
            if not os.path.exists(disk_name):
                with zipfile.ZipFile(disk_name, 'w', compression=zipfile.ZIP_BZIP2) as _zip:
                    for cf in af.artifacts:
                        _zip.write(cf.file, arcname=cf.bundle_filename(af))
        file_name = af.name + ".zip"
    else:
        disk_name = af.file
        file_name = af.filename

    mime, encoding = mimetypes.guess_type(file_name)
    if mime is None:
        mime = ('text/plain' if inline else 'application/octet-stream')
    # If the current simple approach proves to be a problem the discussion
    # at http://stackoverflow.com/q/93551/11722 can be considered.
    response = FileResponse(disk_name, request=request, content_type=mime)
    response.content_disposition = '{}; filename="{}"'.format('inline' if inline else 'attachment', file_name)
    # Specifically needed for jquery.fileDownload
    response.set_cookie('fileDownload', 'true')
    return response