Another way to do it is like this:
HTML Code
<script>
async function getSecret(secretName) {
const secret = await window.get_secret(secretName)
return secret
}
</script>
<button onclick="getSecret('test_secret').then(secret => console.log(secret)).catch(err => console.error(err))">Click Me</button>
Anvil Code
from ._anvil_designer import Form1Template
import anvil.server
from anvil.js import window
class Form1(Form1Template):
def __init__(self, **properties):
self.init_components(**properties)
window.get_secret = self.get_secret
def get_secret(self, secret):
return anvil.server.call("get_secret", secret)
Server Code
import anvil.server
import anvil.secrets
# Make sure you add code to secure the secrets for the right users.
@anvil.server.callable
def get_secret(secret_key):
return anvil.secrets.get_secret(secret_key)
- I made an anvil method that calls the server function and set it as a method on window (this is the recommended way to call python from js Gotcha with calling Python from Javascript - #2)