diff --git a/docs/sanic/examples.rst b/docs/sanic/examples.rst index d6e99d1f..e2a7af14 100644 --- a/docs/sanic/examples.rst +++ b/docs/sanic/examples.rst @@ -156,4 +156,12 @@ execution support provided by the ``pytest-xdist`` plugin. .. literalinclude:: ../../examples/pytest_xdist.py + +Amending Request Object +~~~~~~~~~~~~~~~~~~~~~~~ + +The ``request`` object in ``Sanic`` is a kind of ``dict`` object, this means that ``reqeust`` object can be manipulated as a regular ``dict`` object. + +.. literalinclude:: ../../examples/amending_request_object.py + For more examples and useful samples please visit the `Huge-Sanic's GitHub Page `_ diff --git a/examples/amending_request_object.py b/examples/amending_request_object.py new file mode 100644 index 00000000..55d889f7 --- /dev/null +++ b/examples/amending_request_object.py @@ -0,0 +1,30 @@ +from sanic import Sanic +from sanic.response import text +from random import randint + +app = Sanic() + + +@app.middleware('request') +def append_request(request): + # Add new key with random value + request['num'] = randint(0, 100) + + +@app.get('/pop') +def pop_handler(request): + # Pop key from request object + num = request.pop('num') + return text(num) + + +@app.get('/key_exist') +def key_exist_handler(request): + # Check the key is exist or not + if 'num' in request: + return text('num exist in request') + + return text('num does not exist in reqeust') + + +app.run(host="0.0.0.0", port=8000, debug=True)