From ff1f07fe4b6bd6819d89210cd6d7a9cee3d9cb2a Mon Sep 17 00:00:00 2001 From: "Ivana Yovcheva (VMware)" Date: Tue, 10 Jul 2018 19:20:34 +0300 Subject: [PATCH] Add build options examples This adds an example of how to practically use `build-option` with pillow for Python Signed-off-by: Ivana Yovcheva (VMware) --- docs/cli/build.md | 67 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/docs/cli/build.md b/docs/cli/build.md index 9b04a4af..895351e5 100644 --- a/docs/cli/build.md +++ b/docs/cli/build.md @@ -86,6 +86,73 @@ faas-cli build --lang python3 --build-option dev --build-arg ADDITIONAL_PACKAGE= The entries in the template's Dockerfile described in 1.0 above need to be present for this mode of operation. +## 2.1 Build options examples + +Let's see some practical examples with the `build-option` flag. + +* Use [Pillow](https://pillow.readthedocs.io/en/5.2.x/) for image processing in your Python function + +Create function with + +``` +$ faas-cli new faas-black-and-white --lang python3 --prefix +``` + +Add `pillow`, `requests` and `validators` to `requirements.txt` . + +Edit `handler.py`: + +```python +import os, io, requests, validators +from PIL import Image + +def handle(req): + defaultUrl = "https://pbs.twimg.com/media/DsXDzALW0AAkz2I.jpg:large" + if len(req) > 0 and validators.url(req): + url = req + else: + url = defaultUrl + + errMsg = "Failed to read given URL" + try: + img = Image.open(requests.get(url, stream=True).raw) + except requests.exceptions.SSLError: + return errMsg + except urllib3.exceptions.MaxRetryError: + return errMsg + + blackAndWhite = img.convert('1') + + byteArr = io.BytesIO() + blackAndWhite.save(byteArr, format='JPEG') + res = byteArr.getvalue() + os.write(1, res) + + return res +``` + +What the code does is to open an image from url and convert it to black and white. + +You can build the function with build options (`--build-option dev --build-option pillow`) or add them to the `faas-black-and-white.yml`: +``` + build_options: + - dev + - pillow +``` + +Build push and deploy with: +``` +faas up -f faas-black-and-white.yml +``` + +Test the function with: + +```bash + echo "" | faas invoke faas-black-and-white > blackAndWhite.jpg +``` + +Or in your web browser by opening http://127.0.0.1:8080/function/pillow-func + ## 3.0 Pass custom build arguments You can pass `ARG` values to Docker via the CLI.