(environ, start_response)
| 76 | |
| 77 | |
| 78 | def app(environ, start_response): |
| 79 | is_upgrade = environ.get("HTTP_UPGRADE", "").lower() == "websocket" |
| 80 | if not is_upgrade: |
| 81 | # A normal HTTP request must still work through the regular WSGI path. |
| 82 | body = b"not a websocket" |
| 83 | start_response( |
| 84 | "200 OK", |
| 85 | [ |
| 86 | ("Content-Type", "text/plain"), |
| 87 | ("Content-Length", str(len(body))), |
| 88 | ], |
| 89 | ) |
| 90 | return [body] |
| 91 | |
| 92 | sock = environ.get("werkzeug.socket") |
| 93 | if sock is None: |
| 94 | body = b"no socket in environ" |
| 95 | start_response( |
| 96 | "500 Internal Server Error", |
| 97 | [ |
| 98 | ("Content-Type", "text/plain"), |
| 99 | ("Content-Length", str(len(body))), |
| 100 | ], |
| 101 | ) |
| 102 | return [body] |
| 103 | |
| 104 | key = environ["HTTP_SEC_WEBSOCKET_KEY"] |
| 105 | _handshake(sock, key) |
| 106 | |
| 107 | # Echo text frames back with an "echo:" prefix until the peer closes. |
| 108 | while True: |
| 109 | try: |
| 110 | opcode, payload = _read_frame(sock) |
| 111 | except (ConnectionError, OSError): |
| 112 | break |
| 113 | if opcode == 0x8: # close |
| 114 | _write_frame(sock, 0x8, struct.pack("!H", 1000)) |
| 115 | break |
| 116 | if opcode == 0x1: # text |
| 117 | text = payload.decode("utf-8") |
| 118 | _write_frame(sock, 0x1, f"echo:{text}".encode()) |
| 119 | |
| 120 | return [] |
nothing calls this directly
no test coverage detected