From 148858fde9c676e5885142b7418f3e77f8b4921c Mon Sep 17 00:00:00 2001 From: rr- Date: Thu, 5 May 2016 13:40:32 +0200 Subject: [PATCH] server/middleware: download files --- API.md | 7 +++++++ server/szurubooru/api/context.py | 5 ++++- server/szurubooru/tests/api/test_context.py | 11 +++++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/API.md b/API.md index 2835d3f..904fbee 100644 --- a/API.md +++ b/API.md @@ -106,6 +106,13 @@ Requests that upload files must use `multipart/form-data` encoding. JSON metadata must then be included as field of name `metadata`, whereas files must be included as separate fields with names specific to each request type. +Alternatively, the server can download the files from the Internet on client's +behalf. In that case, the request doesn't need to be specially encoded in any +way. The files, however, should be passed as regular fields appended with `Url` +suffix. For example, to download a file named `content` from +`http://example.com/file.jpg`, the client should pass +`{"contentUrl":"http://example.com/file.jpg"}` as part of the message body. + ## Error handling All errors (except for unhandled fatal server errors) send relevant HTTP status diff --git a/server/szurubooru/api/context.py b/server/szurubooru/api/context.py index 0829cf7..b1da728 100644 --- a/server/szurubooru/api/context.py +++ b/server/szurubooru/api/context.py @@ -1,5 +1,6 @@ import falcon from szurubooru import errors +from szurubooru.func import net class Context(object): def __init__(self): @@ -13,11 +14,13 @@ class Context(object): return name in self.input def has_file(self, name): - return name in self.files + return name in self.files or name + 'Url' in self.input def get_file(self, name, required=False): if name in self.files: return self.files[name] + if name + 'Url' in self.input: + return net.download(self.input[name + 'Url']) if not required: return None raise errors.MissingRequiredFileError( diff --git a/server/szurubooru/tests/api/test_context.py b/server/szurubooru/tests/api/test_context.py index 3b56e9b..edccd90 100644 --- a/server/szurubooru/tests/api/test_context.py +++ b/server/szurubooru/tests/api/test_context.py @@ -1,5 +1,7 @@ +import unittest.mock import pytest from szurubooru import api, errors +from szurubooru.func import net def test_has_param(): ctx = api.Context() @@ -13,6 +15,15 @@ def test_get_file(): assert ctx.get_file('key') == b'content' assert ctx.get_file('key2') is None +def test_get_file_from_url(): + with unittest.mock.patch('szurubooru.func.net.download'): + net.download.return_value = b'content' + ctx = api.Context() + ctx.input = {'keyUrl': 'example.com'} + assert ctx.get_file('key') == b'content' + assert ctx.get_file('key2') is None + net.download.assert_called_once_with('example.com') + def test_getting_list_parameter(): ctx = api.Context() ctx.input = {'key': 'value', 'list': ['1', '2', '3']}