mercredi 18 novembre 2020

How to fetch the json using fetch(js) in flask? [closed]

I am working on a simple flask project. The user selects a photo in a file field and I am going to imagga.com APIs to analyse the image and return some data related to image. It has only one py file which corresponds to flask and one which talks with API.

app.py

from flask import Flask, render_template, request
from api import get_cat

app = Flask(__name__)

ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}

app.config['SECRET_KEY'] = 'my_secret_key'

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@app.route('/', methods=['GET', 'POST'])
def main():
    if request.method=='GET':
        return render_template('index.html')
        

@app.route('/result', methods=['POST'])
def result():
    image = request.files['image']
    t = get_cat(image)
    return t

if __name__=="__main__":
    app.run(debug=True, host='0.0.0.0')
    

index.html

<form action='/result' method="POST" enctype="multipart/form-data">
    <input type="file" name="image">
    <input id='submit' type="submit">
</form>

<script type="text/javascript">
   fetch('/result')
  .then(response => response.json())
  .then(data => alert(data));
</script>

What I want to accomplish is that when the /result route returns the response, I want to fetch it using javascript and display the data in the same page as index.html but it just displays the data in the /result route in browser. Any Ideas how can I fix it?




Aucun commentaire:

Enregistrer un commentaire