All Products
Search
Document Center

2. Create function

Last Updated: May 31, 2019

You can either use the Function Compute console or the command-line tool fcli to create a function.

Procedures

Note: Your function and the OSS bucket must be in the same region. For example, if the OSS bucket is in China East 2 (Shanghai), set the region of the service to China East 2 (Shanghai).

  1. Log on to the Function Compute console.

  2. See topic Service operations to create a service.

    In this example, we select the China East 2 (Shanghai) region, set the service name to demo, select the test-project log project, select the test-logstore Logstore, role operation to Create new role, and system policies to AliyunOSSFullAccess and AliyunLogFullAccess.

  3. See topic Function operations to create a function.

    In this example, we select the Empty Function template, create no triggers, set the function name to resize, runtime environment to Python, and leave other parameters to their default values.

  4. Edit your function code.

Appendix

In this example, we set the function code as follows. You can use and edit the following function accordingly.

  1. 'use strict';
  2. console.log('Loading function ...');
  3. var oss = require('ali-oss').Wrapper;
  4. var fs = require('fs');
  5. var jimp = require("jimp");
  6. module.exports.resize = function (eventBuf, ctx, callback) {
  7. console.log('Received event:', eventBuf.toString());
  8. var event = JSON.parse(eventBuf);
  9. var ossEvent = event.events[0];
  10. // Required by OSS sdk: OSS region is prefixed with "oss-", e.g. "oss-cn-shanghai"
  11. var ossRegion = "oss-" + ossEvent.region;
  12. // Create oss client.
  13. var client = new oss({
  14. region: ossRegion,
  15. // Credentials can be retrieved from context
  16. accessKeyId: ctx.credentials.accessKeyId,
  17. accessKeySecret: ctx.credentials.accessKeySecret,
  18. stsToken: ctx.credentials.securityToken
  19. });
  20. // Bucket name is from OSS event
  21. client.useBucket(ossEvent.oss.bucket.name);
  22. // Processed images will be saved to processed/
  23. var newKey = ossEvent.oss.object.key.replace("source/", "processed/");
  24. var tmpFile = "/tmp/processed.png";
  25. // Get object
  26. console.log('Getting object: ', ossEvent.oss.object.key)
  27. client.get(ossEvent.oss.object.key).then(function (val) {
  28. // Read object from buffer
  29. jimp.read(val.content, function (err, image) {
  30. if (err) {
  31. console.error("Failed to read image");
  32. callback(err);
  33. return;
  34. }
  35. // Resize the image and save it to a tmp file
  36. image.resize(128, 128).write(tmpFile, function (err) {
  37. if (err) {
  38. console.error("Failed to write image locally");
  39. callback(err);
  40. return;
  41. }
  42. // Putting object back to OSS with the new key
  43. console.log('Putting object: ', newKey);
  44. client.put(newKey, tmpFile).then(function (val) {
  45. console.log('Put object:', val);
  46. callback(null, val);
  47. return;
  48. }).catch(function (err) {
  49. console.error('Failed to put object: %j', err);
  50. callback(err);
  51. return
  52. });
  53. });
  54. });
  55. }).catch(function (err) {
  56. console.error('Failed to get object: %j', err);
  57. callback(err);
  58. return
  59. });
  60. };
  1. # -*- coding: utf-8 -*-
  2. import oss2, json
  3. from wand.image import Image
  4. def resize(event, context):
  5. evt = json.loads(event)
  6. creds = context.credentials
  7. # Required by OSS SDK
  8. auth=oss2.StsAuth(
  9. creds.access_key_id,
  10. creds.access_key_secret,
  11. creds.security_token)
  12. evt = evt['events'][0]
  13. bucket_name = evt['oss']['bucket']['name']
  14. endpoint = 'oss-' + evt['region'] + '.aliyuncs.com'
  15. bucket = oss2.Bucket(auth, endpoint, bucket_name)
  16. objectName = evt['oss']['object']['key']
  17. # Processed images will be saved to processed/
  18. newKey = objectName.replace("source/", "processed/")
  19. remote_stream = bucket.get_object(objectName)
  20. if not remote_stream:
  21. return
  22. remote_stream = remote_stream.read()
  23. with Image(blob=remote_stream) as img:
  24. with img.clone() as i:
  25. i.resize(128, 128)
  26. new_blob = i.make_blob()
  27. bucket.put_object(newKey, new_blob)

Next step

Test the function.