Skip to content

Commit

Permalink
Merge 96a63aa into e076c8b
Browse files Browse the repository at this point in the history
  • Loading branch information
sshuair authored Mar 3, 2021
2 parents e076c8b + 96a63aa commit 64f80d7
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
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

0 comments on commit 64f80d7

Please sign in to comment.