Skip to content

Instantly share code, notes, and snippets.

@TheWaWaR
Last active March 10, 2024 14:38
Show Gist options
  • Save TheWaWaR/bd26ef76dabca2d410dd to your computer and use it in GitHub Desktop.
Save TheWaWaR/bd26ef76dabca2d410dd to your computer and use it in GitHub Desktop.
Flask dump request and response example
#!/usr/bin/env python
# coding: utf-8
import os
import sys
import json
import uuid
import tempfile
from flask import Flask, request, Response, g
app = Flask(__name__)
app.debug = True
def save_request(uuid, request):
req_data = {}
req_data['uuid'] = uuid
req_data['endpoint'] = request.endpoint
req_data['method'] = request.method
req_data['cookies'] = request.cookies
req_data['data'] = request.data
req_data['headers'] = dict(request.headers)
req_data['headers'].pop('Cookie', None)
req_data['args'] = request.args
req_data['form'] = request.form
req_data['remote_addr'] = request.remote_addr
files = []
for name, fs in request.files.items():
dst = tempfile.NamedTemporaryFile()
fs.save(dst)
dst.flush()
filesize = os.stat(dst.name).st_size
dst.close()
files.append({'name': name, 'filename': fs.filename, 'filesize': filesize,
'mimetype': fs.mimetype, 'mimetype_params': fs.mimetype_params})
req_data['files'] = files
return req_data
def save_response(uuid, resp):
resp_data = {}
resp_data['uuid'] = uuid
resp_data['status_code'] = resp.status_code
resp_data['status'] = resp.status
resp_data['headers'] = dict(resp.headers)
resp_data['data'] = resp.response
return resp_data
@app.before_request
def before_request():
print(request.method, request.endpoint)
@app.after_request
def after_request(resp):
resp.headers.add('Access-Control-Allow-Origin', '*')
resp.headers.add('Access-Control-Allow-Headers', 'Content-Type, X-Token')
resp.headers.add('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE')
resp_data = save_response(g.uuid, resp)
print('Response:: ', json.dumps(resp_data, indent=4))
return resp
@app.route('/log', methods=['GET', 'POST'])
def log():
g.uuid = uuid.uuid1().hex
req_data = save_request(g.uuid, request)
resp = Response(json.dumps(req_data, indent=4, default=str), mimetype='application/json')
resp.set_cookie('cookie-name', value='cookie-value')
return resp
if __name__ == '__main__':
app.run('0.0.0.0', port=int(sys.argv[1]), debug=True)
@NexPlex
Copy link

NexPlex commented May 2, 2020

also getting byte error. resolved by adding "default=str" to line 57 and 69

print ('Response:: ', json.dumps(resp_data, indent=4, default=str))
Response(json.dumps(req_data, indent=4, default=str), mimetype='application/json')

@NexPlex
Copy link

NexPlex commented May 2, 2020

Very nice!! :)

@TheWaWaR
Copy link
Author

TheWaWaR commented May 2, 2020

Updated :)

@xavibt
Copy link

xavibt commented Oct 17, 2022

Hi I get this error, any clues?

POST None
127.0.0.1 - - [18/Oct/2022 00:03:02] "POST /api/v0/registresdisp HTTP/1.1" 500 -
Traceback (most recent call last):
File "/Users/xavier/Documents/Formacio/lamevaapi/env/lib/python3.9/site-packages/flask/ctx.py", line 49, in getattr
return self.dict[name]
KeyError: 'uuid'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/Users/xavier/Documents/Formacio/lamevaapi/env/lib/python3.9/site-packages/flask/app.py", line 2091, in call
return self.wsgi_app(environ, start_response)
File "/Users/xavier/Documents/Formacio/lamevaapi/env/lib/python3.9/site-packages/flask/app.py", line 2076, in wsgi_app
response = self.handle_exception(e)
File "/Users/xavier/Documents/Formacio/lamevaapi/env/lib/python3.9/site-packages/flask/app.py", line 2073, in wsgi_app
response = self.full_dispatch_request()
File "/Users/xavier/Documents/Formacio/lamevaapi/env/lib/python3.9/site-packages/flask/app.py", line 1519, in full_dispatch_request
return self.finalize_request(rv)
File "/Users/xavier/Documents/Formacio/lamevaapi/env/lib/python3.9/site-packages/flask/app.py", line 1540, in finalize_request
response = self.process_response(response)
File "/Users/xavier/Documents/Formacio/lamevaapi/env/lib/python3.9/site-packages/flask/app.py", line 1885, in process_response
response = self.ensure_sync(func)(response)
File "/Users/xavier/Documents/Formacio/lamevaapi/flask_dump_request_response.py", line 60, in after_request
resp_data = save_response(g.uuid, resp)
File "/Users/xavier/Documents/Formacio/lamevaapi/env/lib/python3.9/site-packages/flask/ctx.py", line 51, in getattr
raise AttributeError(name) from None
AttributeError: uuid

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment