Skip to content

Instantly share code, notes, and snippets.

@bholagabbar
Last active February 14, 2018 07:05
Show Gist options
  • Save bholagabbar/92a20aeb64bc7fe33d9ec810cdbd159d to your computer and use it in GitHub Desktop.
Save bholagabbar/92a20aeb64bc7fe33d9ec810cdbd159d to your computer and use it in GitHub Desktop.
Modify raw Flask responses to Flask JSON Responses
import os
from tempfile import mkstemp
from shutil import move
from os import fdopen, remove
import re
return_pattern = re.compile(r'return json\.dumps.*')
import_pattern = re.compile(r'from flask import.*')
for filename in os.listdir(os.path.dirname(os.path.realpath(__file__))):
if filename.endswith(".py") and not filename.endswith('.pyc') and filename != os.path.basename(__file__):
# Create temp file
fh, abs_path = mkstemp()
with fdopen(fh, 'w') as new_file:
with open(filename) as old_file:
for line in old_file:
if return_pattern.search(line):
# new_file.write(line)
line_arr = line.split(",")
tab_line = ''
for char in line_arr[0]:
if char != 'r':
tab_line += char
else:
break
for i in range(0, len(line_arr)):
line_arr[i] = line_arr[i].strip()
if i == 0:
line_arr[0] = line_arr[0].split('return')[1].strip()
if len(line_arr) == 1:
new_line = tab_line + 'return Response(response=%s, mimetype=\'application/json\')\n' % (line_arr[0])
new_file.write(new_line)
elif len(line_arr) == 2:
new_line = tab_line + 'return Response(response=%s, status=%s, mimetype=\'application/json\')\n' % (line_arr[0], line_arr[1])
new_file.write(new_line)
elif len(line_arr) == 3:
new_line = tab_line + 'return Response(response=%s, status=%s, mimetype=\'application/json\')\n' % (line_arr[0] + ', ' + line_arr[1], line_arr[2])
new_file.write(new_line)
else:
raise Exception('Responses with more than 2 commas, add code')
elif import_pattern.search(line):
new_line = line.strip() + ', Response\n'
new_file.write(new_line)
else:
new_file.write(line)
# Remove original file
remove(filename)
# Move new file
move(abs_path, filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment