I have image that is called 'image.png', first off i make request to my server to save image as base64 string in json file.
def get_img_content(coding='utf-8'):
with open('image.png', 'rb') as f:
img_data = base64.b64encode(f.read()).decode(coding)
return img_data
requests.get(f'http://127.0.0.1:5000/?face={get_img_content()}')
Bellow i've added server's code which handle my request
from flask import Flask, request
import os
import json
app = Flask(__name__)
if "data.json" not in os.listdir(os.getcwd()):
with open('data.json', 'a', encoding='utf-8') as f:
pass
content = {'ids': [], 'results': []}
else:
with open('data.json', 'r', encoding='utf-8') as f:
content = json.loads(f.read())
def add_id(id, face, content=content):
content['ids'].append({id: face})
with open('data.json', 'w', encoding='utf-8') as f:
f.write(json.dumps(content))
@app.route('/', methods=['GET'])
def main():
face = request.args.get('face')
if not face:
return 'Valid request has to contain face'
id = [int(list(i.keys())[0]) for i in content['ids']]
id = str(max(id) + 1 if id else 1)
add_id(id, face)
print(content)
return id
@app.route('/get', methods=['GET'])
def get():
id = request.args.get('id')
if not id:
return 'Valid request has to contain id'
for i in content['results']:
if list(i.keys())[0] == id:
return json.dumps({'result': i[id]})
return "Couldn't find result"
if __name__ == '__main__':
app.run()
After that i tried to read this base64 string from data.json and convert it to image, but i got PaddingError
binascii.Error: Incorrect padding
import base64
import json
with open('data.json', 'r', encoding='utf-8') as f:
content = json.loads(f.read())
def to_image():
with open('image.png', 'wb') as f:
f.write(base64.b64decode(list(content['ids'][0].items())[-1][-1].encode('utf-8')))
to_image()
Please help me to reproduce my steps without this error.