Skip to content

Commit 778e361

Browse files
kanghyojundahlia
authored andcommitted
Initial commit
0 parents  commit 778e361

File tree

8 files changed

+240
-0
lines changed

8 files changed

+240
-0
lines changed

.gitignore

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
*.pyc
2+
.*.swp
3+
.cache/
4+
.tox/
5+
__pycache__/

CHANGES.rst

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
Changelog
2+
=========
3+
4+
Version 0.1.0
5+
-------------
6+
7+
To be released.

README.rst

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
Nirum HTTP transport for Python
2+
===============================
3+
4+
This package provides an HTTP transport for nirum-python_.
5+
6+
.. _nirum-python: https://github.com/spoqa/nirum-python
7+
8+
9+
.. include:: CHANGES.rst

nirum_http.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
from nirum.transport import Transport
2+
from nirum.exc import UnexpectedNirumResponseError
3+
from requests import Session
4+
from six import string_types
5+
from six.moves import urllib
6+
7+
__all__ = 'HttpTransport',
8+
__version__ = '0.1.0'
9+
10+
11+
def url_endswith_slash(url):
12+
if not isinstance(url, string_types):
13+
raise TypeError('url must be a string, not {0!r}'.format(url))
14+
scheme, netloc, path, _, _ = urllib.parse.urlsplit(url)
15+
if not (scheme and netloc):
16+
raise ValueError("{} isn't URL.".format(url))
17+
if not path.endswith('/'):
18+
path += '/'
19+
return urllib.parse.urlunsplit((scheme, netloc, path, '', ''))
20+
21+
22+
class HttpTransport(Transport):
23+
24+
def __init__(self, url, session=None):
25+
if session is None:
26+
session = Session()
27+
elif not isinstance(session, Session):
28+
raise TypeError('session must be {0.__module__}.{0.__name__}, not '
29+
'{1!r}'.format(Session, session))
30+
self.url = url_endswith_slash(url)
31+
self.session = session
32+
33+
def call(self,
34+
method_name,
35+
payload,
36+
service_annotations,
37+
method_annotations,
38+
parameter_annotations):
39+
response = self.session.post(
40+
self.url,
41+
params={'method': method_name},
42+
headers={'Accept': 'application/json'},
43+
json=payload
44+
)
45+
try:
46+
content = response.json()
47+
except ValueError:
48+
raise UnexpectedNirumResponseError(response.text)
49+
return response.ok, content

setup.cfg

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
[bdist_wheel]
2+
universal = 1

setup.py

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import ast
2+
import os
3+
import re
4+
import sys
5+
6+
from setuptools import setup, __version__ as setuptools_version
7+
8+
9+
def readme(name='README.rst'):
10+
try:
11+
with open(name) as f:
12+
rst = f.read()
13+
return re.sub(
14+
r'(^|\n).. include::\s*([^\n]+)($|\n)',
15+
lambda m: m.group(1) + (readme(m.group(2)) or '') + m.group(3),
16+
rst
17+
)
18+
except (IOError, OSError):
19+
return
20+
21+
22+
def get_version():
23+
module_path = os.path.join(os.path.dirname(__file__), 'nirum_http.py')
24+
module_file = open(module_path)
25+
try:
26+
module_code = module_file.read()
27+
finally:
28+
module_file.close()
29+
tree = ast.parse(module_code, module_path)
30+
for node in ast.iter_child_nodes(tree):
31+
if not isinstance(node, ast.Assign) or len(node.targets) != 1:
32+
continue
33+
target, = node.targets
34+
if isinstance(target, ast.Name) and target.id == '__version__':
35+
value = node.value
36+
if isinstance(value, ast.Str):
37+
return value.s
38+
raise ValueError('__version__ is not defined as a string literal')
39+
raise ValueError('could not find __version__')
40+
41+
42+
setup_requires = []
43+
install_requires = [
44+
'nirum >= 0.6.0',
45+
'requests >= 2.11.1',
46+
'six',
47+
]
48+
tests_require = [
49+
'flake8-import-order >= 0.12, < 1.0',
50+
'flake8-import-order-spoqa >= 1.0.0, < 2.0.0',
51+
'pytest >= 3.1.2, < 4.0.0',
52+
'pytest-flake8 >= 0.8.1, < 1.0.0',
53+
'requests-mock >= 1.3.0, < 1.4.0',
54+
]
55+
extras_require = {
56+
'tests': tests_require,
57+
}
58+
below35_requires = [
59+
'typing',
60+
]
61+
62+
63+
if 'bdist_wheel' not in sys.argv and sys.version_info < (3, 5):
64+
install_requires.extend(below35_requires)
65+
66+
67+
if tuple(map(int, setuptools_version.split('.'))) < (17, 1):
68+
setup_requires = ['setuptools >= 17.1']
69+
extras_require.update({":python_version=='3.4'": below35_requires})
70+
extras_require.update({":python_version=='2.7'": below35_requires})
71+
else:
72+
extras_require.update({":python_version<'3.5'": below35_requires})
73+
74+
75+
setup(
76+
name='nirum-http',
77+
version=get_version(),
78+
description='Nirum HTTP transport for Python',
79+
long_description=readme(),
80+
url='https://github.com/spoqa/nirum-python-http',
81+
author='Kang Hyojun',
82+
author_email='iam.kanghyojun' '@' 'gmail.com',
83+
license='MIT license',
84+
py_modules=['nirum_http'],
85+
install_requires=install_requires,
86+
setup_requires=setup_requires,
87+
extras_require=extras_require
88+
)

test.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
from pytest import fixture
2+
from requests import Session
3+
from requests_mock import Adapter
4+
5+
from nirum_http import HttpTransport
6+
7+
8+
@fixture
9+
def fx_adapter():
10+
return Adapter()
11+
12+
13+
@fixture
14+
def fx_session(fx_adapter):
15+
s = Session()
16+
s.mount('http://', fx_adapter)
17+
s.mount('https://', fx_adapter)
18+
return s
19+
20+
21+
def test_call(fx_adapter, fx_session):
22+
def callback(request, context):
23+
return {'_type': 'point', 'x': 1.0, 'top': 2.0}
24+
method_name = 'hello_world'
25+
base_url = 'http://example.com/'
26+
url = '{0}?method={1}'.format(base_url, method_name)
27+
fx_adapter.register_uri('POST', url, json=callback)
28+
t = HttpTransport(base_url, session=fx_session)
29+
successful, result = t.call(
30+
method_name, payload={'name': 'John'},
31+
service_annotations={},
32+
method_annotations={},
33+
parameter_annotations={}
34+
)
35+
assert successful
36+
assert result == {'_type': 'point', 'x': 1.0, 'top': 2.0}

tox.ini

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
[tox]
2+
envlist = py27,py34,py35,py36,docs
3+
skipsdist = true
4+
5+
[testenv]
6+
skip_install = true
7+
commands =
8+
pip install -f {distdir} -e .[tests]
9+
pytest -v
10+
11+
[testenv:devruntime]
12+
; Use this when the tests against the Python source code generated by
13+
; the compiler require the bleeding-edge version of nirum-python runtime
14+
; (which is not released yet).
15+
skip_install = true
16+
deps =
17+
wget >= 3.2
18+
wheel >= 0.29.0
19+
changedir = {envtmpdir}
20+
whitelist_externals =
21+
mkdir
22+
commands =
23+
python -m wget -o devruntime.zip https://github.com/{env:DEVRUNTIME_REPO:spoqa/nirum-python}/archive/{env:DEVRUNTIME_REF:master}.zip
24+
python -m zipfile -e devruntime.zip .
25+
python -c 'import glob, os.path; [os.rename(f, os.path.join(".", os.path.basename(f))) for f in glob.glob("nirum-python-*/*")]'
26+
python setup.py sdist bdist_wheel
27+
mkdir {distdir}
28+
python -c 'import glob, os, sys; [os.rename(f, os.path.join(sys.argv[1], os.path.basename(f))) for f in glob.glob("dist/nirum-*")]' {distdir}
29+
30+
[testenv:docs]
31+
basepython = python3
32+
deps = docutils
33+
commands =
34+
rst2html.py --strict CHANGES.rst
35+
rst2html.py --strict README.rst
36+
python3 setup.py --long-description | rst2html.py --strict
37+
38+
[pytest]
39+
addopts = --ff --flake8 test.py
40+
41+
[flake8]
42+
exclude = .env, .tox
43+
import-order-style = spoqa
44+
application-import-names = nirum_http, tests

0 commit comments

Comments
 (0)