Last active
April 19, 2020 21:40
-
-
Save wryfi/1f3db7ffca050f696bfbe6603e3906cf to your computer and use it in GitHub Desktop.
yodafact cloud function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Use the official Python image. | |
# https://hub.docker.com/_/python | |
FROM python:3.7-slim | |
RUN mkdir /app | |
WORKDIR /app | |
COPY . . | |
# Install production dependencies. | |
RUN pip install gunicorn functions-framework | |
RUN pip install -r requirements.txt | |
# Run the web service on container startup. Here we use the gunicorn | |
# webserver, with one worker process and 8 threads. | |
# For environments with multiple CPU cores, increase the number of workers | |
# to be equal to the cores available. | |
CMD exec gunicorn --bind :$PORT --workers 1 --threads 8 -e FUNCTION_TARGET=yodafact functions_framework:app |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import logging | |
import re | |
from suds.client import Client | |
import requests | |
YODA_WSDL = 'http://www.yodaspeak.co.uk/webservice/yodatalk.php?wsdl' | |
FACT_JSON = 'https://uselessfacts.jsph.pl/random.json?language=en' | |
log = logging.getLogger(__name__) | |
def yodafact(request): | |
""" | |
returns a random fact in yoda speak | |
""" | |
factyoda = yoda(fact()) | |
output = json.dumps({'fact': factyoda}) | |
return output, 200, {'Content-Type': 'application/json; charset=utf-8'} | |
def fact(): | |
""" | |
returns a random fact from the uselessfacts api | |
""" | |
try: | |
response = requests.get(FACT_JSON) | |
return response.json()['text'] | |
except Exception as ex: | |
log.error(f'error getting fact: {ex}') | |
return 'This is not a random fact.' | |
def yoda(text): | |
""" | |
sends text to the yodaspeak api and returns yoda speak as text | |
""" | |
yoda = Client(YODA_WSDL) | |
try: | |
yodaspeak = yoda.service.yodaTalk(text) | |
yodaspeak = re.sub(r'\s+\.\s+', '', yodaspeak) | |
yodaspeak = yodaspeak.strip() | |
return yodaspeak | |
except Exception as ex: | |
log.error(f'error speaking yoda: {ex}') | |
return text |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment