• Stars
    star
    152
  • Rank 244,685 (Top 5 %)
  • Language
    Python
  • License
    MIT License
  • Created over 4 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A very simple shared memory dict implementation

Shared Memory Dict

A very simple shared memory dict implementation.

Requires: Python >= 3.8

>>> # In the first Python interactive shell
>> from shared_memory_dict import SharedMemoryDict
>> smd = SharedMemoryDict(name='tokens', size=1024)
>> smd['some-key'] = 'some-value-with-any-type'
>> smd['some-key']
'some-value-with-any-type'

>>> # In either the same shell or a new Python shell on the same machine
>> existing_smd = SharedMemoryDict(name='tokens', size=1024)
>>> existing_smd['some-key']
'some-value-with-any-type'
>>> existing_smd['new-key'] = 'some-value-with-any-type'


>>> # Back in the first Python interactive shell, smd reflects this change
>> smd['new-key']
'some-value-with-any-type'

>>> # Clean up from within the second Python shell
>>> existing_smd.shm.close()  # or "del existing_smd"

>>> # Clean up from within the first Python shell
>>> smd.shm.close()
>>> smd.shm.unlink()  # Free and release the shared memory block at the very end
>>> del smd  # use of smd after call unlink() is unsupported

The arg name defines the location of the memory block, so if you want to share the memory between process use the same name. The size (in bytes) occupied by the contents of the dictionary depends on the serialization used in storage. By default pickle is used.

Installation

Using pip:

pip install shared-memory-dict

Locks

To use multiprocessing.Lock on write operations of shared memory dict set environment variable SHARED_MEMORY_USE_LOCK=1.

Serialization

We use pickle as default to read and write the data into the shared memory block.

You can create a custom serializer by implementing the dumps and loads methods.

Custom serializers should raise SerializationError if the serialization fails and DeserializationError if the deserialization fails. Both are defined in the shared_memory_dict.serializers module.

An example of a JSON serializer extracted from serializers module:

NULL_BYTE: Final = b"\x00"


class JSONSerializer:
    def dumps(self, obj: dict) -> bytes:
        try:
            return json.dumps(obj).encode() + NULL_BYTE
        except (ValueError, TypeError):
            raise SerializationError(obj)

    def loads(self, data: bytes) -> dict:
        data = data.split(NULL_BYTE, 1)[0]
        try:
            return json.loads(data)
        except json.JSONDecodeError:
            raise DeserializationError(data)

Note: A null byte is used to separate the dictionary contents from the bytes that are in memory.

To use the custom serializer you must set it when creating a new shared memory dict instance:

>>> smd = SharedMemoryDict(name='tokens', size=1024, serializer=JSONSerializer())

Caveat

The pickle module is not secure. Only unpickle data you trust.

See more here.

Django Cache Implementation

There's a Django Cache Implementation with Shared Memory Dict:

# settings/base.py
CACHES = {
    'default': {
        'BACKEND': 'shared_memory_dict.caches.django.SharedMemoryCache',
        'LOCATION': 'memory',
        'OPTIONS': {'MEMORY_BLOCK_SIZE': 1024}
    }
}

Install with: pip install "shared-memory-dict[django]"

Caveat

With Django cache implementation the keys only expire when they're read. Be careful with memory usage

AioCache Backend

There's also a AioCache Backend Implementation with Shared Memory Dict:

From aiocache import caches

caches.set_config({
    'default': {
        'cache': 'shared_memory_dict.caches.aiocache.SharedMemoryCache',
        'size': 1024,
    },
})

This implementation is very based on aiocache SimpleMemoryCache

Install with: pip install "shared-memory-dict[aiocache]"

More Repositories

1

teresa

Open source tool to deploy apps to Kubernetes clusters
Go
553
star
2

tutorial-python-brasil

Construindo API's robustas utilizando Python
Python
329
star
3

dev-guide

Guias e boas práticas de programação para um melhor desenvolvimento de software
Shell
326
star
4

lasier

A sync/async circuit breaker implementation in Python
Python
90
star
5

juggernaut

An unstoppable boilerplate
JavaScript
57
star
6

ramos

Generic backend pool
Python
29
star
7

gandalf-lint

Bad Code Shall Not Pass
JavaScript
27
star
8

dev.magalu.com-docs

Conteúdo do portal Magalu para Desenvolvedores, incluindo especificações da plataforma aberta Magalu
20
star
9

cookiecutter-aiohttp-api

Python
20
star
10

mitose

Go
18
star
11

django-toolkit

Python
18
star
12

hub

Luizalabs' product/people management app
Python
13
star
13

DistributedCircuitBreaker.NET

C#
10
star
14

hello-teresa

Hello world apps ready to be deployed on Kubernetes clusters through Teresa
Java
10
star
15

heimdall

Python
8
star
16

react-boilerplate

React boilerplate
JavaScript
7
star
17

juggernaut-demo

Demonstração de utilização de componentes utilizando o template juggernaut.
JavaScript
7
star
18

tornado-cookiecutter

This repository is no longer maintained :(
JavaScript
6
star
19

moo-cli

A MOOvelous CLI
TypeScript
5
star
20

helm-rke2-o7k

Helm charts for RKE2
Smarty
5
star
21

asyncio-toolkit

Python
5
star
22

id-magalu-cli

CLI para operações relacionadas aos resources do ID Magalu
5
star
23

covid-19

5
star
24

homebrew-teresa-cli

Ruby
4
star
25

request-manager

Python
4
star
26

sindico

A executable that integrates useful kubernetes controllers
Go
4
star
27

gandalf-lint-react

React Bad Code Shall Not Pass
JavaScript
4
star
28

ansible-sentry

Nginx
3
star
29

mangos

Python
3
star
30

peladeiros

Python
3
star
31

dev.magalu.com

Magalu para Desenvolvedores: Experiência, APIs e Exemplos
3
star
32

MultiLineUIPageControl

UIPageControl with multiple lines! \o/
Objective-C
3
star
33

rey

Go
2
star
34

slugstore

Shell
2
star
35

sqs_logger

Python
1
star
36

nginx-lua

armazenar o Dockerfile da imagem de nginx
Lua
1
star
37

luizalabs.github.io

Blog
CSS
1
star
38

stewie-goiaba

Java
1
star
39

object-matchbox

Java
1
star