Skip to content

Commit

Permalink
Merge pull request #7 from dnikolayev/master
Browse files Browse the repository at this point in the history
Push the new version of sanic-redis with Python 3.11 support
  • Loading branch information
strahe authored Feb 10, 2023
2 parents d98e7a4 + 94543a0 commit 064d21d
Show file tree
Hide file tree
Showing 7 changed files with 201 additions and 34 deletions.
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
sanic-redis
==============
Redis support for sanic.
Async Redis support for sanic.

Built on top of [aioredis](https://github.com/aio-libs/aioredis).
Built on top of Async version of [Redis library](https://redis-py.readthedocs.io/en/stable/examples/asyncio_examples.html).

[HiRedis](https://github.com/redis/hiredis-py) is used by default for parsing the read results for a higher performance.

Installation
------------
Expand Down
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
sanic
aioredis
redis>=4.4.0
hiredis==2.2.1
9 changes: 6 additions & 3 deletions sanic_redis/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
from .core import SanicRedis

"""
Sanic-Redis init file
"""
from .core import SanicRedis, __version__ as version

__version__ = version
__all__ = ['SanicRedis']
__version__ = '0.3.0'

43 changes: 36 additions & 7 deletions sanic_redis/core.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,52 @@
import aioredis.client
"""
Sanic-Redis core file
"""

from redis.asyncio import client, from_url
from sanic import Sanic
from sanic.log import logger
from aioredis import from_url

__version__ = "0.4.0"


class SanicRedis:
"""
Redis Class for Sanic
"""

conn: aioredis.client.Redis
conn: client.Redis
app: Sanic
redis_url: str
config_name: str

def __init__(self, app: Sanic = None, config_name="REDIS", redis_url: str = ""):
def __init__(self, app: Sanic = None, config_name="REDIS",
redis_url: str = ""):
"""
init method of class
"""

self.__version__ = __version__
self.app: Sanic = app
self.redis_url: str = redis_url
self.conn: aioredis.client.Redis
self.conn: client.Redis
self.config_name: str = config_name

if app:
self.init_app(app=app)

def init_app(self, app: Sanic, config_name: str = None, redis_url: str = ""):
def version(self):
"""
dummy function to pass pylint
"""

return self.__version__

def init_app(self, app: Sanic, config_name: str = None,
redis_url: str = ""):
"""
init_app for Sanic
"""

self.app = app
self.redis_url = redis_url
if config_name:
Expand All @@ -33,7 +59,10 @@ async def aio_redis_configure(_app: Sanic, _loop):
else:
_redis_url = _app.config.get(self.config_name)
if not _redis_url:
raise ValueError("You must specify a redis_url or set the {} Sanic config variable".format(config_name))
raise ValueError(
f"You must specify a redis_url or set the "
f"{config_name} Sanic config variable"
)
logger.info("[sanic-redis] connecting")
_redis = await from_url(_redis_url)
setattr(_app.ctx, self.config_name.lower(), _redis)
Expand Down
116 changes: 95 additions & 21 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,99 @@
from setuptools import setup


setup(
name='sanic-redis',
version='0.3.0',
description='Adds redis support to sanic .',
long_description='sanic-redis is a sanic framework extension which adds support for the redis.',
url='https://github.com/strahe/sanic-redis',
author='octal',
author_email="[email protected]",
license='MIT',
packages=['sanic_redis'],
install_requires=('sanic', 'aioredis'),
zip_safe=False,
keywords=['sanic', 'redis', 'aioredis'],
classifiers=[
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
"""
Sanic-Redis
"""

import sys

from setuptools import find_packages, setup
from setuptools.command.test import test as TestCommand

from sanic_redis import __version__ as version


class PyTest(TestCommand):
"""
Provide a Test runner to be used from setup.py to run unit tests
"""

user_options = [("pytest-args=", "a", "Arguments to pass to pytest")]

def initialize_options(self):
TestCommand.initialize_options(self)
self.pytest_args = ""

def run_tests(self):
import shlex

import pytest

errno = pytest.main(shlex.split(self.pytest_args))
sys.exit(errno)


setup_kwargs = {
"name": "sanic-redis",
"version": version,
"url": "https://github.com/strahe/sanic-redis",
"license": "MIT",
"author": "octal",
"author_email": "[email protected]",
"description": (
'Adds redis support to Sanic'
),
"long_description": 'sanic-redis is a Sanic framework extension which adds support for the redis.',
"packages": find_packages(exclude=("tests", "tests.*")),
"platforms": "any",
"python_requires": ">=3.7",
"keywords": ['sanic', 'redis', 'aioredis'],
"zip_safe": False,
"classifiers": [
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
'Programming Language :: Python :: 3 :: Only',
'Topic :: Internet :: WWW/HTTP :: Session',
],
}

env_dependency = (
'; sys_platform != "win32" ' 'and implementation_name == "cpython"'
)
ujson = "ujson>=1.35" + env_dependency
uvloop = "uvloop>=0.15.0" + env_dependency
types_ujson = "types-ujson" + env_dependency

requirements = [
"sanic",
"redis>=4.4.0",
"hiredis==2.2.1"
]

tests_require = [
"sanic-testing>=22.9.0",
"pytest==7.1.*",
"coverage",
"beautifulsoup4",
"pytest-sanic",
"pytest-benchmark",
"chardet==3.*",
"flake8",
"black",
"isort>=5.0.0",
"bandit",
"mypy>=0.901,<0.910",
"docutils",
"pygments",
"uvicorn<0.15.0",
"slotscheck>=0.8.0,<1",
types_ujson,
]

setup_kwargs["install_requires"] = requirements
setup_kwargs["tests_require"] = tests_require
setup_kwargs["cmdclass"] = {"test": PyTest}
setup(**setup_kwargs)
28 changes: 28 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""
Conftest for Sanic-Redis
"""

from typing import Any, Dict
import re
import pytest

from sanic import Sanic
from sanic_redis import SanicRedis

CACHE: Dict[str, Any] = {}

slugify = re.compile(r"[^a-zA-Z0-9_\-]")


@pytest.fixture(scope="function")
def app(request):
"""
Basic Fixture to test Sanic
"""

my_app = Sanic(slugify.sub("-", request.node.name))
redis = SanicRedis()
redis.init_app(my_app, config_name="my_test_redis",
redis_url="redis://127.0.0.1")

yield my_app
30 changes: 30 additions & 0 deletions tests/test_base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"""
Basic test for Sanic-Redis
Expects to have Redis on 127.0.0.1 with standard port
"""

import random

from sanic import Sanic
from sanic.response import text


def test_app_loop_running(app: Sanic):
"""
Test uses random keys and values to verify the work of Redis with Sanic
"""
test_key = f"test_key{random.random()}"
test_value = f"{random.random()}_test_value"

@app.get("/test")
async def handler(request):
redis = request.app.ctx.my_test_redis
await redis.set(test_key, test_value)
await redis.expire(test_key, 10)

bytes_result = await redis.get(test_key)
result = bytes_result.decode("utf-8")
return text(result)

_, response = app.test_client.get("/test")
assert response.text == test_value

0 comments on commit 064d21d

Please sign in to comment.