Skip to content

Commit

Permalink
update for sanic >= 21.3
Browse files Browse the repository at this point in the history
  • Loading branch information
lixxu committed May 8, 2021
1 parent a14ae5e commit ac15039
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 29 deletions.
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ Simple motor wrapper for Sanic.

```
Notice:
version 0.5 requires Sanic >= 21.3
Works on Sanic >= 0.4.0 and MOTOR_URI need to be defined in app.config
```

Expand All @@ -19,13 +21,14 @@ Works on Sanic >= 0.4.0 and MOTOR_URI need to be defined in app.config
from sanic import Sanic
from sanic.response import json
from sanic_jinja2 import SanicJinja2

from sanic_motor import BaseModel

app = Sanic(__name__)

settings = dict(MOTOR_URI='mongodb://localhost:27017/myapp',
LOGO=None,
)
settings = dict(
MOTOR_URI='mongodb://localhost:27017/myapp', LOGO=None
)
app.config.update(settings)

BaseModel.init_app(app)
Expand Down
36 changes: 15 additions & 21 deletions sanic_motor/__init__.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

try:
from sanic.log import logger
except ImportError:
from sanic.log import log as logger

from bson.codec_options import CodecOptions
from bson.objectid import ObjectId
from motor.motor_asyncio import AsyncIOMotorClient
from pymongo import (
ASCENDING,
DESCENDING,
Expand All @@ -15,11 +13,9 @@
HASHED,
TEXT,
)
from bson.codec_options import CodecOptions
from bson.objectid import ObjectId
from motor.motor_asyncio import AsyncIOMotorClient
from sanic.log import logger

__version__ = "0.4.0"
__version__ = "0.5.0"

INDEX_NAMES = dict(
asc=ASCENDING,
Expand Down Expand Up @@ -116,9 +112,9 @@ def default_open_connection(cls, app, loop, name=None, uri=None):
if not name:
name = app.name

logger.info("opening motor connection for [{}]".format(name))
logger.info(f"opening motor connection for [{name}]")
cls.connect_database(app, name, uri or app.config.MOTOR_URI, loop)
app.motor_client = app.motor_clients[name]
app.ctx.motor_client = app.ctx.motor_clients[name]

@classmethod
def connect_database(cls, app, name, uri, loop):
Expand All @@ -127,19 +123,19 @@ def connect_database(cls, app, name, uri, loop):
cls.__dbkey__ = name
cls.__motor_client__ = client
cls.__motor_db__ = db
if not hasattr(app, "motor_clients"):
app.motor_clients = {}
if not hasattr(app.ctx, "motor_clients"):
app.ctx.motor_clients = {}

# for closing use
app.motor_clients[name] = client
app.ctx.motor_clients[name] = client
cls.__motor_clients__[name] = client
cls.__motor_dbs__[name] = db

@staticmethod
def default_close_connection(app, loop):
if hasattr(app, "motor_clients"):
for name, client in app.motor_clients.items():
logger.info("closing motor connection for [{}]".format(name))
if hasattr(app.ctx, "motor_clients"):
for name, client in app.ctx.motor_clients.items():
logger.info(f"closing motor connection for [{name}]")
client.close()

@property
Expand All @@ -157,7 +153,7 @@ def __setitem__(self, key, value):
self.__dict__[key] = value

def __repr__(self):
return "{}".format(self.__dict__)
return f"{self.__dict__}"

def __getattr__(self, key):
"""just return None instead of key error"""
Expand All @@ -167,9 +163,7 @@ def __getattr__(self, key):
def get_collection(cls, db=None):
if "__coll__" not in cls.__dict__:
raise ValueError(
"collection name is required, set {}.__coll__".format(
cls.__name__
)
f"collection name is required, set {cls.__name__}.__coll__"
)

if not db:
Expand Down
11 changes: 6 additions & 5 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@
Simple Motor wrapper for sanic
"""
import os
from pathlib import Path
import platform
from pathlib import Path

from setuptools import setup

if platform.system().startswith("Windows"):
os.environ["SANIC_NO_UVLOOP"] = "yes"

p = Path(__file__) / "../sanic_motor/__init__.py"
version = ""
with p.resolve().open(encoding="utf-8") as f:
for line in f:
if line.startswith("__version__ = "):
Expand All @@ -30,7 +32,8 @@
packages=["sanic_motor"],
zip_safe=False,
platforms="any",
install_requires=["motor>=2.0", "sanic>=0.4.0"],
install_requires=["motor>=2.0", "sanic>=21.3"],
python_requires=">=3.7",
classifiers=[
"Environment :: Web Environment",
"Intended Audience :: Developers",
Expand All @@ -39,8 +42,6 @@
"Programming Language :: Python",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
"Topic :: Software Development :: Libraries :: Python Modules",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3",
],
)

0 comments on commit ac15039

Please sign in to comment.