From 9e8cf521b8c399f78d8d29cb0cfb50541d27e8d7 Mon Sep 17 00:00:00 2001 From: Jonathon Belotti Date: Fri, 20 Oct 2023 15:24:49 -0400 Subject: [PATCH] Add example of using @web_endpoint with lifecycle class (#472) --- 07_web_endpoints/basic_web.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 07_web_endpoints/basic_web.py diff --git a/07_web_endpoints/basic_web.py b/07_web_endpoints/basic_web.py new file mode 100644 index 000000000..55fc9aae1 --- /dev/null +++ b/07_web_endpoints/basic_web.py @@ -0,0 +1,33 @@ +import modal +from modal import web_endpoint + +stub = modal.Stub(name="example-lifecycle-web") + +# Hello world! +# +# This is as simple as it gets. A GET endpoint which +# returns a string. + + +@stub.function() +@web_endpoint() +def hello(): + return "Hello world!" + + +# Lifecycle-based. +# +# Web endpoints can be methods on a [lifecycle class](/docs/guide/lifecycle-functions#container-lifecycle-functions-and-parameters). +# This example will only set the `val` instance variable once, on container startup. +# But note that they don't need the [`modal.method`](/docs/reference/modal.method#modalmethod) decorator. + + +@stub.cls() +class WebApp: + def __enter__(self): + print("🏁 Startup up!") + self.val = "Hello world" + + @web_endpoint() + def web(self): + return {"message": self.val}