Skip to content

Commit cf12312

Browse files
author
Joel Collins
committed
Support websocket methods in View class
1 parent fc91f04 commit cf12312

File tree

1 file changed

+19
-14
lines changed

1 file changed

+19
-14
lines changed

src/labthings/views/__init__.py

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from flask.views import MethodView, http_method_funcs
2-
from flask import request
2+
from flask import request, abort
33
from werkzeug.wrappers import Response as ResponseBase
44
from werkzeug.exceptions import BadRequest
55

@@ -107,19 +107,29 @@ def get_value(self):
107107
else: # Unless somehow an HTTP response isn't returned...
108108
return response
109109

110+
def _find_request_method(self):
111+
meth = getattr(self, request.method.lower(), None)
112+
if meth is None and request.method == "HEAD":
113+
meth = getattr(self, "get", None)
114+
115+
# Handle the case of a GET request asking for WS upgrade where
116+
# no websocket method is defined on the view
117+
if request.method == "GET" and request.environ.get("wsgi.websocket"):
118+
ws_meth = getattr(self, "websocket", None)
119+
if ws_meth is None:
120+
abort(400, "Unable to upgrade websocket connection")
121+
return ws_meth
122+
123+
return meth
124+
110125
def dispatch_request(self, *args, **kwargs):
111126
"""
112127
113128
:param *args:
114129
:param **kwargs:
115130
116131
"""
117-
meth = getattr(self, request.method.lower(), None)
118-
119-
# If the request method is HEAD and we don't have a handler for it
120-
# retry with GET.
121-
if meth is None and request.method == "HEAD":
122-
meth = getattr(self, "get", None)
132+
meth = self._find_request_method()
123133

124134
# Generate basic response
125135
return self.represent_response(meth(*args, **kwargs))
@@ -272,7 +282,7 @@ def dispatch_request(self, *args, **kwargs):
272282
:param **kwargs:
273283
274284
"""
275-
meth = getattr(self, request.method.lower(), None)
285+
meth = self._find_request_method()
276286

277287
# Let base View handle non-POST requests
278288
if request.method != "POST":
@@ -414,12 +424,7 @@ def dispatch_request(self, *args, **kwargs):
414424
:param **kwargs:
415425
416426
"""
417-
meth = getattr(self, request.method.lower(), None)
418-
419-
# If the request method is HEAD and we don't have a handler for it
420-
# retry with GET.
421-
if meth is None and request.method == "HEAD":
422-
meth = getattr(self, "get", None)
427+
meth = self._find_request_method()
423428

424429
# POST and PUT methods can be used to write properties
425430
# In all other cases, ignore arguments

0 commit comments

Comments
 (0)