Skip to content

Commit

Permalink
Merge 1036250 into c56ba63
Browse files Browse the repository at this point in the history
  • Loading branch information
Relrin committed Nov 28, 2016
2 parents c56ba63 + 1036250 commit e9aeaa0
Show file tree
Hide file tree
Showing 12 changed files with 66 additions and 37 deletions.
12 changes: 7 additions & 5 deletions aiorest_ws/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,27 +144,29 @@ def _init_factory(self, url, **options):
"""
Create a factory instance.
"""
debug = options.get('debug', False)

factory = self.factory(url, debug=debug)
log_level = options.get('log_level', 'info')
factory = self.factory(url)
factory.protocol = self.protocol
factory.log._set_log_level(log_level)
return factory

def _enable_compressing(self, factory, **options):
"""
Set compression message for factory, if defined.
"""
compress = options.get('compress', False)
accept_function = options.get('accept_function', accept)
protocol_options = {"perMessageCompressionAccept": accept_function}

if compress:
factory.setProtocolOptions(perMessageCompressionAccept=accept)
factory.setProtocolOptions(**protocol_options)

def _set_factory_router(self, factory, **options):
"""
Set users router for factory, if defined.
"""
router = options.get('router', None)
assert router, "Argument `router` must be defined for Application."
assert router, "Argument `router` must be defined for the Application."

factory.router = router
factory.router._middlewares = self.middlewares
Expand Down
1 change: 1 addition & 0 deletions aiorest_ws/utils/websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
def deflate_offer_accept(offers):
"""
Function to accept offers from the client.
NOTE: For using this you will need a "permessage-deflate" extension.
:param offers: iterable object (list, tuple), where every object
is instance of PerMessageDeflateOffer.
Expand Down
17 changes: 14 additions & 3 deletions docs/source/app.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ Application usage
This module provide :class:`Application` class, which used as entry point
for your REST applications with WebSockets.


Run a instance of application
-----------------------------

Expand All @@ -23,6 +22,7 @@ handler. It can be method-based:
from aiorest_ws.views import MethodBasedView
class HelloWorld(MethodBasedView):
def get(self, request, *args, **kwargs):
return "Hello, world!"
Expand Down Expand Up @@ -128,8 +128,9 @@ the next parameters:
then server REST with WebSockets will be available on the ``ws://127.0.0.1:8080/api``
or ``wss://127.0.0.1:8080/api`` (when SSL enabled)

- debug
If given, enable or disable debug mode. Default to ``False``
- log_level
If specified, set logging level. Default to ``'info'``. Available options are: ``'info'``,
``'debug'``, ``'critical'``, ``'error'``, ``'warn'``, ``'trace'``

- router
Router with registered endpoints
Expand All @@ -138,6 +139,10 @@ the next parameters:
- compress
Enable compressing for transmitted traffic. Default to ``False``

- accept_function
Function for compressing of transmitted traffic. Default function is ``aiorest_ws.utils.websocket.deflate_offer_accept``.
Using only when ``compress`` argument specified with ``True`` value.

Running with SSL
----------------

Expand Down Expand Up @@ -180,3 +185,9 @@ For enable this feature is enough to append ``compress`` parameter with
app = Application()
app.run(compress=True)
By default using deflate compression method which is provided by "permessage-deflate" extension. If you
want to change this behaviour to a custom, then specify ``accept_function`` argument with certain
functionality (as a function). For instance you can look on the
`example <https://github.com/crossbario/autobahn-python/tree/master/examples/twisted/websocket/echo_compressed>`_
of autobahn-python repository.
2 changes: 1 addition & 1 deletion examples/auth_token/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def onMessage(self, payload, isBinary):


if __name__ == '__main__':
factory = WebSocketClientFactory("ws://localhost:8080", debug=False)
factory = WebSocketClientFactory("ws://localhost:8080")
factory.protocol = AuthAPIClientProtocol

loop = asyncio.get_event_loop()
Expand Down
2 changes: 1 addition & 1 deletion examples/django_orm/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def onMessage(self, payload, isBinary):


if __name__ == '__main__':
factory = WebSocketClientFactory("ws://localhost:8080", debug=False)
factory = WebSocketClientFactory("ws://localhost:8080")
factory.protocol = HelloClientProtocol

loop = asyncio.get_event_loop()
Expand Down
14 changes: 9 additions & 5 deletions examples/function_based_api/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,28 @@ class HelloClientProtocol(WebSocketClientProtocol):

def onOpen(self):
# hello username
request = {'method': 'GET',
'url': '/hello/'}
request = {
'method': 'GET',
'url': '/hello/'
}
self.sendMessage(json.dumps(request).encode('utf8'))

# sum endpoint with arg in URL path (two random digits)
for _ in range(0, 10):
digit_1 = str(randint(1, 100))
digit_2 = str(randint(1, 100))
request = {'method': 'GET',
'url': '/sum/{0}/{1}'.format(digit_1, digit_2)}
request = {
'method': 'GET',
'url': '/sum/{0}/{1}'.format(digit_1, digit_2)
}
self.sendMessage(json.dumps(request).encode('utf8'))

def onMessage(self, payload, isBinary):
print("Result: {0}".format(payload.decode('utf8')))


if __name__ == '__main__':
factory = WebSocketClientFactory("ws://localhost:8080", debug=False)
factory = WebSocketClientFactory("ws://localhost:8080")
factory.protocol = HelloClientProtocol

loop = asyncio.get_event_loop()
Expand Down
22 changes: 14 additions & 8 deletions examples/method_based_api/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,31 +11,37 @@ class HelloClientProtocol(WebSocketClientProtocol):

def onOpen(self):
# hello username
request = {'method': 'GET',
'url': '/hello/'}
request = {
'method': 'GET',
'url': '/hello/'
}
self.sendMessage(json.dumps(request).encode('utf8'))

# hello endpoint with arg in URL path (`user` and random digit)
for _ in range(0, 10):
user_id = str(randint(1, 100))
request = {'method': 'GET',
'url': '/hello/user/' + user_id}
request = {
'method': 'GET',
'url': '/hello/user/' + user_id
}
self.sendMessage(json.dumps(request).encode('utf8'))

# send request and parameters are separately
digits = [randint(1, 10) for _ in range(3)]
print("calculate sum for {}".format(digits))
request = {'method': 'GET',
'url': '/calc/sum',
'args': {'digits': digits}}
request = {
'method': 'GET',
'url': '/calc/sum',
'args': {'digits': digits}
}
self.sendMessage(json.dumps(request).encode('utf8'))

def onMessage(self, payload, isBinary):
print("Result: {0}".format(payload.decode('utf8')))


if __name__ == '__main__':
factory = WebSocketClientFactory("ws://localhost:8080", debug=False)
factory = WebSocketClientFactory("ws://localhost:8080")
factory.protocol = HelloClientProtocol

loop = asyncio.get_event_loop()
Expand Down
3 changes: 3 additions & 0 deletions examples/method_based_api/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,19 @@


class HelloWorld(MethodBasedView):

def get(self, request, *args, **kwargs):
return "Hello, username!"


class HelloWorldCustom(MethodBasedView):

def get(self, request, user, id, *args, **kwargs):
return "Hello, {0} with ID={1}".format(user, id)


class CalculateSum(MethodBasedView):

def get(self, request, *args, **kwargs):
try:
digits = kwargs['params']['digits']
Expand Down
2 changes: 1 addition & 1 deletion examples/sqlalchemy_orm/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def onMessage(self, payload, isBinary):


if __name__ == '__main__':
factory = WebSocketClientFactory("ws://localhost:8080", debug=False)
factory = WebSocketClientFactory("ws://localhost:8080")
factory.protocol = HelloClientProtocol

loop = asyncio.get_event_loop()
Expand Down
2 changes: 1 addition & 1 deletion requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
alabaster>=0.7.5
autobahn==0.12.1
autobahn==0.16.0
cov-core==1.15.0
coverage==4.0.3
Django==1.10.2
Expand Down
8 changes: 5 additions & 3 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@
version = str(ast.literal_eval(_version_re.search(
f.read().decode('utf-8')).group(1)))

requirements = ['autobahn>=0.12.1', ]
test_requirements = requirements + ['pytest', 'pytest-asyncio',
'pytest-cov', 'pytest-xdist']
requirements = ['autobahn==0.16.0', ]
test_requirements = requirements + [
'pytest', 'pytest-asyncio',
'pytest-cov', 'pytest-xdist'
]


def read(f):
Expand Down
18 changes: 9 additions & 9 deletions tests/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,21 +126,21 @@ def test_get_ssl_context_4(self):
def test_init_factory(self):
url = self.app.generate_url('127.0.0.1', 8080)
factory = self.app._init_factory(url)
self.assertFalse(factory.debug)
self.assertEqual(factory.log._log_level, 'info')
self.assertEqual(factory.protocol, RequestHandlerProtocol)

def test_init_factory_2(self):
url = self.app.generate_url('127.0.0.1', 8080)
options = {'debug': False}
options = {'log_level': 'info'}
factory = self.app._init_factory(url, **options)
self.assertFalse(factory.debug)
self.assertEqual(factory.log._log_level, 'info')
self.assertEqual(factory.protocol, RequestHandlerProtocol)

def test_init_factory_3(self):
url = self.app.generate_url('127.0.0.1', 8080)
options = {'debug': True}
options = {'log_level': 'debug'}
factory = self.app._init_factory(url, **options)
self.assertTrue(factory.debug)
self.assertEqual(factory.log._log_level, 'debug')
self.assertEqual(factory.protocol, RequestHandlerProtocol)

def test_enable_compressing(self):
Expand Down Expand Up @@ -187,23 +187,23 @@ class CustomRouter(SimpleRouter):
def test_generate_factory(self):
url = self.app.generate_url('127.0.0.1', 8080)
factory = self.app.generate_factory(
url, debug=True, router=SimpleRouter()
url, log_level='debug', router=SimpleRouter()
)
self.assertTrue(factory.debug)
self.assertEqual(factory.log._log_level, 'debug')
self.assertIsInstance(factory.router, SimpleRouter)

def test_generate_factory_2(self):
url = self.app.generate_url('127.0.0.1', 8080)
factory = self.app.generate_factory(url, router=SimpleRouter())
self.assertFalse(factory.debug)
self.assertEqual(factory.log._log_level, 'info')
self.assertIsInstance(factory.router, SimpleRouter)

def test_generate_factory_3(self):
url = self.app.generate_url('127.0.0.1', 8080)
factory = self.app.generate_factory(
url, router=SimpleRouter(), compress=True
)
self.assertFalse(factory.debug)
self.assertEqual(factory.log._log_level, 'info')
self.assertIsInstance(factory.router, SimpleRouter)
self.assertEqual(factory.perMessageCompressionAccept, accept)

Expand Down

0 comments on commit e9aeaa0

Please sign in to comment.