Skip to content

Commit

Permalink
Merge pull request #136 from CPtung/develop
Browse files Browse the repository at this point in the history
feat: code compatible with python2 and python3
  • Loading branch information
taotao authored Nov 21, 2019
2 parents 5c54cc2 + 41ae8ff commit 6ed3020
Show file tree
Hide file tree
Showing 13 changed files with 49 additions and 24 deletions.
11 changes: 8 additions & 3 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
sudo: false
language: python
matrix:
include:
- python: 2.7
env: TOXENV=py27
- python: 3.4
env: TOXENV=py34
- python: 3.5
env: TOXENV=py35
install:
- pip install -r requirements.txt
- pip install tox
script: make tox
env:
- TOXENV=py27
- TOXENV=pypy
after_success:
coveralls
notifications:
Expand Down
5 changes: 3 additions & 2 deletions sanji/connection/mqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import os
import sys
import six
import uuid
import logging
import simplejson as json
Expand Down Expand Up @@ -101,7 +102,7 @@ def set_tunnels(self, tunnels):
"""
set_tunnels(self, tunnels):
"""
for tunnel_type, (tunnel, callback) in tunnels.iteritems():
for tunnel_type, (tunnel, callback) in six.iteritems(tunnels):
if tunnel is None:
continue
self.set_tunnel(tunnel_type, tunnel, callback)
Expand All @@ -124,7 +125,7 @@ def set_on_publish(self, func):
"""
self.client.on_publish = func

def publish(self, topic="/controller", qos=0, payload=None):
def publish(self, topic="/controller", qos=2, payload=None):
"""
publish(self, topic, payload=None, qos=0, retain=False)
Returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS to
Expand Down
12 changes: 9 additions & 3 deletions sanji/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import threading
import re
import traceback
import six
from random import random
from threading import Event
from threading import Thread
Expand Down Expand Up @@ -134,8 +135,11 @@ def ___dispatch(handler, message):

try:
for result in results: # same route
map(lambda handler: ___dispatch(handler, result["message"]),
data = map(lambda handler: ___dispatch(
handler, result["message"]),
result["handlers"])
if not isinstance(data, list):
list(data)
except Exception as e:
_logger.error(e, exc_info=True)

Expand All @@ -162,10 +166,12 @@ def ___dispatch(handler, message, resp):
for result in results: # same route
resp = self.publish.create_response(
result["message"], self.bundle.profile["name"])
map(lambda handler: ___dispatch(
data = map(lambda handler: ___dispatch(
handler, result["message"], resp
),
result["handlers"])
if not isinstance(data, list):
list(data)
except Exception as e:
_logger.error(e, exc_info=True)
resp_data = {"message": "Internal Error."}
Expand Down Expand Up @@ -460,7 +466,7 @@ def wrapper(self, *args, **kwargs):
# Ordered by declare sequence
# http://stackoverflow.com/questions/4459531/how-to-read-class-attributes-in-the-same-order-as-declared
f_locals = sys._getframe(1).f_locals
_order = len([v for v in f_locals.itervalues()
_order = len([v for v in six.itervalues(f_locals)
if hasattr(v, '__call__') and
hasattr(v, '__name__') and
v.__name__ == "wrapper"])
Expand Down
5 changes: 3 additions & 2 deletions sanji/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,8 @@ class Message(object):
Message
"""
def __init__(self, message, generate_id=False):
if isinstance(message, six.string_types):
if (isinstance(message, six.string_types) or
isinstance(message, six.binary_type)):
try:
message = json.loads(message)
except Exception:
Expand All @@ -131,7 +132,7 @@ def __init__(self, message, generate_id=False):
raise TypeError("Message must be JSON string or Dict")

# put all prop into object
for (prop, value) in message.iteritems():
for (prop, value) in six.iteritems(message):
setattr(self, prop, value)

if generate_id is True:
Expand Down
3 changes: 2 additions & 1 deletion sanji/model/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from sanji.model_initiator import ModelInitiator
from voluptuous import Schema
from threading import Event
from six import moves


class ModelBatch(object):
Expand Down Expand Up @@ -161,7 +162,7 @@ def set(self, id, newObj):
MultipleInvalid: If input object is invaild
"""
newObj = self.validation(newObj)
for index in xrange(0, len(self.model.db)):
for index in moves.range(0, len(self.model.db)):
if self.model.db[index]["id"] != id:
continue

Expand Down
6 changes: 3 additions & 3 deletions sanji/publish.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def _crud(resource,
code=200,
timeout=60,
topic="/controller",
qos=0):
qos=2):

message = self._create_message(
headers={"resource": resource, "method": method, "code": code},
Expand All @@ -99,7 +99,7 @@ def _crud(resource,
timeout=60,
topic="/controller",
tunnel=None,
qos=0):
qos=2):
"""
_crud
Expand Down Expand Up @@ -149,7 +149,7 @@ def _response(code=200, data=None):

with self._session.session_lock:
mid = self._conn.publish(topic="/controller",
qos=0, payload=resp_msg.to_dict())
qos=2, payload=resp_msg.to_dict())
session = self._session.create(resp_msg, mid=mid, age=10)
logging.debug("sending response as mid: %s" % mid)
return self._wait_published(session, no_response=True)
Expand Down
3 changes: 2 additions & 1 deletion sanji/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"""

import re
import six
from sanji.message import trim_resource


Expand Down Expand Up @@ -126,7 +127,7 @@ def dispatch(self, message):

def get_routes(self):
routes = {}
for resource, route in self.routes.iteritems():
for resource, route in six.iteritems(self.routes):
routes.update({resource: route.get_methods()})

return routes
3 changes: 2 additions & 1 deletion sanji/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import logging
import uuid
import six

from collections import deque
from threading import Event
Expand Down Expand Up @@ -74,7 +75,7 @@ def resolve(self, msg_id, message=None, status=Status.RESOLVED):

def resolve_send(self, mid_id):
with self.session_lock:
for session in self.session_list.itervalues():
for session in six.itervalues(self.session_list):
if session["mid"] == mid_id:
session["status"] = Status.SENT
session["is_published"].set()
Expand Down
5 changes: 4 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def read(*paths):

setup(
name="sanji",
version="1.0.2",
version="1.1.0",
description="Sanji Framework SDK",
long_description=read('README.rst'),
url="https://github.com/Sanji-IO/sanji",
Expand All @@ -29,6 +29,9 @@ def read(*paths):
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
5 changes: 2 additions & 3 deletions tests/sanji/test_model_initiator.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + '/../../')
from sanji.model_initiator import ModelInitiator
except ImportError:
print "Please check the python PATH for import test module. (%s)" \
% __file__
print("Please check the python PATH for import test module. (%s)" % __file__)
exit(1)

logger = logging.getLogger()
Expand All @@ -29,7 +28,7 @@
def rmgeneric(path, __func__):
try:
__func__(path)
except OSError, (errno, strerror):
except (OSError, errno, strerror):
logger.debug(ERROR_STR % {'path': path, 'error': strerror})


Expand Down
4 changes: 2 additions & 2 deletions tests/sanji/test_publish.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def test_crud(self): # noqa
self.publish.__getattribute__(method)("/test/resource",
{"test": method}, False)
self.conn.publish.assert_called_once_with(topic="/controller",
qos=0,
qos=2,
payload=ANY)
self.conn.publish.reset_mock()
self.session.create.assert_called_once_with(ANY, mid=1, age=60)
Expand Down Expand Up @@ -118,7 +118,7 @@ def test_event(self):
self.publish.event.get("/test/event2",
{"type": "notify2", "message": "hi"})
self.publish._conn.publish.assert_called_once_with(
topic="/controller", qos=0, payload=ANY)
topic="/controller", qos=2, payload=ANY)

def test_direct(self):
with patch("sanji.publish.Publish._wait_published") as _wait_published:
Expand Down
3 changes: 2 additions & 1 deletion tests/sanji/test_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import os
import sys
import six
from collections import deque
from mock import Mock
from mock import MagicMock
Expand Down Expand Up @@ -111,7 +112,7 @@ def test_aging(self, sleep):
self.session.create(message1, age=0)
self.session.aging()

for session in self.session.session_list.itervalues():
for session in six.itervalues(self.session.session_list):
session["is_published"].set()

try:
Expand Down
8 changes: 7 additions & 1 deletion tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,18 @@
# and then run "tox" from this directory.

[tox]
envlist = py27, pypy
envlist = py27, py34, py35
skipsdist = True

[testenv:py27]
basepython = python2.7

[testenv:py34]
basepython = python3.4

[testenv:py35]
basepython = python3.5

[testenv]
deps = -rrequirements.txt
commands = make

0 comments on commit 6ed3020

Please sign in to comment.