Skip to content
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
24 changes: 14 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
[![Chat on discord](https://img.shields.io/badge/join%20-discord-brightgreen.svg)](https://discord.com/invite/KKGhy8ZqzK)

A python software development kit for the Multi-Chain Storage(MCS) https://www.multichain.storage service. It provides a convenient interface for working with the MCS API.

# Table of Contents <!-- omit in toc -->

- [Getting Started](#-Getting-Started)
Expand All @@ -21,14 +22,15 @@ A python software development kit for the Multi-Chain Storage(MCS) https://www.m
- via _pip_ (Recommended):

```
pip install python-mcs-sdk
pip install python-mcs-sdk
```

- Build from source (optional)

```
git clone https://github.com/filswan/python-mcs-sdk.git
git checkout main
pip install -r requirements.txt
git clone https://github.com/filswan/python-mcs-sdk.git
git checkout main
pip install -r requirements.txt
```

### Setup Credentials
Expand Down Expand Up @@ -57,7 +59,7 @@ if __name__ == '__main__':


### Onchain Storage

Onchain storage is designed for stored file information in smart contract.It requires payment for each file

* Upload File to Onchain storage
Expand All @@ -68,27 +70,29 @@ Onchain storage is designed for stored file information in smart contract.It req

print(onchain.upload_file('<File Path>'))
```

* Pay for the storage contract

Please move forward for [How to pay for the storage](https://docs.filswan.com/multichain.storage/developer-quickstart/sdk/python-mcs-sdk/onchain-storage/advanced-usage)

### Bucket Storage

- Create a bucket

```python
from mcs import BucketAPI
bucket_client = BucketAPI(mcs_api)
bucket_data = bucket_client.create_bucket('YOUR_BUCKET')
bucket_data = bucket_client.create_bucket('YOUR_BUCKET_NAME')
print(bucket_data)
```
```

- Upload a file to the bucket

```python
# prefix is your targeted bucket related path from the root('./')
file_data = bucket_client.upload_to_bucket(bucket_data["data"], 'YOUR_FILE_PATH' ,prefix='')
# file_path is the path relative to the current file
file_data = bucket_client.upload_file('YOUR_BUCKET_NAME', 'OBJECT_NAME' , 'FILE_PATH')
print(file_data)
```
```

For more examples, please see the [SDK documentation.](https://docs.filswan.com/multi-chain-storage/developer-quickstart/sdk)

Expand Down
37 changes: 28 additions & 9 deletions mcs/api/bucket_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,29 +20,36 @@ def __init__(self, api_client=None):
def list_buckets(self):
result = self.api_client._request_without_params(GET, BUCKET_LIST, self.MCS_API, self.token)
bucket_info_list = []
if result['status'] != 'success':
print("\033[31mError: " + result['message'] + "\033[0m" )
return
data = result['data']
for bucket in data:
bucket_info: Bucket = Bucket(bucket)
bucket_info_list.append(bucket_info)

# print(bucket_info_list)
return bucket_info_list

def create_bucket(self, bucket_name):
params = {'bucket_name': bucket_name}
result = self.api_client._request_with_params(POST, CREATE_BUCKET, self.MCS_API, params, self.token, None)
if result is None:
print("Error: This bucket already exists")
print("\033[31mError: This bucket already exists\033[0m")
return False
if result['status'] == 'success':
print("\033[32mBucket created successfully\033[0m")
return True

def delete_bucket(self, bucket_name):
bucket_id = self._get_bucket_id(bucket_name)
params = {'bucket_uid': bucket_id}
result = self.api_client._request_with_params(GET, DELETE_BUCKET, self.MCS_API, params, self.token, None)
if result is None:
print("Error: Can't find this bucket")
print("\033[31mError: Can't find this bucket\033[0m")
return False
if result['status'] == 'success':
print("\033[32mBucket delete successfully\033[0m")
return True

def get_bucket(self, bucket_name='', bucket_id=''):
Expand All @@ -59,7 +66,7 @@ def get_bucket(self, bucket_name='', bucket_id=''):
for bucket in bucketlist:
if bucket.bucket_uid == bucket_id:
return bucket
print("Error: User does not have this bucket")
print("\033[31mError: User does not have this bucket\033[0m")
return None

# object name
Expand All @@ -69,16 +76,18 @@ def get_file(self, bucket_name, object_name):
for file in file_list:
if file.name == file_name:
return file
print("Error: Can't find this object")
print("\033[31mError: Can't find this object\033[0m")
return None

def create_folder(self, bucket_name, folder_name, prefix=''):
bucket_id = self._get_bucket_id(bucket_name)
params = {"file_name": folder_name, "prefix": prefix, "bucket_uid": bucket_id}
result = self.api_client._request_with_params(POST, CREATE_FOLDER, self.MCS_API, params, self.token, None)
if result['status'] == 'success':
print("\033[32mFolder created successfully\033[0m")
return True
else:
print("\033[31mError: " + result['message']+ "\033[0m")
return False

def delete_file(self, bucket_name, object_name):
Expand All @@ -90,13 +99,14 @@ def delete_file(self, bucket_name, object_name):
file_id = file.id
params = {'file_id': file_id}
if file_id == '':
print("Error: Can't find the file")
print("\033[31mError: Can't find the file\033[0m")
return False
result = self.api_client._request_with_params(GET, DELETE_FILE, self.MCS_API, params, self.token, None)
if result['status'] == 'success':
print("\033[32mFile delete successfully\033[0m")
return True
else:
print("Error: Can't delete the file")
print("\033[31mError: Can't delete the file\033[0m")
return False

def list_files(self, bucket_name, prefix='', limit='10', offset="0"):
Expand All @@ -110,18 +120,25 @@ def list_files(self, bucket_name, prefix='', limit='10', offset="0"):
file_info: File = File(file)
file_list.append(file_info)
return file_list
else:
print("\033[31mError: " + result['message'] + "\033[0m")
return False


def upload_file(self, bucket_name, object_name, file_path):
prefix, file_name = object_to_filename(object_name)
bucket_id = self._get_bucket_id(bucket_name)
if os.stat(file_path).st_size == 0:
print("Error:File size cannot be 0")
print("\033[31mError:File size cannot be 0\033[0m")
return None
file_name = os.path.basename(file_path)
file_size = os.stat(file_path).st_size
with open(file_path, 'rb') as file:
file_hash = md5(file.read()).hexdigest()
result = self._check_file(bucket_id, file_hash, file_name, prefix)
if result is None:
print("\033[31mError:Cannot found bucket\033[0m")
return
if not (result['data']['file_is_exist']):
if not (result['data']['ipfs_is_exist']):
with open(file_path, 'rb') as file:
Expand All @@ -142,8 +159,9 @@ def upload_file(self, bucket_name, object_name, file_path):
result = self._merge_file(bucket_id, file_hash, file_name, prefix)
file_id = result['data']['file_id']
file_info = self._get_file_info(file_id)
print("\033[32mFile upload successfully\033[0m")
return file_info
print("Error:File already existed")
print("\033[31mError:File already existed\033[0m")
return None

# def upload_folder(self, bucket_id, folder_path, prefix=''):
Expand All @@ -169,8 +187,9 @@ def download_file(self, bucket_name, object_name, local_filename):
with open(local_filename, 'wb') as f:
data = urllib.request.urlopen(ipfs_url)
f.write(data.read())
print("\033[32mFile download successfully\033[0m")
return True
print('Error: File does not exist')
print('\033[31mError: File does not exist\033[0m')
return False

def _check_file(self, bucket_id, file_hash, file_name, prefix=''):
Expand Down
16 changes: 12 additions & 4 deletions mcs/api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,20 @@ def get_price_rate(self):
return self._request_without_params(GET, PRICE_RATE, self.MCS_API, self.token)

def api_key_login(self):
params = {}
params['apikey'] = self.api_key
params['access_token'] = self.access_token
params['network'] = self.chain_name
params = {'apikey': self.api_key, 'access_token': self.access_token, 'network': self.chain_name}
if params.get('apikey') == '' or params.get('access_token') == '':
print("\033[31mAPIkey or access token does not exist\033[0m")
return False
result = self._request_with_params(POST, APIKEY_LOGIN, self.MCS_API, params, None, None)
if result == '':
print("\033[31mRequest Error\033[0m")
return
if result['status'] != "success":
print("\033[31mError: " + result['message'] + ". \nPlease check your APIkey and access token, or "
"check whether the current network environment corresponds to the APIkey.\033[0m")
return
self.token = result['data']['jwt_token']
print("\033[32mLogin successful\033[0m")
return self.token

def _request(self, method, request_path, mcs_api, params, token, files=False):
Expand Down