How to use KV storage in a serverless function
After building the FaaS feature, we needed a way to store data to make these functions more useful. This is where KV storage comes in. KV storage allows you to store key-value pairs that persist between serverless function executions. This means you can save user preferences, session data, or any other information that needs to be retained across function calls.
In this tutorial, we'll cover how to use KV storage custom blocks in your serverless functions.
-
Enter add new function page: Go to the "Functions" section in your project dashboard and click "Add New Function".
-
Select Blockly from the language dropdown: Choose "Blockly" as the programming language for your function. Then enter a name for your function.
- Scroll down to the low code editor: You will find the low code editor which is a Blockly workspace where you can drag and drop blocks to build your function logic.
- Click on the "KV Storage" category: In the block palette on the left side, find the "KV Storage" category. This contains all the blocks related to KV storage operations.
- Drag and drop the "Create KV Storage" block: This block initializes a new KV storage instance. You can set the key with a text bloc, the value with a json bloc, the TTL (time to live) with a number bloc (this way it becomes temporary), and finally you can set result to a variable if you want to.
As always, you can see the generated Python code when you switch from Low code to Code mode.
- Use the "Get KV Storage" block: If you already have a KV storage created in another function, or you created from the KV storage interface (see How to create a KV storage), you can use the "Get KV Storage" block to retrieve it. This block allows you to access existing KV storage by its key and set the result to a variable.
And you can see the generated Python code when you switch from Low code to Code mode.
- You can also use the "Update KV Storage" block: This block allows you to update an existing KV storage entry. It has the same parameters as the "Create KV Storage" block, so you can set the key, value, and TTL. If the key already exists, it will update the value; if not, it will create a new entry.
And you can see the generated Python code when you switch from Low code to Code mode.
- Use the "Delete KV Storage" block: If you want to remove a KV storage entry, you can use the "Delete KV Storage" block. This block takes a key as input and deletes the corresponding entry from the KV storage.
And you can see the generated Python code when you switch from Low code to Code mode.
- Test your function: After adding the necessary blocks, you can save your function and test it.