Skip to content

Add headers & query params to websocket handler object #115

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
12 changes: 12 additions & 0 deletions tests/test_query_parse.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from websocket_server import WebSocketHandler


def test_websocket_handler_query_parse():
case1 = WebSocketHandler.parse_query("GET /?a=hello HTTP/1.1")
case2 = WebSocketHandler.parse_query("GET / HTTP/1.1")
case3 = WebSocketHandler.parse_query("GET /?a=hello&b=world HTTP/1.1")
case4 = WebSocketHandler.parse_query("GET /?a=hello&a=world HTTP/1.1")
assert case1 == {'a': ['hello']}
assert case2 == {}
assert case3 == {'a': ['hello'], 'b': ['world']}
assert case4 == {'a': ['hello', 'world']}
15 changes: 15 additions & 0 deletions websocket_server/websocket_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import errno
import threading
from socketserver import ThreadingMixIn, TCPServer, StreamRequestHandler
from urllib.parse import urlparse, parse_qs

from websocket_server.thread import WebsocketServerThread

Expand Down Expand Up @@ -261,6 +262,8 @@ class WebSocketHandler(StreamRequestHandler):

def __init__(self, socket, addr, server):
self.server = server
self.headers = {}
self.query_params = {}
assert not hasattr(self, "_send_lock"), "_send_lock already exists"
self._send_lock = threading.Lock()
if server.key and server.cert:
Expand Down Expand Up @@ -412,6 +415,16 @@ def send_text(self, message, opcode=OPCODE_TEXT):
with self._send_lock:
self.request.send(header + payload)

@staticmethod
def parse_query(http_get):
"""
Parses the query parameters from the first line.
Example: "GET /?q=hello HTTP/1.1" will be parsed to {'q': ['hello']}
"""
query = http_get.split(" ")[1] # example: http_get = "GET /?q=hello HTTP/1.1"
parsed_url = urlparse(query)
return parse_qs(parsed_url.query)

def read_http_headers(self):
headers = {}
# first line should be HTTP GET
Expand All @@ -424,6 +437,8 @@ def read_http_headers(self):
break
head, value = header.split(':', 1)
headers[head.lower().strip()] = value.strip()
self.headers = headers
self.query_params = WebSocketHandler.parse_query(http_get)
return headers

def handshake(self):
Expand Down