async def fan_out(request, receiver): while True: yield (ws_send(f"current-time-stamp {time.time()}")) await asyncio.sleep(1) @websocket async def one_to_one(request, receiver): async for message in receiver: if message == "hello": yield ws_send("hello beautiful") elif message == "exit": yield ws_send("byebye") break elif message == "i like you": yield ws_send("That is very nice! I like you too!") else: yield ws_send("pardon me. I do not have a reply to this") routes = [ ("/fan-in", ["WS"], fan_in), ("/fan-out", ["WS"], fan_out), ("/chatbot", ["WS"], one_to_one), ] app = build_server(apply_middleware(wrap_routes(routes))(standard_not_found)) if __name__ == "__main__": import uvicorn uvicorn.run(app)
asyncio.ensure_future(t) while True: item = await q.get() yield item @websocket async def chatroom(scope, receiver, name): client_msgs = named_receiver(name, receiver) broadcast_messages = receive_from_broadcast(name) async for user_name, message in merge(client_msgs, broadcast_messages): if user_name == name: send_broadcast(name, message) else: yield ws_send(f"@{user_name}: {message}") async def alive(request): return json({"alive": True}) app = build_server( apply_middleware( wrap_routes([("/chat/{name}", ["WS"], chatroom), ("/", ["GET"], alive)]))(standard_not_found)) if __name__ == "__main__": import uvicorn uvicorn.run(app)
"name": "apple" } } async def fruit_collection(request): return json({"fruits": list(fruit_store.keys())}) async def fruit_details(request, fruit_name): return json(fruit_store[fruit_name]) async def change_quantity(request): data = request["json"] for fruit_name, new_qt in data.items(): fruit_store[fruit_name]["qty"] = new_qt return json({"updated": list(data.keys())}) routes = [("/fruits", ["GET"], fruit_collection), ("/fruits/{name}", ["GET"], fruit_details), ("/fruits", ["POST"], change_quantity)] middlewares = apply_middleware(wrap_json, wrap_routes(routes)) fruit_app = build_server(middlewares(not_found)) if __name__ == "__main__": import uvicorn uvicorn.run(fruit_app, host="127.0.0.1", port=5000, debug=True)
import sys import time here = os.path.dirname(__file__) tutorials_path = os.path.join(here, "..", "tutorial") sys.path.append(tutorials_path) from tutorial_04 import app as _simple_ws_app @websocket async def never_collect_messages(scope, receiver): while True: await asyncio.sleep(1) ws_never_collect = running_sever_fixture(build_server(never_collect_messages)) ws_simple = running_sever_fixture(_simple_ws_app) @pytest.mark.asyncio @pytest.mark.skip async def test_never_collect_messages(ws_never_collect): index = 0 bytes_send = 0.0 async with websockets.connect(ws_never_collect.replace("http", "ws")) as ws: while True: index += 1 data = "testdata" * 128 * int(1024) bytes_send += len(data) / (1024)
from shallot import build_server from shallot.response import text from shallot.middlewares import apply_middleware, wrap_static, wrap_content_type async def greetings(request): user_agent = request["headers"].get("user-agent") return text(f"Special greetings to you: {user_agent}") middlewares = apply_middleware( wrap_content_type(), wrap_static("./static"), ) greet_and_static_handler = middlewares(greetings) hello_world_app = build_server(greet_and_static_handler) if __name__ == "__main__": import uvicorn uvicorn.run(hello_world_app, host="127.0.0.1", port=5000, debug=True)
from urllib.parse import quote, unquote from .helper import running_sever_fixture, st_hpath_list from shallot.middlewares import wrap_static encoding = sys.getfilesystemencoding() __here__ = os.path.dirname(__file__) __test_data__ = "../test/data" async def noop_handler(request): return {"status": 218, "body": request["path"].encode()} handler = apply_middleware(wrap_static(__test_data__, __here__))(noop_handler) running_server = running_sever_fixture(build_server(handler)) @given(st.text()) def test_arbitrary_text_does_not_result_in_500(running_server, path): result = requests.get(running_server + path) assert result.status_code in {200, 218}, f"{result}, {result.content}" @given(st_hpath_list) def test_hpath(running_server, http_path): http_path = "/".join(http_path) result = requests.get(running_server + http_path) assert result.status_code in {200, 218, 404}, f"{result}, {result.content}"
from shallot import build_server from shallot.response import text async def greetings(request): user_agent = request["headers"].get("user-agent") return text(f"Special greetings to you: {user_agent}") hello_world_app = build_server(greetings) if __name__ == "__main__": import uvicorn uvicorn.run(hello_world_app, host="127.0.0.1", port=5000, debug=True)
async def test_app_handler_exposes_asgi_interface_for_ws(): app = build_server(raw_asgi_wrapper) response = await (app({"type": "websocket"})(receive_raise, send_none)) assert response is raw_asgi_handler
async def test_app_handler_adds_WS_as_method_for_websockets(): app = build_server(_handle_identity) response = await (app({"type": "websocket"})(receive_raise, send_none)) assert "method" in response assert response["method"] == "WS"