async def err_middleware(ctx: Context, nxt): ctx.body = {'msg': 'err_middleware'} try: await nxt() except Exception: ctx.body = {'msg': 'error handled'} ctx.status = 400
async def lemon_error_middleware(ctx: Context, nxt): """Catch the final exception""" try: await nxt() except HttpError as e: ctx.body = e.body ctx.status = e.status except Exception as e: error_logger.error(e) ctx.status = 500 ctx.body = ctx.body or 'INTERNAL ERROR'
async def exception_middleware(ctx: Context, nxt: typing.Callable) -> typing.Any: """Catch the final exception""" try: return await nxt() except GeneralException as e: ctx.body = e.body ctx.status = e.status except Exception as e: traceback.print_exc() ctx.status = 500 ctx.body = ctx.body or { 'lemon': 'INTERNAL ERROR', }
async def test_set_context(self): ctx = Context() ctx.body = { 'a': 1, } ctx.req = await Request.from_asgi_interface({ 'channel': 'http.request', 'server': ('127.0.0.1', 9999), 'client': ('127.0.0.1', 58175), 'scheme': 'http', 'http_version': '0.0', 'method': 'POST', 'path': '/', 'query_string': b'', 'headers': [ [b'content-type', b'application/x-www-form-urlencoded'], [b'cache-control', b'no-cache'], [b'postman-token', b'e279159d-6af2-45da-87ac-1a331f317a60'], [b'user-agent', b'PostmanRuntime/7.1.1'], [b'accept', b'*/*'], [b'host', b'127.0.0.1:9999'], [b'accept-encoding', b'gzip, deflate'], [b'content-length', b'11'], [b'connection', b'keep-alive'], ] }, {}) assert ctx.body['a'] == 1 assert ctx.res.body['a'] == 1 assert id(ctx.res.body) == id(ctx.body) assert id(ctx.res.status) == id(ctx.status)
async def handle(ctx: Context): my_cookie = ctx.req.cookies.get('my_cookie') my_cookie2 = ctx.req.cookies.get('my_cookie2') ctx.body = { 'my_cookie': my_cookie, 'my_cookie2': my_cookie2, }
async def handler(ctx: Context): server_recv = int(time.time() * 1000) # do something server_resp = int(time.time() * 1000) ctx.body = { 'server_recv': server_recv, 'server_resp': server_resp, }
async def correct(ctx: Context): data = ctx.req.json content = data['content'] ret = zh_checker.correct(content=content) ret = [r.to_json() for r in ret] ctx.body = { 'data': ret, }
async def handle(ctx: Context): ctx.body = { 'ok': True, }
async def handle(ctx: Context): data = ctx.req.data ctx.body = { 'file_content': data['file'].read().decode(), }
async def handle(ctx: Context): ctx.body = { 'ack': 'yeah !', }
async def handle(ctx: Context): data = ctx.req.json ctx.body = { 'hi': data['hi'], }
async def handle(ctx: Context): ctx.body = ctx.req.json
async def handle(ctx: Context): ctx.body = 'xxxxxx'
async def handle(ctx: Context): ctx.body = { 'ack': 'ok', }
async def health(ctx: Context): ctx.body = {'success': True}
async def handle(ctx: Context): ctx.body = {"msg": "hello world"}
async def middleware(ctx: Context, nxt): ctx.body = { 'msg': 'hello world' } await nxt()
async def handle(ctx: Context): data = ctx.req.data ctx.body = { 'ack': data['xxx'].read().decode(), }