Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add an example of health check.
Browse files Browse the repository at this point in the history
Fix #354.
aaugustin committed May 5, 2018
1 parent d851f57 commit 849666b
Showing 2 changed files with 25 additions and 1 deletion.
5 changes: 4 additions & 1 deletion docs/deployment.rst
Original file line number Diff line number Diff line change
@@ -75,4 +75,7 @@ widely different operational characteristics of HTTP and WebSocket.

``websockets`` provide minimal support for responding to HTTP requests with
the :meth:`~server.WebSocketServerProtocol.process_request()` hook. Typical
use cases include health checks.
use cases include health checks. Here's an example:

.. literalinclude:: ../example/health_check_server.py
:emphasize-lines: 7-11,17-18
21 changes: 21 additions & 0 deletions example/health_check_server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#!/usr/bin/env python

import asyncio
import http
import websockets

class ServerProtocol(websockets.WebSocketServerProtocol):

async def process_request(self, path, request_headers):
if path == '/__health__/':
return http.HTTPStatus.OK, [], b'OK\n'

async def echo(websocket, path):
async for message in websocket:
await websocket.send(message)

start_server = websockets.serve(
echo, 'localhost', 8765, create_protocol=ServerProtocol)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

2 comments on commit 849666b

@ddehghan
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would add to that

elif path not in ['/', '/socket']:
return BAD_REQUEST, [('Content-Length', 0)], ""

otherwise just going to the root of the domain will cause exceptions that will propagate to Pager Duty !

Bots that visit your domain will cause lots of errors.

Your example might as well built in some best practices. It is good to make a recommendation to name your url end point '/socket' so that you can filter out the socket requests explicitly from random connection to root of the domain by bots.

@aaugustin
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, there's room for further improvements to solve #369 — perhaps improvements to the code and not just examples in the docs.

Please sign in to comment.