Web Development 701 ~ OpenFaas ~ Creating a Function
With assessment 2 finished now it’s time to focus back on assessment 3, which serverless via OpenFaas. In this blog I am going to create the function, and it will be with a program I’ve already made; sbh. The first thing to do is create a new directory to store the code in, this will be done via mkdir web701
.
The next thing to do is scaffold a new function via faas-cli new --lang python3 sbh --prefix="<dockerhub-username>"
Now with our scaffolded function it’s time to add the following to handler.py
.
import hashlib
import os
import random
from string import ascii_lowercase, digits, printable
import sys
SYMBOLS = printable[62:]
def handle(req):
return sbh()
def cc(rot, plaintext):
plaintext = plaintext.replace(' ', '')
encrypted = ''
for n in plaintext:
if n.isalpha():
encrypted += ascii_lowercase[(ascii_lowercase.index(n.lower()) + rot) % len(ascii_lowercase)]
elif n.isdigit():
encrypted += digits[(digits.index(n) + rot) % len(digits)]
else:
encrypted += SYMBOLS[(SYMBOLS.index(n) + rot) % len(SYMBOLS)]
return hashlib.sha256(bytes(encrypted, 'UTF-8')).hexdigest()
def sbh():
query = os.getenv('Http_Query').split(',')
plaintext = query[0].split('=')[1]
nrots = int(query[1].split('=')[1])
seed = int(query[2].split('=')[1])
random.seed(seed)
text = cc(random.randint(1, sys.maxsize), plainText)
for _ in range(1, nrots):
rot = random.randint(1, sys.maxsize)
text = cc(rot, text)
return text
Now to build/deploy the function via faas-cli up -f sbh.yml
Once it’s finished we invoke the function via echo "" | faas-cli invoke sbh --query plaintext=test,nrots=3,seed=3
It should print 89c00164680e5e77266515e02005ed9e81ec0b8b448f997dfb192b6f05a3f41b
Works!