After you configure an Apsara File Storage NAS (NAS) mount target for a service in Function Compute, you can write code in a function of the service to access files in the NAS file system the same way as you do in an on-premises file system. This topic provides sample function code that is used to read data from and write data to a NAS file system.
Prerequisites
Create a function that writes data to NAS
- Log on to the Function Compute console. In the left-side navigation pane, click Services & Functions.
- In the top navigation bar, select a region. On the Services page, click the desired service.
- On the Functions page, click the name of the desired function.
- On the function details page, click the Code tab to write code in the code editor. The following sample code uses Python 3 as an example.
#!/usr/bin/env python # -*- coding: utf-8 -*- import random import subprocess import string import os def handler(event, context): # report file system disk space usage and check NAS mount target out, err = subprocess.Popen(['df','-h'], stdout = subprocess.PIPE).communicate() print('disk: ' + str(out)) lines = [ l.decode() for l in out.splitlines() if str(l).find(':') != -1 ] nas_dirs = [ x.split()[-1] for x in lines ] print('uid : ' + str(os.geteuid())) print('gid : ' + str(os.getgid())) for nas_dir in nas_dirs: sub_dir = randomString(16) file_name = randomString(6)+'.txt' new_dir = nas_dir + '/' + sub_dir + '/' print('test file: ' + new_dir + file_name) content = "NAS here I come" os.mkdir(new_dir) fw = open(new_dir + file_name, "w+") fw.write(content) fw.close() # Showing the folder tree in NAS for home, dirs, files in os.walk(nas_dir): level = home.replace(nas_dir, '').count(os.sep) indent = ' ' * 2 * (level) print('{}{}/'.format(indent, os.path.basename(home))) subindent = ' ' * 2 * (level + 1) for f in files: print('{}{}'.format(subindent, f)) return 'success' def randomString(n): return ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(n))
Create a function that read data from NAS
- Log on to the Function Compute console. In the left-side navigation pane, click Services & Functions.
- In the top navigation bar, select a region. On the Services page, click the desired service.
- On the Functions page, click the name of the desired function.
- On the function details page, click the Code tab to write code in the code editor. The following sample code uses Python 3 as an example.
# -*- coding: utf-8 -*- def handler(event, context): f = open("/mnt/test/test.txt", "r") print(f.readline()) f.close() return 'ok'
The result of the execution of this function is the content written by the function created in Create a function that writes data to NAS.