Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce transport and deprecate nirum.rpc.* #92

Merged
merged 4 commits into from
Jul 11, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,64 @@ Version 0.6.0

To be released.

- Deprecated ``nirum.rpc`` module.

This module and all it has provided are deprecated or obsolete. The most
of them are now distributed as separated packages, or replaced by a newer
concept. See also the below for details.

It will be completely obsolete at version 0.7.0.

- Client transport layer. [`#79`_]

- Added ``nirum.transport.Transport`` interface.

The recent builds of Nirum compiler became to generate ``*_Client`` classes
taking a ``nirum.transport.Transport`` instance through their constructor.

Use nirum-python-http_ (PyPI handle: ``nirum-http``) instead for HTTP
client of services e.g.:

.. code-block:: python

from yourservice import YourService_Client
from nirum_http import HttpTransport

transport = HttpTransport('https://service-host/')
client = YourService_Client(transport)

- Deprecated ``nirum.rpc.Client`` type. The recent builds of Nirum compiler
became to generate ``*_Client`` classes for services without subclassing
``nirum.rpc.Client``.

The deprecated ``nirum.rpc.Client`` will be completely obsolete at
version 0.7.0.

- ``nirum.rpc.Service`` was moved to ``nirum.service.Service``.

The recent builds of Nirum compiler became to generate service classes
that inherit ``nirum.service.Service`` instead of ``nirum.rpc.Service``.

The deprecated ``nirum.rpc.Service`` will be completely obsolete at
version 0.7.0.

- Deprecated ``nirum.rpc.WsgiApp``. This will be completely obsolete at
version 0.7.0.

Use nirum-python-wsgi_ (PyPI handle: ``nirum-wsgi``) instead.

- ``nirum-server`` command is obsolete. The same command is now provided
by nirum-python-wsgi_ (PyPI handle: ``nirum-wsgi``), a separated package.

- ``nirum.func.import_string()`` function and ``nirum.func.IMPORT_RE`` constant
are obsolete.

- Fixed ``NameError`` raised from forward references. [`compiler #138`_]

.. _#79: https://github.com/spoqa/nirum-python/issues/79
.. _compiler #138: https://github.com/spoqa/nirum/issues/138
.. _nirum-python-http: https://github.com/spoqa/nirum-python-http
.. _nirum-python-wsgi: https://github.com/spoqa/nirum-python-wsgi


Version 0.5.3
Expand Down
37 changes: 2 additions & 35 deletions nirum/func.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,6 @@
import re
from six.moves import urllib

from six.moves import urllib, reduce

__all__ = 'IMPORT_RE', 'import_string', 'url_endswith_slash'
IMPORT_RE = re.compile(
r'''^
(?P<modname> (?!\d) [\w]+
(?: \. (?!\d)[\w]+ )*
)
:
(?P<clsexp> (?P<clsname> (?!\d) \w+ )
(?: \(.*\) )?
)
$''',
re.X
)
__all__ = 'url_endswith_slash'


def url_endswith_slash(url):
Expand All @@ -24,22 +10,3 @@ def url_endswith_slash(url):
if not path.endswith('/'):
path += '/'
return urllib.parse.urlunsplit((scheme, netloc, path, '', ''))


def import_string(imp):
m = IMPORT_RE.match(imp)
if not m:
raise ValueError(
"malformed expression: {}, have to be x.y:z(...)".format(imp)
)
module_name = m.group('modname')
import_root_mod = __import__(module_name)
# it is used in `eval()`
import_mod = reduce(getattr, module_name.split('.')[1:], import_root_mod) # noqa
class_expression = m.group('clsexp')
try:
v = eval(class_expression, import_mod.__dict__, {})
except AttributeError:
raise ValueError("Can't import {}".format(imp))
else:
return v
97 changes: 50 additions & 47 deletions nirum/rpc.py
Original file line number Diff line number Diff line change
@@ -1,69 +1,69 @@
""":mod:`nirum.rpc`
~~~~~~~~~~~~~~~~~~~

.. deprecated:: 0.6.0
This module and all it has provided are deprecated or obsolete. The most
of them are now distributed as separated packages, or replaced by a newer
concept.

It will be completely obsolete at version 0.7.0.

"""
import argparse
import collections
import json
import typing
import warnings

from six import integer_types, string_types
from six.moves import urllib
from werkzeug.exceptions import HTTPException
from werkzeug.http import HTTP_STATUS_CODES
from werkzeug.routing import Map, Rule
from werkzeug.serving import run_simple
from werkzeug.wrappers import Request as WsgiRequest, Response as WsgiResponse

from .constructs import NameDict
from .deserialize import deserialize_meta
from .exc import (InvalidNirumServiceMethodNameError,
InvalidNirumServiceMethodTypeError,
NirumProcedureArgumentRequiredError,
from .exc import (NirumProcedureArgumentRequiredError,
NirumProcedureArgumentValueError,
UnexpectedNirumResponseError)
from .func import import_string, url_endswith_slash
from .func import url_endswith_slash
from .serialize import serialize_meta
from .service import Service as BaseService

__all__ = 'Client', 'WsgiApp', 'Service', 'client_type', 'service_type'
JSONType = typing.Mapping[
str, typing.Union[str, float, int, bool, object]
]


class Service(object):
"""Nirum RPC service."""
class Service(BaseService):
"""Abstract base of Nirum services.

__nirum_service_methods__ = {}
__nirum_method_names__ = NameDict([])
.. deprecated:: 0.6.0
Use :class:`nirum.service.Service` instead.
It will be completely obsolete at version 0.7.0.

@staticmethod
def __nirum_method_error_types__(k, d=None):
return d
"""

def __init__(self):
for method_name in self.__nirum_service_methods__:
try:
method = getattr(self, method_name)
except AttributeError:
raise InvalidNirumServiceMethodNameError(
"{0}.{1} inexist.".format(
typing._type_repr(self.__class__), method_name
)
)
if not callable(method):
raise InvalidNirumServiceMethodTypeError(
"{0}.{1} isn't callable".format(
typing._type_repr(self.__class__), method_name
)
)
warnings.warn(
'nirum.rpc.Service is deprecated; use nirum.service.Service '
'instead. It will be completely obsolete at version 0.7.0.',
DeprecationWarning
)
super(Service, self).__init__()


class WsgiApp:
"""Create WSGI application adapt Nirum service.

:param service: A nirum service.

.. deprecated:: 0.6.0
Use ``nirum_wsgi.WsgiApp`` (provided by `nirum-wsgi
<https://github.com/spoqa/nirum-python-wsgi>`_ package) instead.

It will be completely obsolete at version 0.7.0.

"""

#: (:class:`werkzeug.routing.Map`) url map
Expand All @@ -73,6 +73,12 @@ class WsgiApp:
])

def __init__(self, service):
warnings.warn(
'nirum.rpc.WsgiApp is deprecated; use nirum_wsgi.WsgiApp '
'(provided by nirum-wsgi package). It will be completely '
'obsolete at version 0.7.0.',
DeprecationWarning
)
self.service = service

def __call__(self, environ, start_response):
Expand Down Expand Up @@ -323,8 +329,23 @@ def _raw_response(self, status_code, response_json, **kwargs):


class Client(object):
"""HTTP service client base class.

.. deprecated:: 0.6.0
Use :class:`nirum.transport.Transport` and
:mod:`nirum_http.HttpTransport` (provided by `nirum-http
<https://github.com/spoqa/nirum-python-http>` package) instead.
It will be completely obsolete at version 0.7.0.

"""

def __init__(self, url, opener=urllib.request.build_opener()):
warnings.warn(
'nirum.rpc.Client is deprecated; use nirum.transport.Transport '
'and nirum_http.HttpTransport (provided by nirum-http package) '
'instead. It will be completely obsolete at version 0.7.0.',
DeprecationWarning
)
self.url = url_endswith_slash(url)
self.opener = opener

Expand Down Expand Up @@ -431,21 +452,3 @@ def do_request(self, request_url, payload):
# with postfix named `_type`
service_type = Service
client_type = Client


def main():
parser = argparse.ArgumentParser(description='Nirum service runner')
parser.add_argument('-H', '--host', help='the host to listen',
default='0.0.0.0')
parser.add_argument('-p', '--port', help='the port number to listen',
type=int, default=9322)
parser.add_argument('-d', '--debug', help='debug mode',
action='store_true', default=False)
parser.add_argument('service_impl', help='service implementation name')
args = parser.parse_args()
service_impl = import_string(args.service_impl)
run_simple(
args.host, args.port, WsgiApp(service_impl),
use_reloader=args.debug, use_debugger=args.debug,
use_evalex=args.debug
)
43 changes: 43 additions & 0 deletions nirum/service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
""":mod:`nirum.service` --- Runtime base of Nirum services
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

"""
import typing

from .constructs import NameDict
from .exc import (InvalidNirumServiceMethodTypeError,
InvalidNirumServiceMethodNameError)

__all__ = 'Service',


class Service(object):
"""Abstract base of Nirum services.

All service classes generated by Nirum compiler inherit this.

"""

__nirum_service_methods__ = {}
__nirum_method_names__ = NameDict([])

@staticmethod
def __nirum_method_error_types__(k, d=None):
return d

def __init__(self):
for method_name in self.__nirum_service_methods__:
try:
method = getattr(self, method_name)
except AttributeError:
raise InvalidNirumServiceMethodNameError(
'{0}.{1}() method has to be implemented.'.format(
typing._type_repr(type(self)), method_name
)
)
if not callable(method):
raise InvalidNirumServiceMethodTypeError(
'{0}.{1} has to be callable so that is a method'.format(
typing._type_repr(type(self)), method_name
)
)
Loading