×
Community Blog Program VSCode Shortcut upload file and folder to Object Storage OSS

Program VSCode Shortcut upload file and folder to Object Storage OSS

Program VSCode Shortcut upload file and folder to Object Storage OSS

Install OSS SDK

pip install --upgrade pip pyyaml oss2
  • oss2 : call API upload file from local to Objetc Storrage OSS
  • pyyaml : read access key of OSS from yaml file

Create VSCode Shortcut

  • crtl+K+S write this content to file keybindings.json
[
  {
    "key": "ctrl+shift+4",
    "command": "workbench.action.terminal.sendSequence",
    "args": {
      "text": "python3 /code/.vscode/execute.py ${file} 4\u000D"
    }
  },
  {
    "key": "ctrl+shift+5",
    "command": "workbench.action.terminal.sendSequence",
    "args": {
      "text": "python3 /code/.vscode/execute.py ${file} 5\u000D"
    }
  }
]
  • Mode 4 : upload single current file selected to OSS
  • Mode 5 : compress then upload the folder which contain the file selected

Handle Shortcut Execute

Append this content to file /code/.vscode/execute.py to handle shortcut execute

import os, sys, yaml

class Exe:
  def __init__(self, absolute_path, mode):
    self.path = absolute_path
    self.mode = str(mode).strip()
    tmp = self.path.split('/')
    self.name = tmp[-1]
    self.ext =  self.name.split('.')[-1]
    self.folder = '/'.join(tmp[:-1])
    if mode == '4':
      self.upload_file()
    elif mode == '5':
      self.upload_folder()

  def upload(self, obj_key, local_file):
    import oss2
    login = yaml.safe_load(open('secret/credential.yml', 'r'))
    OSS = oss2.Bucket(
      auth = oss2.Auth(login['access'], login['secret']),
      endpoint = login['endpoint'],
      bucket_name = login['bucket'],
    )
    OSS.put_object_from_file(obj_key, local_file)
    url = 'https://' + login['bucket'] + '.' + login['endpoint'][len('https://'):] + '/' + obj_key
    print(url)

  def upload_file(self):
    self.upload(self.name, self.path)

  def upload_folder(self):
    folder_tar = self.compress()
    self.upload(folder_tar[len('/tmp/'):], folder_tar)

  def compress(self):
    import tarfile
    folder_name = self.folder.split('/')[-1]
    folder_tar = f'/tmp/{folder_name}.tar.bz2'
    os.system(f'rm -rf {folder_tar}')
    with tarfile.open(folder_tar, 'w:bz2') as f:
      f.add(self.folder, '')
    return folder_tar

absolute_path, mode, *_ = sys.argv[1:]
Exe(absolute_path, mode)

Access Key

Put RAM access key of the Bucket OSS to file /code/secret/credential.yml

access: LTA*****
secret: ********
endpoint: https://oss-ap-southeast-1.aliyuncs.com
bucket: ***

ZazZCEG48RMJQ9bwenkdhmLFYqkijqlol2mkwClV

0 1 0
Share on

quangnn

8 posts | 0 followers

You may also like

Comments