Carlos Aguni

Highly motivated self-taught IT analyst. Always learning and ready to explore new skills. An eternal apprentice.


Flask return image from base64

22 Dec 2021 »
from flask import Flask, request, jsonify, json, abort, redirect, url_for, render_template, send_file
from flask_cors import CORS, cross_origin
import os
import io
import re
import subprocess
import traceback
import flatdict
import threading
import time
import base64
import requests

app = Flask(__name__, template_folder='template')
cors = CORS(app)


@app.route('/', methods=['GET', 'POST'])
@app.route('/<ttt>', methods=['GET', 'POST'])
def home(ttt=""):
    
    ret = {}

    rs = requests.get("http://api-dupi2.local.com/image/8e18eb106f994b43a509bffea9549583.png")

    benc = base64.b64encode(rs.content).decode('utf-8')

    print("ttt", ttt, type(ttt))

    if ttt == "":
        print("here")
        b = "data:image/png;base64,"+benc
        return jsonify(b)
    elif ttt == "image":
        b = base64.b64decode(benc.encode('utf-8'))
        buf = io.BytesIO(b)
        buf.seek(0)
        return send_file(buf, mimetype="image/png")


    return jsonify(ret)




# gunicorn --workers=2 'app:create_app()' --bind=0.0.0.0:<port>
def create_app():
    return app

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=9000)
    
    #test 
    #with app.test_client() as c:
    #    rs = c.get("/")
    #    print(rs.data)