def upload_file(request): # type: (Request) -> HTTPException """ Upload a file to secured vault. """ error = "File missing." try: req_file = request.POST.get("file") # type: Optional[cgi_FieldStorage] req_fs = getattr(req_file, "file", None) # type: Optional[BufferedIOBase] except Exception as exc: error = str(exc) req_file = req_fs = None if not isinstance(req_fs, BufferedIOBase): raise OWSMissingParameterValue( json={ "code": "MissingParameterValue", "name": "file", "description": sd.BadRequestVaultFileUploadResponse.description, "error": error, }) if not re.match(REGEX_VAULT_FILENAME, req_file.filename): LOGGER.debug("Invalid filename refused by Vault: [%s]", req_file.filename) raise OWSInvalidParameterValue( status=HTTPUnprocessableEntity, json={ "code": "InvalidParameterValue", "name": "filename", "description": sd.UnprocessableEntityVaultFileUploadResponse.description, "value": str(req_file.filename) }) # save file to disk from request contents # note: 'vault_file.name' includes everything after 'vault_dir' (<id>/<original_name.ext>) vault_file = VaultFile("") vault_dir = get_vault_dir(request) vault_fs = LocalFileStorage(vault_dir) vault_fs.extensions = get_allowed_extensions() try: req_file.file = vault_file.encrypt(req_file.file) vault_file.name = vault_fs.save(req_file, folder=str(vault_file.id)) except FileNotAllowed: file_ext = os.path.splitext(req_file.filename) LOGGER.debug("Invalid file extension refused by Vault: [%s]", file_ext) raise OWSInvalidParameterValue( status=HTTPUnprocessableEntity, json={ "code": "InvalidParameterValue", "name": "filename", "description": sd.UnprocessableEntityVaultFileUploadResponse.description, "value": str(file_ext) }) db = get_db(request) vault = db.get_store(StoreVault) vault.save_file(vault_file) data = {"description": sd.OkVaultFileUploadedResponse.description} data.update(vault_file.json()) path = get_vault_path(vault_file, request) headers = get_file_headers(path) headers["Content-Location"] = get_vault_url(vault_file, request) return HTTPOk(json=data, headers=headers)
def __init__(self, base_url, base_path): suffix = '' if not base_url.endswith('/'): suffix = '/' self.storage = LocalFileStorage(base_path, base_url + suffix)