Development/Python
[python] request body 출력
하 선생
2022. 4. 4. 11:56
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.exceptions import HTTPException
from json.decoder import JSONDecodeError
import uvicorn
app = Starlette(debug=True)
@app.exception_handler(JSONDecodeError)
async def log_exceptions(request, exc):
body: bytes = await request.body() # hangs forever
body_text: str = bytes.decode(body)
assert body_text, "I could not retrieve the body"
return JSONResponse({ "error": "Unexpected error happened!" })
@app.route('/api', methods=["POST"])
async def homepage(request):
body_bytes = await request.body()
if body_bytes:
json = await request.json()
print(json)
print("-----")
print(request.headers)
return JSONResponse(json)
return JSONResponse({ "error": "empty body, please send something" })
if __name__ == '__main__':
uvicorn.run(app, host='0.0.0.0', port=7000)