cassiacommon
Provides commonly used utility classes and functions.
SimpleFuture
A lightweight asynchronous result container used to wait for an event to complete and retrieve its result in asynchronous code.
Example
1import asyncio
2import cassiacommon
3
4
5async def main():
6 print("start simple future")
7 fut = cassiacommon.SimpleFuture()
8
9 async def producer():
10 print("producer sleep 3 seconds...")
11 await asyncio.sleep(3)
12 fut.set_result(200, "OK")
13 print("producer ok")
14
15 asyncio.create_task(producer())
16 code, value = await fut.wait()
17 print("simple future done:", code, value)
18
19
20asyncio.run(main())
API
- class SimpleFuture
A lightweight, one-time event synchronization primitive implemented using asyncio.ThreadSafeFlag.
- __init__() SimpleFuture
Initialize the object
- set_result(code, value)
Sets the result and wakes up any waiters. Can only take effect once; subsequent calls are ignored.
- Parameters:
code: Custom status code
value: Data to be passed
- Returns:
None
- async wait() Tuple[code, value]
Suspends execution until the result is ready, then returns the packaged data.
- Parameters:
None
- Returns:
code: Custom status code
value: Data to be passed
AsyncQueue
A lightweight asynchronous queue used to pass data between asynchronous tasks.
Example
1import asyncio
2import cassiacommon
3
4
5async def main():
6 print("start async queue")
7
8 q = cassiacommon.AsyncQueue(max_size=4)
9 q.put_nowait("a")
10 q.put_nowait("b")
11 print(await q.get())
12 print(await q.get())
13
14 print("async queue done")
15
16
17asyncio.run(main())
API
- class AsyncQueue
A lightweight, one-time event synchronization primitive implemented using asyncio.ThreadSafeFlag.
- __init__(max_size=16) AsyncQueue
Initialize the object
- put_nowait(item)
Puts an element into the queue without blocking. If the queue is full, the element is discarded without raising an exception.
- Parameters:
item: Object to be enqueued
- Returns:
None
- async get() Any
Retrieves the element at the front of the queue. If the queue is empty, suspends execution until data becomes available.
- Parameters:
None
- Returns:
The earliest enqueued element
DataCache
A data cache with size limits, supporting custom settings for max_bytes and hashtable_size.
Type |
Description |
Default |
|---|---|---|
max_bytes |
Max Size |
|
hashtable_size |
Hash Size |
|
Example
1import asyncio
2import cassiacommon
3
4
5async def main():
6 print("===================")
7 print("data cache start")
8
9 cache = cassiacommon.DataCache()
10
11 cache_info = cache.info()
12 print(f"cache info init status: {cache_info}")
13
14 # add sample data
15 await cache.put("z", {"z_key1": "z_value1"})
16 await cache.put("z", {"z_key2": "z_value2"})
17 await cache.put("z", [{"z_key3": "z_value3"}])
18
19 await cache.put("a", {"a_key1": "a_value1"})
20 await cache.put("a", {"a_key2": "a_value2"})
21 await cache.put("a", [{"a_key3": "a_value3"}])
22
23 # current cache info
24 cache_info = cache.info()
25 print(f"cache info after put data status: {cache_info}")
26
27 # get data by key
28 user_data = await cache.get("a", cnt=1)
29 print(f"a data: {user_data}")
30
31 # get no exist key
32 noexistent_data = await cache.get("nonexistent:key")
33 print(f"no exist data: {noexistent_data}")
34
35 # get data by key order
36 key_ordered_data = await cache.get_next(cnt=1, flag=True)
37 print(f"key ordered data: {key_ordered_data}")
38
39 # get data by time order
40 time_ordered_data = await cache.get_next(cnt=1, flag=False)
41 print(f"time ordered data: {time_ordered_data}")
42
43 cache.clear()
44 print(f"cache clear ok")
45 print(cache.info())
46
47 print("data cache done")
48
49
50asyncio.run(main())
API
- class DataCache
A data cache with size limits, supporting custom settings for
max_bytesandhashtable_size.- _DATA_CACHE_MAX_MEM
The default maximum memory usage is 256 KB (262,144 bytes).
- _DATA_CACHE_HASHTABLE_SIZE
The default hashtable size is 53.
- _DATA_CACHE_GET_MAX_CNT
The default maximum fetch count is 10.
- __init__(self, max_bytes=_DATA_CACHE_MAX_MEM, hashtable_size=_DATA_CACHE_HASHTABLE_SIZE) DataCache
Initialize the object
- info()
Get cache information
- Parameters:
None
- Returns:
current_size: Used space
max_size: Total space size
- async put(key, data)
Asynchronously store data to cache
- Parameters:
key (str) – Data Key
data (any) – Data to be stored
- Returns:
Return
- async get_next(cnt=_DATA_CACHE_GET_MAX_CNT, flag=False)
Asynchronously fetch the next batch of data
- Parameters:
cnt (int) – The number of data items to fetch, defaulting to _DATA_CACHE_GET_MAX_CNT
flag (bool) – Sort flag, True indicates key order, False indicates time or queue order
- Returns:
Data list
- Return type:
list
If the cache is not initialized or contains no data, return an empty list.
- async get(key, cnt=_DATA_CACHE_GET_MAX_CNT)
Asynchronously fetch data by key.
- Parameters:
key (str) – Data Key
cnt (int) – The number of data items to fetch, defaulting to _DATA_CACHE_GET_MAX_CNT
- Returns:
Data list
- Return type:
list
If the cache is not initialized or no data exists for the corresponding key, return an empty list.