我們的前端並不是一個精美的UI,在本次Lab中實做了前端有兩個目的
那麼接下來讓我們看看我們前端有什麼功能
python frontend.py --type uo --name obj01 --version 1.7.3 --file /home/distributed\_obj\_storage\_system/distributed\_obj\_system/test
首先,在執行frontend.py,我們必須傳遞一個type parameter,指定要做什麼request,type的mapping如下所示
funcMap = {
'uo': uploadObject,
'vl': getVersionList,
'do': downloadObject,
'ol': getObjLocation,
}
uo mapping到uploadObject,uploadObject的程式碼如下圖所示
def uploadObject(args):
content = args.content
name = args.name
file = args.file
if not name:
print('--name is required')
if not content and not file:
print('--name or --file is required')
if file:
content = open(file, 'r').read()
content = compress(content.encode()) # content type will be byte after compress
hash = sha256(content)
size = len(content)
chunk = 10
for i in range(0, size, chunk):
res = requests.post(f"{server_url}/objects/{name}", files={
'obj': content[i:i+chunk],
'hash':hash,
'version': args.version,
'start': i,
'length': chunk,
'size': size})
print(i, chunk, size, res.status_code)
我們傳遞Object的content,可以藉由—content
指定內容,或是—file指定檔案位置
python frontend.py --type do --name obj01 --version 1.7.3
介紹完type的意思後,就直接上Download Object的程式碼了
def downloadObject(args):
name = args.name
version = args.version
if not name:
print('--name is required')
return
if not version:
print('--version is required')
return
# 1. get object size
size = requests.get(f"{server_url}/objects/size/{name}?version={version}").json()['size']
print(f'Size of Object: {size} bytes')
content = b''
start = 0
# download object until length of content fits size
while len(content)<size:
try:
content += requests.get(f"{server_url}/objects/{name}?version={version}&start={start}").content
except KeyboardInterrupt:
sys.exit()
except Exception as e:
start = len(content)
print('Something wrong, downloading again...', e)
try:
print(f'Get content: {decompress(content).decode()}')
except Exception as e:
print(f'Something wrong: {e}')
由於前端需要知道我要download的這個object何時要結束,所以需要先request object size,再根據size大小判斷何時結束
python frontend.py --type vl --name obj01
這部分比較簡單,就是一個簡單的GET request取的metadata的資料,讀者可以自行理解
python frontend.py --type ol --name obj01 --version 1.7.3
這部分比較簡單,就是一個簡單的GET request取的metadata的資料,讀者可以自行理解