From afbe7bb4581226a062530495fea08e2f88a75f0c Mon Sep 17 00:00:00 2001 From: Alex Root Junior Date: Sat, 14 Jul 2018 01:19:35 +0300 Subject: [PATCH] Allow to use RapidJSON. Allow to disable uvloop, ujson or rapidjson by env. variables. --- aiogram/__init__.py | 4 ++- aiogram/utils/json.py | 57 +++++++++++++++++++++++++++++++------------ dev_requirements.txt | 1 + 3 files changed, 45 insertions(+), 17 deletions(-) diff --git a/aiogram/__init__.py b/aiogram/__init__.py index 39948944..9dbbb13e 100644 --- a/aiogram/__init__.py +++ b/aiogram/__init__.py @@ -1,4 +1,5 @@ import asyncio +import os from .bot import Bot from .dispatcher import Dispatcher @@ -8,7 +9,8 @@ try: except ImportError: uvloop = None else: - asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) + if 'DISABLE_UVLOOP' not in os.environ: + asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) __version__ = '2.0.dev1' __api_version__ = '3.6' diff --git a/aiogram/utils/json.py b/aiogram/utils/json.py index a5d214d7..a8777593 100644 --- a/aiogram/utils/json.py +++ b/aiogram/utils/json.py @@ -1,27 +1,52 @@ -import json +import os + +JSON = 'json' +RAPIDJSON = 'rapidjson' +UJSON = 'ujson' try: - import ujson + if 'DISABLE_UJSON' not in os.environ: + import ujson as json - _UJSON_IS_AVAILABLE = True + mode = UJSON + + + def dumps(data): + return json.dumps(data, ensure_ascii=False) + + else: + mode = JSON except ImportError: - _UJSON_IS_AVAILABLE = False + mode = JSON -_use_ujson = _UJSON_IS_AVAILABLE +try: + if 'DISABLE_RAPIDJSON' not in os.environ: + import rapidjson as json + + mode = RAPIDJSON -def disable_ujson(): - global _use_ujson - _use_ujson = False + def dumps(data): + return json.dumps(data, ensure_ascii=False, number_mode=json.NM_NATIVE, + datetime_mode=json.DM_ISO8601 | json.DM_NAIVE_IS_UTC) -def dumps(data): - if _use_ujson: - return ujson.dumps(data) - return json.dumps(data) + def loads(data): + return json.loads(data, number_mode=json.NM_NATIVE, + datetime_mode=json.DM_ISO8601 | json.DM_NAIVE_IS_UTC) + + else: + mode = JSON +except ImportError: + mode = JSON + +if mode == JSON: + import json -def loads(data): - if _use_ujson: - return ujson.loads(data) - return json.loads(data) + def dumps(data): + return json.dumps(data, ensure_ascii=False) + + + def loads(data): + return json.loads(data) diff --git a/dev_requirements.txt b/dev_requirements.txt index 7f6f9b19..ea4d686a 100644 --- a/dev_requirements.txt +++ b/dev_requirements.txt @@ -1,6 +1,7 @@ -r requirements.txt ujson>=1.35 +python-rapidjson>=0.6.3 emoji>=0.5.0 pytest>=3.5.0 pytest-asyncio>=0.8.0