{"id":13725282,"url":"https://github.com/openfaas/python-flask-template","last_synced_at":"2025-04-04T15:07:18.186Z","repository":{"id":38840495,"uuid":"118883783","full_name":"openfaas/python-flask-template","owner":"openfaas","description":"HTTP and Flask-based OpenFaaS templates for Python 3","archived":false,"fork":false,"pushed_at":"2025-01-17T22:07:09.000Z","size":72,"stargazers_count":86,"open_issues_count":9,"forks_count":84,"subscribers_count":6,"default_branch":"master","last_synced_at":"2025-03-28T14:06:09.345Z","etag":null,"topics":["faas","hacktoberfest","kubernetes","python","serverless"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/openfaas.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-01-25T08:17:28.000Z","updated_at":"2025-03-06T05:32:58.000Z","dependencies_parsed_at":"2024-06-18T13:17:56.667Z","dependency_job_id":"f4b314e5-e5c7-43ef-a632-1509d071388b","html_url":"https://github.com/openfaas/python-flask-template","commit_stats":null,"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openfaas%2Fpython-flask-template","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openfaas%2Fpython-flask-template/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openfaas%2Fpython-flask-template/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openfaas%2Fpython-flask-template/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/openfaas","download_url":"https://codeload.github.com/openfaas/python-flask-template/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247198450,"owners_count":20900080,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["faas","hacktoberfest","kubernetes","python","serverless"],"created_at":"2024-08-03T01:02:18.158Z","updated_at":"2025-04-04T15:07:18.165Z","avatar_url":"https://github.com/openfaas.png","language":"Python","funding_links":[],"categories":["Python","Flask"],"sub_categories":["Phaser"],"readme":"OpenFaaS Python Flask Templates\n=============================================\n\nThe Python Flask templates that make use of the incubator project [of-watchdog](https://github.com/openfaas-incubator/of-watchdog).\n\nTemplates available in this repository:\n\n- python3-http\n- python3-http-debian (ideal for compiled dependencies like numpy, pandas, pillow)\n\n- python3-flask\n- python3-flask-debian (ideal for compiled dependencies like numpy, pandas, pillow)\n\n- python27-flask (Python 2.7 is deprecated)\n\nNotes:\n- To build and deploy a function for an ARM computer, you'll need to use `faas-cli publish --platforms`\n\n## SSH authentication for private Git repositories and Pip modules\n\nIf you need to install Pip modules from private Git repositories, we provide an alternative set of templates for OpenFaaS Pro customers:\n\n* [OpenFaaS Pro templates for Python](https://github.com/openfaas/pro-templates)\n\n## Picking your template\n\nThe templates named `python*-flask*` are designed as a drop-in replacement for the classic `python3` template, but using the more efficient of-watchdog. The move to use flask as an underlying framework allows for greater control over the HTTP request and response.\n\nThose templates named `python*-http*` are designed to offer full control over the HTTP request and response. Flask is used as an underlying framework.\n\nThe `witness` HTTP server is used along with Flask for all templates.\n\nAre you referencing pip modules which require a native build toolchain? It's advisable to use the template with a `-debian` suffix in this case. The Debian images are larger, however they are usually more efficient for use with modules like `numpy` and `pandas`.\n\n## Python Versioning\n\nWe try to keep the default Python 3 version up-to-date, however, you can specify a specific python version using the `PYTHON_VERSION` build argument.\n\nThe current stable version of Python is 3.12, you might want to test the next pre-release using:\n\n```yaml\nfunctions:\n  pgfn:\n    lang: python3-http-debian\n    handler: ./pgfn\n    image: pgfn:latest\n    build_args:\n      - PYTHON_VERSION=3.12\n```\nOr pin to a older version while you wait for your dependencies to be updated.\n\n```yaml\nfunctions:\n  pgfn:\n    lang: python3-http-debian\n    handler: ./pgfn\n    image: pgfn:latest\n    build_args:\n      - PYTHON_VERSION=3.10\n```\n\nThis can also be set using the `--build-arg` flag.\n\n```bash\nfaas-cli build --build-arg PYTHON_VERSION=3.12\n```\n\nFor the `-debian` templates, the `DEBIAN_OS` build_args is also available to specify the Debian version. The default is currently `bookworm`.\n\n## Downloading the templates\n\nUsing template pull with the repository's URL:\n\n```bash\nfaas-cli template pull https://github.com/openfaas-incubator/python-flask-template\n```\n\nUsing the template store:\n\n```bash\n# Either command downloads both templates\nfaas-cli template store pull python3-http\n\n# Or\nfaas-cli template store pull python3-flask\n```\n\nUsing your `stack.yml` file:\n\n```yaml\nconfiguration:\n    templates:\n        - name: python3-http\n```\n\n# Using the python3-http templates\n\nCreate a new function\n\n```\nexport OPENFAAS_PREFIX=alexellis2\nexport FN=\"tester\"\nfaas-cli new --lang python3-http $FN\n```\n\nBuild, push, and deploy\n\n```\nfaas-cli up -f $FN.yml\n```\n\nTest the new function\n\n```\necho -n content | faas-cli invoke $FN\n```\n\n## Event and Context Data\n\nThe function handler is passed two arguments, *event* and *context*.\n\n*event* contains data about the request, including:\n- body\n- headers\n- method\n- query\n- path\n\n*context* contains basic information about the function, including:\n- hostname\n\n## Response Bodies\n\nBy default, the template will automatically attempt to set the correct Content-Type header for you based on the type of response.\n\nFor example, returning a dict object type will automatically attach the header `Content-Type: application/json` and returning a string type will automatically attach the `Content-Type: text/html, charset=utf-8` for you.\n\n## Example usage\n\n### Return a JSON body with a Content-Type\n\n```python\ndef handle(event, context):\n    return {\n        \"statusCode\": 200,\n        \"body\": {\"message\": \"Hello from OpenFaaS!\"},\n        \"headers\": {\n            \"Content-Type\": \"application/json\"\n        }\n    }\n```\n\n### Custom status codes and response bodies\n\nSuccessful response status code and JSON response body\n```python\ndef handle(event, context):\n    return {\n        \"statusCode\": 200,\n        \"body\": {\n            \"key\": \"value\"\n        }\n    }\n```\nSuccessful response status code and string response body\n```python\ndef handle(event, context):\n    return {\n        \"statusCode\": 201,\n        \"body\": \"Object successfully created\"\n    }\n```\nFailure response status code and JSON error message\n```python\ndef handle(event, context):\n    return {\n        \"statusCode\": 400,\n        \"body\": {\n            \"error\": \"Bad request\"\n        }\n    }\n```\n### Custom Response Headers\nSetting custom response headers\n```python\ndef handle(event, context):\n    return {\n        \"statusCode\": 200,\n        \"body\": {\n            \"key\": \"value\"\n        },\n        \"headers\": {\n            \"Location\": \"https://www.example.com/\"\n        }\n    }\n```\n### Accessing Event Data\nAccessing request body\n```python\ndef handle(event, context):\n    return {\n        \"statusCode\": 200,\n        \"body\": \"You said: \" + str(event.body)\n    }\n```\nAccessing request method\n```python\ndef handle(event, context):\n    if event.method == 'GET':\n        return {\n            \"statusCode\": 200,\n            \"body\": \"GET request\"\n        }\n    else:\n        return {\n            \"statusCode\": 405,\n            \"body\": \"Method not allowed\"\n        }\n```\nAccessing request query string arguments\n```python\ndef handle(event, context):\n    return {\n        \"statusCode\": 200,\n        \"body\": {\n            \"name\": event.query['name']\n        }\n    }\n```\nAccessing request headers\n```python\ndef handle(event, context):\n    return {\n        \"statusCode\": 200,\n        \"body\": {\n            \"content-type-received\": event.headers.get('Content-Type')\n        }\n    }\n```\n\n### Example with Postgresql:\n\nstack.yml\n\n```yaml\nversion: 1.0\nprovider:\n  name: openfaas\n  gateway: http://127.0.0.1:8080\nfunctions:\n  pgfn:\n    lang: python3-http-debian\n    handler: ./pgfn\n    image: pgfn:latest\n    build_options:\n      - libpq\n```\n\nAlternatively you can specify `ADDITIONAL_PACKAGE` in the `build_args` section for the function.\n\n```yaml\n    build_args:\n      ADDITIONAL_PACKAGE: \"libpq-dev gcc python3-dev\"\n```\n\nrequirements.txt\n\n```\npsycopg2==2.9.3\n```\n\nCreate a database and table:\n\n```sql\nCREATE DATABASE main;\n\n\\c main;\n\nCREATE TABLE users (\n    name TEXT,\n);\n\n-- Insert the original Postgresql author's name into the test table:\n\nINSERT INTO users (name) VALUES ('Michael Stonebraker');\n```\n\nhandler.py:\n\n```python\nimport psycopg2\n\ndef handle(event, context):\n\n    try:\n        conn = psycopg2.connect(\"dbname='main' user='postgres' port=5432 host='192.168.1.35' password='passwd'\")\n    except Exception as e:\n        print(\"DB error {}\".format(e))\n        return {\n            \"statusCode\": 500,\n            \"body\": e\n        }\n\n    cur = conn.cursor()\n    cur.execute(\"\"\"SELECT * from users;\"\"\")\n    rows = cur.fetchall()\n\n    return {\n        \"statusCode\": 200,\n        \"body\": rows\n    }\n```\n\nAlways read the secret from an OpenFaaS secret at `/var/openfaas/secrets/secret-name`. The use of environment variables is an anti-pattern and will be visible via the OpenFaaS API.\n\n# Using the python3-flask template\n\nCreate a new function\n\n```\nexport OPENFAAS_PREFIX=alexellis2\nexport FN=\"tester\"\nfaas-cli new --lang python3-flask $FN\n```\n\nBuild, push, and deploy\n\n```\nfaas-cli up -f $FN.yml\n```\n\nTest the new function\n\n```\necho -n content | faas-cli invoke $FN\n```\n\n## Example of returning a string\n\n```python\ndef handle(req):\n    \"\"\"handle a request to the function\n    Args:\n        req (str): request body\n    \"\"\"\n\n    return \"Hi\" + str(req)\n```\n\n## Example of returning a custom HTTP code\n\n```python\ndef handle(req):\n    return \"request accepted\", 201\n```\n\n## Example of returning a custom HTTP code and content-type\n\n```python\ndef handle(req):\n    return \"request accepted\", 201, {\"Content-Type\":\"binary/octet-stream\"}\n```\n\n## Example of accepting raw bytes in the request\n\nUpdate stack.yml:\n\n```yaml\n    environment:\n      RAW_BODY: True\n```\n\n\u003e Note: the value for `RAW_BODY` is case-sensitive.\n\n```python\ndef handle(req):\n    \"\"\"handle a request to the function\n    Args:\n        req (str): request body\n    \"\"\"\n\n    # req is bytes, so an input of \"hello\" returns i.e. b'hello'\n    return str(req)\n```\n\n\n## Testing\nThe `python3` templates will run `pytest` using `tox` during the `faas-cli build`. There are several options for controlling this.\n\n### Disabling testing\nThe template exposes the build arg `TEST_ENABLED`. You can completely disable testing during build by passing the following flag to the CLI\n\n```sh\n--build-arg 'TEST_ENABLED=false'\n```\n\nYou can also set it permanently in your stack.yaml, see the [YAML reference in the docs](https://docs.openfaas.com/reference/yaml/#function-build-args-build-args).\n\n### Changing the test configuration\nThe template creates a default `tox.ini` file, modifying this file can completely control what happens during the test. You can change the test command, for example switching to `nose`. See the [tox docs](https://tox.readthedocs.io/en/latest/index.html) for more details and examples.\n\n### Changing the test command\nIf you don't want to use `tox` at all, you can also change the test command that is used. The template exposes the build arg `TEST_COMMAND`. You can override the test command during build by passing the following flag to the CLI\n\n```sh\n--build-arg 'TEST_COMMAND=bash test.sh'\n```\nSetting the command to any other executable in the image or any scripts you have in your function.\n\nYou can also set it permanently in your stack.yaml, see the [YAML reference in the docs](https://docs.openfaas.com/reference/yaml/#function-build-args-build-args).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fopenfaas%2Fpython-flask-template","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fopenfaas%2Fpython-flask-template","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fopenfaas%2Fpython-flask-template/lists"}