Skip to content

Instantly share code, notes, and snippets.

@alexellis
Last active September 24, 2020 17:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save alexellis/39807167e93c29c60342df1f05349add to your computer and use it in GitHub Desktop.
Save alexellis/39807167e93c29c60342df1f05349add to your computer and use it in GitHub Desktop.
Flask on FaaS - minimal example with CGI Handler
  • Place hello.html into templates/

  • Build the Docker image and then deploy

For the time being the FaaS gateway will only accept POST requests, but you can use multiple HTTP methods through the watchdog for testing. A proxy like Nginx could also be used to re-write GET into POST.

FROM python:2.7-alpine
ADD https://github.com/alexellis/faas/releases/download/0.5.6-alpha/fwatchdog /usr/bin
RUN chmod +x /usr/bin/fwatchdog
WORKDIR /root/
RUN pip install flask
ENV fprocess="python handler.py"
COPY handler.py .
HEALTHCHECK --interval=1s CMD [ -e /tmp/.lock ] || exit 1
CMD ["fwatchdog"]
#!/usr/bin/python
from wsgiref.handlers import CGIHandler
from flask import render_template
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello(name=None):
return render_template('hello.html', name=name)
class ProxyFix(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
environ['SERVER_NAME'] = "localhost"
environ['SERVER_PORT'] = "8080"
environ['REQUEST_METHOD'] = "GET"
environ['SCRIPT_NAME'] = ""
environ['PATH_INFO'] = "/"
environ['QUERY_STRING'] = ""
environ['SERVER_PROTOCOL'] = "HTTP/1.1"
return self.app(environ, start_response)
if __name__ == '__main__':
app.wsgi_app = ProxyFix(app.wsgi_app)
CGIHandler().run(app)
<!doctype html>
<title>Hello from Flask</title>
{% if name %}
<h1>Hello {{ name }}!</h1>
{% else %}
<h1>Hello, World!</h1>
{% endif %}
@alexellis
Copy link
Author

This gist is not supported. You should contact the community via Slack. https://openfaas.com

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment