Skip to content

Commit

Permalink
setting
Browse files Browse the repository at this point in the history
  • Loading branch information
Traineratwot committed Sep 27, 2023
1 parent d43a6cd commit 22dea4e
Show file tree
Hide file tree
Showing 9 changed files with 199 additions and 28 deletions.
34 changes: 17 additions & 17 deletions .github/workflows/python-publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ name: Upload Python Package

on:
release:
types: [published]
types: [ published ]

permissions:
contents: read
Expand All @@ -21,19 +21,19 @@ jobs:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v3
with:
python-version: '3.x'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install build
- name: Build package
run: python -m build
- name: Publish package
uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29
with:
user: __token__
password: ${{ secrets.PYPI_API_TOKEN }}
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v3
with:
python-version: '3.x'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install build
- name: Build package
run: python -m build
- name: Publish package
uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29
with:
user: __token__
password: ${{ secrets.PYPI_API_TOKEN }}
16 changes: 11 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
# SimpleCache
## Usage

## Usage

```python
from SimpleCache2 import simple_cache
from SimpleCache2.FileCache import FileCache
from SimpleCache2.LruCache import LruCache

lru_cache = LruCache()
from SimpleCache2.MemoryCache import MemoryCache
from SimpleCache2.Settings import Settings

# save cache in python variable
memory = MemoryCache()
# save cache in one json file
settings = Settings(settings_file="path/to/test.json")
# save cache in many binary files
cache = FileCache(cache_dir=None)


Expand All @@ -29,6 +34,7 @@ cache.clearOld() # bool
```

## Api

You can write you self cache class:

```python
Expand Down
31 changes: 31 additions & 0 deletions SimpleCache2/CacheSystem.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import pickle
import re
from abc import ABC, abstractmethod
from typing import Callable

Expand All @@ -14,6 +15,8 @@ def getKey(self, key: any = None) -> str:
serialize key return key_prefix + md5(pickle.dumps(key))
:param key:
"""
if self.is_valid_filename(key):
return key
return get_md5_hash(pickle.dumps(key))
pass

Expand Down Expand Up @@ -71,3 +74,31 @@ def clearOld(self):
pass

pass

def is_valid_filename(self, filename) -> bool:
if not filename:
return False
# Проверяем, что строка не пустая
if not isinstance(filename, str):
return False

# Проверяем, что строка не содержит запрещенных символов
forbidden_chars = r'[<>:"/\\|?*\x00-\x1F]'
if re.search(forbidden_chars, filename):
return False

# Проверяем, что строка не начинается с точки (скрытый файл)
if filename.startswith('.'):
return False

# Проверяем, что строка не заканчивается точкой или пробелом
if filename.endswith('.') or filename.endswith(' '):
return False

# Проверяем, что длина строки не превышает максимально допустимую
max_length = 255
if len(filename) > max_length:
return False

# Если все проверки пройдены, возвращаем True
return True
2 changes: 1 addition & 1 deletion SimpleCache2/LruCache.py → SimpleCache2/MemoryCache.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from SimpleCache2.CacheSystem import CacheSystem


class LruCache(CacheSystem):
class MemoryCache(CacheSystem):
memory: {}

def __init__(self):
Expand Down
72 changes: 72 additions & 0 deletions SimpleCache2/Settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import json
import os.path
from os import makedirs, getenv
from os.path import dirname, exists, realpath, expanduser, expandvars

from SimpleCache2.CacheSystem import CacheSystem


class Settings(CacheSystem):
settings_file: str

def __init__(self, settings_file: str = None):
self.settings_file = expanduser(expandvars(getenv('DISK_CACHE_DIR', os.path.join(dirname(realpath(__file__)), 'disk_cache', "settings.json"))))
self.settingsData = {}
if settings_file:
self.settings_file = settings_file
makedirs(dirname(self.settings_file), exist_ok=True)
super().__init__()
self.load()

def __del__(self):
self.save()
pass

def __set__(self, instance, value):
self.set(instance, value)

def __delete___(self, instance):
self.delete(instance)

def __len__(self):
return len(self.settingsData)

def exist(self, key: any) -> bool:
k = self.getKey(key)
return k in self.settingsData
pass

def get(self, key: any) -> any:
k = self.getKey(key)
if k in self.settingsData:
return self.settingsData[k]
return None
pass

def set(self, key: any, value: object, ttl: int = 0) -> object:
k = self.getKey(key)
self.settingsData[k] = value
self.save()
return self
pass

def delete(self, key: any) -> bool:
return False
pass

def clearOld(self) -> list:
return []
pass

def load(self):
if not exists(self.settings_file):
self.save()
return
with open(self.settings_file, "rb") as file:
self.settingsData = json.load(file)
pass

def save(self):
with open(self.settings_file, "w") as file:
json.dump(self.settingsData, file)
pass
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

setuptools.setup(
name="SimpleCache2",
version="1.1.0",
version="1.2.0",
author="Traineratwot",
author_email="[email protected]",
description="Cache system for python",
Expand All @@ -18,4 +18,4 @@
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
),
)
)
3 changes: 3 additions & 0 deletions tests/FileCacheTest.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,6 @@ def testFunc(name):
self.assertEqual(testFunc('Bob'), testFunc('Bob'))
self.assertNotEqual(testFunc('Bob'), testFunc('Dan'))
pass

def test7(self):
self.assertNotEqual("/test/bob/index.php", self.cache.getKey('/test/bob/index.php'))
56 changes: 56 additions & 0 deletions tests/MemoryCacheTest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import unittest
from time import sleep

from SimpleCache2 import simple_cache
from SimpleCache2.MemoryCache import MemoryCache


class MemoryCacheTest(unittest.TestCase):

def setUp(self):
self.cache = MemoryCache()

def test(self):
self.cache.set('test1', (1, 2), 10)
g = self.cache.get('test1')
self.assertEqual((1, 2), g)

def test2(self):
self.cache.set('test2', [1, 2], 10)
g = self.cache.get('test2')
self.assertEqual([1, 2], g)

def test3(self):
self.cache.set('test3', {"hello": "world"}, 10)
g = self.cache.get('test3')
self.assertEqual({"hello": "world"}, g)

def test4(self):
self.cache.set('test4', "string", 10)
g = self.cache.get('test4')
self.assertEqual("string", g)

def test5(self):
def testFunc(name):
sleep(1)
return f"hello world {name}"

g = self.cache.call('test5', 10, testFunc, 'Bob')
self.assertEqual("hello world Bob", g)

g = self.cache.call('test5', 10, testFunc, 'Bob')
self.assertEqual("hello world Bob", g)
pass

def test6Decorator(self):
@simple_cache(self.cache, 10)
def testFunc(name):
sleep(1)
return f"hello world {name}"

self.assertEqual(testFunc('Bob'), testFunc('Bob'))
self.assertNotEqual(testFunc('Bob'), testFunc('Dan'))
pass

def test7(self):
self.assertNotEqual("/test/bob/index.php", self.cache.getKey('/test/bob/index.php'))
9 changes: 6 additions & 3 deletions tests/LruCacheTest.py → tests/SettingsTest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
from time import sleep

from SimpleCache2 import simple_cache
from SimpleCache2.LruCache import LruCache
from SimpleCache2.Settings import Settings


class FileCacheTest(unittest.TestCase):
class SettingsTest(unittest.TestCase):

def setUp(self):
self.cache = LruCache()
self.cache = Settings()

def test(self):
self.cache.set('test1', (1, 2), 10)
Expand Down Expand Up @@ -51,3 +51,6 @@ def testFunc(name):
self.assertEqual(testFunc('Bob'), testFunc('Bob'))
self.assertNotEqual(testFunc('Bob'), testFunc('Dan'))
pass

def test7(self):
self.assertNotEqual("/test/bob/index.php", self.cache.getKey('/test/bob/index.php'))

0 comments on commit 22dea4e

Please sign in to comment.