Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add HTTP backend #860

Merged
merged 7 commits into from
Mar 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion mmcv/fileio/file_client.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import inspect
from abc import ABCMeta, abstractmethod
from urllib.request import urlopen


class BaseStorageBackend(metaclass=ABCMeta):
Expand Down Expand Up @@ -191,6 +192,18 @@ def get_text(self, filepath):
return value_buf


class HTTPBackend(BaseStorageBackend):
"""HTTP and HTTPS storage bachend."""

def get(self, filepath):
value_buf = urlopen(filepath).read()
return value_buf

def get_text(self, filepath):
value_buf = urlopen(filepath).read()
return value_buf.decode('utf-8')


class FileClient:
"""A general file client to access files in different backend.

Expand All @@ -200,7 +213,7 @@ class FileClient:

Attributes:
backend (str): The storage backend type. Options are "disk", "ceph",
"memcached" and "lmdb".
"memcached", "lmdb" and "http".
client (:obj:`BaseStorageBackend`): The backend object.
"""

Expand All @@ -210,6 +223,7 @@ class FileClient:
'memcached': MemcachedBackend,
'lmdb': LmdbBackend,
'petrel': PetrelBackend,
'http': HTTPBackend,
}

def __init__(self, backend='disk', **kwargs):
Expand Down
26 changes: 26 additions & 0 deletions tests/test_fileclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,32 @@ def test_lmdb_backend(self):
img = mmcv.imfrombytes(img_bytes)
assert img.shape == (120, 125, 3)

def test_http_backend(self):
http_backend = FileClient('http')
img_url = 'https://raw.githubusercontent.com/open-mmlab/mmcv/' \
'master/tests/data/color.jpg'
text_url = 'https://raw.githubusercontent.com/open-mmlab/mmcv/' \
'master/tests/data/filelist.txt'

# input is path or Path object
with pytest.raises(Exception):
http_backend.get(self.img_path)
with pytest.raises(Exception):
http_backend.get(str(self.img_path))
with pytest.raises(Exception):
http_backend.get_text(self.text_path)
with pytest.raises(Exception):
http_backend.get_text(str(self.text_path))

# input url is http image
img_bytes = http_backend.get(img_url)
img = mmcv.imfrombytes(img_bytes)
assert img.shape == self.img_shape

# input url is http text
value_buf = http_backend.get_text(text_url)
assert self.text_path.open('r').read() == value_buf

def test_register_backend(self):

# name must be a string
Expand Down