Skip to content

Commit

Permalink
Support put http in HTTPFile (#352)
Browse files Browse the repository at this point in the history
* support put method in HTTPFile

* fix package lock
  • Loading branch information
oeway authored May 3, 2022
1 parent 34e8a52 commit af739ec
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 5 deletions.
2 changes: 1 addition & 1 deletion javascript/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion javascript/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "imjoy-rpc",
"version": "0.5.8",
"version": "0.5.9",
"description": "Remote procedure calls for ImJoy.",
"module": "index.js",
"scripts": {
Expand Down
2 changes: 1 addition & 1 deletion python/imjoy_rpc/VERSION
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"version": "0.5.8"
"version": "0.5.9"
}
34 changes: 32 additions & 2 deletions python/imjoy_rpc/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -649,6 +649,19 @@ def type_of_script():
}
"""
)

_sync_xhr_put = eval(
"""globalThis._sync_xhr_put = function(url, rawData, type, append){
if(append) throw new Error("append is not supported for put requests");
var request = new XMLHttpRequest();
request.open('PUT', url, false); // `false` makes the request synchronous
var formData = new FormData();
var file = new Blob([new Uint8Array(rawData)],{type});
request.send(file);
return request
}
"""
)
IS_PYODIDE = True
except ImportError:
from urllib.request import Request, urlopen
Expand All @@ -659,7 +672,15 @@ def type_of_script():
class HTTPFile(io.IOBase):
"""A virtual file for reading content via HTTP."""

def __init__(self, url, mode="r", encoding=None, newline=None, name=None):
def __init__(
self,
url,
mode="r",
encoding=None,
newline=None,
name=None,
upload_method="POST",
):
"""Initialize the http file object."""
self._url = url
self._pos = 0
Expand All @@ -675,6 +696,8 @@ def __init__(self, url, mode="r", encoding=None, newline=None, name=None):
assert self._size is not None
self._chunk = 1024
self._initial_request = True
assert upload_method in ["POST", "PUT"]
self._upload_method = upload_method

def tell(self):
"""Tell the position of the pointer."""
Expand Down Expand Up @@ -774,7 +797,14 @@ def _upload(self, content):
else:
append = True

req = _sync_xhr_post(self._url, content, "application/octet-stream", append)
if self._upload_method == "POST":
req = _sync_xhr_post(
self._url, content, "application/octet-stream", append
)
elif self._upload_method == "PUT":
req = _sync_xhr_post(
self._url, content, "application/octet-stream", append
)
if req.status != 200:
raise Exception(f"Failed to write: {req.response}, {req.status}")

Expand Down

0 comments on commit af739ec

Please sign in to comment.