After you configure a NAS mount point for a Function Compute service, you can write code to access files in the NAS just like accessing a local
file system. This topic provides an example of the function code for writing and reading
NAS files.
Create a function to write to a NAS file
- Log on to the Function Compute console.
- In the left-side navigation pane, click Services and Functions.
- In the top navigation bar, select the region where the service resides.
- On the Services page, find the service that you want to manage and click Functions in the Actions column.
- On the Functions page, click the name of the function that you want to manage.
- On the function details page, click the Function Code tab and write code in the code editor.
In this topic, Python 3 is used as an example. The following sample code is used.
#!/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 root, dirs, files in os.walk(nas_dir):
level = root.replace(nas_dir, '').count(os.sep)
indent = ' ' * 2 * (level)
print('{}{}/'.format(indent, os.path.basename(root)))
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 to read NAS files
- Log on to the Function Compute console.
- In the left-side navigation pane, click Services and Functions.
- In the top navigation bar, select the region where the service resides.
- On the Services page, find the service that you want to manage and click Functions in the Actions column.
- On the Functions page, click the name of the function that you want to manage.
- On the function details page, click the Function Code tab and write code in the code editor.
In this topic, Python 3 is used as an example. The following sample code is used.
# -*- coding: utf-8 -*-
def handler(event, context):
f = open("/mnt/test/test.txt", "r")
print(f.readline())
f.close()
return 'ok'