This example demonstrates how to integrate Python on GraalVM with a Micronaut application. The application uses the Gradle build tool.
-
Download the latest GraalPy as described on https://www.graalvm.org/python/. For example on Linux:
wget https://github.com/oracle/graalpython/releases/download/graal-23.1.1/graalpy-23.1.1-linux-amd64.tar.gz tar xzf graalpy-23.1.1-linux-amd64.tar.gz
-
Install the required packages for this demo into the resources directory:
graalpy-23.1.1-linux-amd64/bin/graalpy -m venv src/main/resources/venv src/main/resources/venv/bin/graalpy -m pip install nltk
-
Optional: Download and install GraalVM JDK for Java 21 or later to run Python with runtime compilation and to build a native image. The demo will work on any OpenJDK distribution, but will be much faster on GraalVM JDK.
-
Build application with Gradle:
./gradlew run
-
Navigate to http://localhost:12345/#/chat/bob
You can connect from multiple browsers and chat via websockets. The Python code will load a language model in the background. Once it is ready, it will analyse the sentiments of all messages and add an emoji to the message to indicate the feelings conveyed. A chat may look like this (newest message at the top):
[bob 😀] awesome, GraalVM and GraalPy rock! [bob 🫥] are we done yet? [bob 💬] still loading the sentiment model I believe
The application can be AOT compiled using GraalVM Native Image. The Python code has to be shipped in a resources directory that is kept next to the native executable.
-
Build a native executable with the Micronaut AOT support:
./gradlew nativeCompile
-
Copy the venv into the output resources directory:
cp -R src/main/resources/venv/ build/native/nativeCompile/resources/python/
-
Run the native executable:
build/native/nativeCompile/websocket.chat
Learn more about GraalVM polyglot capabilities here.