示例#1
0
def cookie_handler():
    async def noop(request):
        return {
            "request_cookies": request.get("cookies"),
            "cookies": {"a": {"value": "tasty_tomato"}, "b": {"value": 12, "secure": True}}
        }
    return apply_middleware(wrap_cookies)(noop)
示例#2
0
async def test_default_content_types_for_unknown_ext_can_be_overridden():
    async def stream_handler(request):
        return {"stream": "asf"}

    content_type = apply_middleware(
        wrap_content_type(default_content_type="app/buba"))
    response = await content_type(stream_handler)({
        "path":
        "some/path/t/no/extension"
    })
    assert "app/buba" == response["headers"]["content-type"]
示例#3
0
async def return_cookie_values_from_handler(handler, request=None):
    request = {} if request is None else request
    http_handler = apply_middleware(wrap_cookies)(handler)
    response = await http_handler(request)
    values = list(map(lambda x: x[1], response["cookies"].items()))
    return values
示例#4
0
        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)
示例#5
0
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)
示例#6
0
def parameters():
    return apply_middleware(wrap_parameters())(return_request)
示例#7
0
def json_middleware():
    return apply_middleware(wrap_json)
示例#8
0
def staticfiles_handler():
    return apply_middleware(wrap_static("./data", __here__))(noop_handler)
示例#9
0
        "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)
示例#10
0
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)
示例#11
0
import os
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}"
示例#12
0
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)


async def handle_any_request(request):
    return json({
        "query_string": request["query_string"].decode(),
        "params": request["params"],
        "query_params": request["query_params"],
        "form_params": request["form_params"],
    })


handler = apply_middleware(
    wrap_parameters(keep_blank_values=True))(handle_any_request)
running_server = running_sever_fixture(build_server(handler))


@given(st.text())
@settings(max_examples=1000)
def test_arbitrary_query_strings_dont_return_500(running_server, qstring):
    url = running_server + "a?" + qstring
    response = requests.get(url)
    assert response.status_code == 200, f"Error for url {url}, reponse: {response.content}"


@given(st_query_list)
@settings(max_examples=1000)
def test_all_qstrings_can_be_grouped_and_joined_for_forms_and_standard_queries_url(
        running_server, queries):
示例#13
0
def content_type():
    add_mapping = {"application/fruit": [".apple", "orange"]}
    return apply_middleware(
        wrap_content_type(additional_content_types=add_mapping))
示例#14
0

@websocket
async def echo_server(request, receiver):
    async for message in receiver:
        yield ws_send(f"@echo: {message}")


@websocket
async def print_out_server(request, receiver):
    async for message in receiver:
        print(message)
        if message == "exit":
            raise Exception("Boom")


routes = [
    ("/echo", ["WS"], echo_server),
    ("/print-out", ["WS"], print_out_server)

]

app = build_server(
    apply_middleware(
        wrap_routes(routes)
    )(standard_not_found)
)

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app)