Using OpenWhisk Web action and Hypi’s File Upload APIs, manage QR code images

OpenWhisk web actions enable you to quickly build web-based applications. You may program the backend logic of your web application using web actions and Hypi’s low code backend.

In this post, we will see how to use the OpenWhisk Web action and Hypi’s file upload APIs for QR code image file creation, storage, and download.

The Web Action is written using the Python. Here is the Python script.

import sys
import requests
import qrcode
import json
from io import BytesIO
from string import Template
import wget
def main(args):
    token = args.get("hypi_token")
    qr_data = args.get("code")
   
    #create qr code file from text
    qrfilename = qr_data + '.png'
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_Q,
        box_size=10,
        border=4,
    )
    qr.add_data(qr_data)
    qr.make(fit=True)
    img = qr.make_image(fill_color="black", back_color="white")
    byte_io = BytesIO()
    img.save(byte_io, 'png')
    byte_io.seek(0)
    imagefile={'files[]':(qrfilename,byte_io,'image/png')}
    
    #upload to Hypi domain
    
    url = "https://controversially.apps.hypi.app/upload/"
    headers = {
    	'authorization': token,
        'Accept':"application/json",
        'hypi-domain':"controversially.apps.hypi.app",
    }
    response = requests.request("POST", url, files=imagefile, headers=headers)
    print(response.text)
    
    #Set permissions
    
    output= json.loads(response.text)
    id = output[qrfilename]['file']['hypi']['id']
    query_value = Template('mutation {upsert(values:{Permission:[{name:"Grant access to anonymous user" decisionStrategy: Unanimous type:"File" resource: "${id}" scopes: ["*"] operationType: Query  operations:["find"] includeAllAccounts: true }]}){id}}').substitute(id=id)
    data1 = {'query': query_value}
    data2 = json.dumps(data1)
    headers = {
    	'authorization': token,
        'Accept':"application/json",
        'hypi-domain':"controversially.apps.hypi.app",
        'Content-Type':"application/json"
    }
    response1 = requests.post("https://controversially.apps.hypi.app/graphql",data=data2,headers=headers)
    text1 = response1.text
    print(response1.text)
    
    #download file 

    path = output[qrfilename]['file']['url']['path']
    url = "https://controversially.apps.hypi.app" + path

    qrfile = wget.download(url,out=qrfilename)
    return { 'headers': { 'Content-Type': 'image/png' }, 'statusCode': 200, 'body': qrfile }
    

if __name__ == "__main__":
    main(sys.argv)

We pass on the parameter code to the web action. code is the text to convert into a QR image. QR code image gets created using qrcode module. request module of Python is used to upload the file to the Hypi domain. Once the file gets uploaded, we set permissions to download the file without authorization heders. After that, we can extract the path of the file from the output JSON and then create the URL to download the file from Hypi. We can download the file from the created url using the wget module of python.

Now we will move towards OpenWhisk Web actions. First, we need to configure OpenWhisk to point towards Hypi.

wsk property set --apihost "https://fn.hypi.app" --auth " controversially.apps.hypi.app:<Auth_Key>"

Let’s create the web action using OpenWhisk now.

wsk action create qrcode main.py --web true

The python modules may not be accessible with just import. We need to use Docker to import the modules like qrcode, wget. Here are the steps to use docker.

  1. Create Dockerfile
  2. In Dockerfile, add the following
FROM openwhisk/python3action
# lapack-dev is available in community repo.
RUN echo "http://dl-4.alpinelinux.org/alpine/edge/community" >> /etc/apk/repositories
# add package build dependencies
RUN apk add --no-cache \
         g++ \
         lapack-dev \
         gfortran
 # add python packages
 RUN pip install qrcode,wget
  1. Run docker file with docker build -t username/python_qrcode .
  2. docker push username/python_qrcode:v3
  3. Submit a new action to OpenWhisk that uses your custom docker image + your custom python action
  4. wsk action update qrcode –docker username/python_qrcode:v3 main.py

Let’s proceed to invoking web action now. We can use the authorization token as the protected parameter of the web action qrcode

wsk action update qrcode --docker username/python_qrcode:v4 main.py --param hypi_token <auth-token>
Let’s invoke the web action to check the result.

wsk action invoke qrcode --param code asasam --result
{
    "body": "asasam.png",
    "headers": {
        "Content-Type": "image/png"
    },
    "statusCode": 200
}

We can create a url to invoke the web action. The OpenWhisk format is
https://{APIHOST}/api/v1/web/{QUALIFIED ACTION NAME}.{EXT}

Here is our url to download the QR image.

https://fn.hypi.app/api/v1/web/01F2GA50PHFK7BAE9FZTPSPBK3/qrcode.http

Conclusion:

Hypi has a wide variety of features to offer. Serverless functions can easily be written and reused using Hypi and OpenWhisk. While developing web applications, you may write the backend logic using serverless functions. And then reuse the code across different web applications.

Do give it a try!