Python
Write a Coderunner Function, Job or Schedule in Python.
Use this reference for Functions, Jobs and Schedules written in Python. For a container with your own web server, see Services.
Project files
my-function/
├── handler.py
└── requirements.txtZip these at the root of the archive, not inside a folder. List your packages in requirements.txt, one per line:
requestsThe handler
Define a function named handler in handler.py:
def handler(context, payload):
# your code
passpayloadis the JSON input as adict: the request body for a Function, the run's input for a Job.contextis reserved for information from the runtime. Don't rely on its contents yet.
Function example
A Function can return anything. This shape is the convention:
def handler(context, payload):
name = (payload or {}).get("name")
if not name:
return {
"statusCode": 400,
"body": {"error": "name is required"},
"headers": {"content-type": "application/json"},
}
return {
"statusCode": 200,
"body": {"greeting": f"Hello, {name}"},
"headers": {"content-type": "application/json"},
}Use status codes as in the Node.js reference.
Job and Schedule example
A Job or Schedule doesn't need to return anything:
def handler(context, payload):
print("Import started")
count = import_customers((payload or {}).get("source"))
print(f"Imported {count} customers")If an exception escapes the handler, the run is marked Failed. If you catch it, the run succeeds and handling it is up to you. See Jobs.
Settings, secrets and logs
- Read settings with
os.environ.get("NAME"). See Configuration and secrets. - Read secrets from the Secrets API at runtime, never from your ZIP; see Configuration and secrets.
printoutput goes to the Process Log.
Deploy
gf deploy --name my-function --workload-type function # or job, or schedule with --scheduleThe CLI detects Python from requirements.txt or pyproject.toml. Or create the Coderunner in the Client Portal and upload the ZIP; see Functions.