Flask returns HTTP code 0 when sending file












0















I have a Flask web app that uploads images to a machine learning model and returns predictions in a zip file. For the sake of simplicity, the code in this example simply uploads the images and returns them in a zip. I also implemented flask-dropzone in the html.



This is the error code that i get when the send_from_directory line is executed



"GET /horus/download HTTP/1.1" 0 


interface.html



<body>
<h3>Welcome to Horus&trade; v1.0</h3>

{{ dropzone.create(action=url_for('predict')) }}
<button class="btn waves-effect waves-light btn-large" id="upload">Upload
<i class="material-icons right">send</i>
</button>

{{ dropzone.load_js() }}
{{ dropzone.config(custom_options='addRemoveLinks: true,dictRemoveFileConfirmation:"Are you sure you want to remove this file?" ') }}
</body>
</html>


app.py



import base64
import zipfile
import json
import requests
import os
from flask import Flask, request,jsonify,render_template,url_for,redirect,send_from_directory,current_app,send_file,after_this_request
from werkzeug import secure_filename
from keras.preprocessing import image
from lib.JsonToXML import convert

from flask_dropzone import Dropzone
from flask_cors import CORS, cross_origin



app = Flask(__name__)
CORS(app)
app.config['CORS_HEADERS']='Content-Type'
app.config.update(
DROPZONE_ALLOWED_FILE_CUSTOM = True,
DROPZONE_ALLOWED_FILE_TYPE = '.JPG,.JPEG,.jpg,.jpeg',
DROPZONE_UPLOAD_ON_CLICK = True,
DROPZONE_UPLOAD_MULTIPLE = True,
DROPZONE_DEFAULT_MESSAGE = 'Drop files here to upload or click here to open File Explorer. Allowed file extensions: .jpg, .jpeg'
)



dropzone = Dropzone(app)

@app.route('/horus/predict/v1', methods=['POST','GET'])

def predict():

if request.method == 'POST':


for key,files in request.files.items():
if key.startswith('file'):
print(files)
files.save('output/'+ secure_filename(files.filename))


return redirect(url_for('download'))
else:
return render_template('interface.html')

@app.route('/horus/download',methods=['GET'])
@cross_origin(origin='*')
def download():

uploads = os.path.join(current_app.root_path,'output/')
zfile = zipfile.ZipFile('output/Annotations.zip','w',zipfile.ZIP_DEFLATED)

for xfile in os.listdir(uploads):
if xfile.endswith('.jpg'):
zfile.write('output/'+xfile)

zfile.close()

for files in os.listdir(uploads):
if files.endswith('.zip')==False:
os.remove(uploads+files)
print(files + ' deleted.')

return send_from_directory(uploads,'Annotations.zip',as_attachment=True)


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


Prior to this, i tested the API with a normal form and it worked just fine. This issue happened after i implemented flask-dropzone. I also tried implementing flask-cors but the result is the same. I am currently at a dead end and any help is greatly appreciated.










share|improve this question



























    0















    I have a Flask web app that uploads images to a machine learning model and returns predictions in a zip file. For the sake of simplicity, the code in this example simply uploads the images and returns them in a zip. I also implemented flask-dropzone in the html.



    This is the error code that i get when the send_from_directory line is executed



    "GET /horus/download HTTP/1.1" 0 


    interface.html



    <body>
    <h3>Welcome to Horus&trade; v1.0</h3>

    {{ dropzone.create(action=url_for('predict')) }}
    <button class="btn waves-effect waves-light btn-large" id="upload">Upload
    <i class="material-icons right">send</i>
    </button>

    {{ dropzone.load_js() }}
    {{ dropzone.config(custom_options='addRemoveLinks: true,dictRemoveFileConfirmation:"Are you sure you want to remove this file?" ') }}
    </body>
    </html>


    app.py



    import base64
    import zipfile
    import json
    import requests
    import os
    from flask import Flask, request,jsonify,render_template,url_for,redirect,send_from_directory,current_app,send_file,after_this_request
    from werkzeug import secure_filename
    from keras.preprocessing import image
    from lib.JsonToXML import convert

    from flask_dropzone import Dropzone
    from flask_cors import CORS, cross_origin



    app = Flask(__name__)
    CORS(app)
    app.config['CORS_HEADERS']='Content-Type'
    app.config.update(
    DROPZONE_ALLOWED_FILE_CUSTOM = True,
    DROPZONE_ALLOWED_FILE_TYPE = '.JPG,.JPEG,.jpg,.jpeg',
    DROPZONE_UPLOAD_ON_CLICK = True,
    DROPZONE_UPLOAD_MULTIPLE = True,
    DROPZONE_DEFAULT_MESSAGE = 'Drop files here to upload or click here to open File Explorer. Allowed file extensions: .jpg, .jpeg'
    )



    dropzone = Dropzone(app)

    @app.route('/horus/predict/v1', methods=['POST','GET'])

    def predict():

    if request.method == 'POST':


    for key,files in request.files.items():
    if key.startswith('file'):
    print(files)
    files.save('output/'+ secure_filename(files.filename))


    return redirect(url_for('download'))
    else:
    return render_template('interface.html')

    @app.route('/horus/download',methods=['GET'])
    @cross_origin(origin='*')
    def download():

    uploads = os.path.join(current_app.root_path,'output/')
    zfile = zipfile.ZipFile('output/Annotations.zip','w',zipfile.ZIP_DEFLATED)

    for xfile in os.listdir(uploads):
    if xfile.endswith('.jpg'):
    zfile.write('output/'+xfile)

    zfile.close()

    for files in os.listdir(uploads):
    if files.endswith('.zip')==False:
    os.remove(uploads+files)
    print(files + ' deleted.')

    return send_from_directory(uploads,'Annotations.zip',as_attachment=True)


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


    Prior to this, i tested the API with a normal form and it worked just fine. This issue happened after i implemented flask-dropzone. I also tried implementing flask-cors but the result is the same. I am currently at a dead end and any help is greatly appreciated.










    share|improve this question

























      0












      0








      0








      I have a Flask web app that uploads images to a machine learning model and returns predictions in a zip file. For the sake of simplicity, the code in this example simply uploads the images and returns them in a zip. I also implemented flask-dropzone in the html.



      This is the error code that i get when the send_from_directory line is executed



      "GET /horus/download HTTP/1.1" 0 


      interface.html



      <body>
      <h3>Welcome to Horus&trade; v1.0</h3>

      {{ dropzone.create(action=url_for('predict')) }}
      <button class="btn waves-effect waves-light btn-large" id="upload">Upload
      <i class="material-icons right">send</i>
      </button>

      {{ dropzone.load_js() }}
      {{ dropzone.config(custom_options='addRemoveLinks: true,dictRemoveFileConfirmation:"Are you sure you want to remove this file?" ') }}
      </body>
      </html>


      app.py



      import base64
      import zipfile
      import json
      import requests
      import os
      from flask import Flask, request,jsonify,render_template,url_for,redirect,send_from_directory,current_app,send_file,after_this_request
      from werkzeug import secure_filename
      from keras.preprocessing import image
      from lib.JsonToXML import convert

      from flask_dropzone import Dropzone
      from flask_cors import CORS, cross_origin



      app = Flask(__name__)
      CORS(app)
      app.config['CORS_HEADERS']='Content-Type'
      app.config.update(
      DROPZONE_ALLOWED_FILE_CUSTOM = True,
      DROPZONE_ALLOWED_FILE_TYPE = '.JPG,.JPEG,.jpg,.jpeg',
      DROPZONE_UPLOAD_ON_CLICK = True,
      DROPZONE_UPLOAD_MULTIPLE = True,
      DROPZONE_DEFAULT_MESSAGE = 'Drop files here to upload or click here to open File Explorer. Allowed file extensions: .jpg, .jpeg'
      )



      dropzone = Dropzone(app)

      @app.route('/horus/predict/v1', methods=['POST','GET'])

      def predict():

      if request.method == 'POST':


      for key,files in request.files.items():
      if key.startswith('file'):
      print(files)
      files.save('output/'+ secure_filename(files.filename))


      return redirect(url_for('download'))
      else:
      return render_template('interface.html')

      @app.route('/horus/download',methods=['GET'])
      @cross_origin(origin='*')
      def download():

      uploads = os.path.join(current_app.root_path,'output/')
      zfile = zipfile.ZipFile('output/Annotations.zip','w',zipfile.ZIP_DEFLATED)

      for xfile in os.listdir(uploads):
      if xfile.endswith('.jpg'):
      zfile.write('output/'+xfile)

      zfile.close()

      for files in os.listdir(uploads):
      if files.endswith('.zip')==False:
      os.remove(uploads+files)
      print(files + ' deleted.')

      return send_from_directory(uploads,'Annotations.zip',as_attachment=True)


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


      Prior to this, i tested the API with a normal form and it worked just fine. This issue happened after i implemented flask-dropzone. I also tried implementing flask-cors but the result is the same. I am currently at a dead end and any help is greatly appreciated.










      share|improve this question














      I have a Flask web app that uploads images to a machine learning model and returns predictions in a zip file. For the sake of simplicity, the code in this example simply uploads the images and returns them in a zip. I also implemented flask-dropzone in the html.



      This is the error code that i get when the send_from_directory line is executed



      "GET /horus/download HTTP/1.1" 0 


      interface.html



      <body>
      <h3>Welcome to Horus&trade; v1.0</h3>

      {{ dropzone.create(action=url_for('predict')) }}
      <button class="btn waves-effect waves-light btn-large" id="upload">Upload
      <i class="material-icons right">send</i>
      </button>

      {{ dropzone.load_js() }}
      {{ dropzone.config(custom_options='addRemoveLinks: true,dictRemoveFileConfirmation:"Are you sure you want to remove this file?" ') }}
      </body>
      </html>


      app.py



      import base64
      import zipfile
      import json
      import requests
      import os
      from flask import Flask, request,jsonify,render_template,url_for,redirect,send_from_directory,current_app,send_file,after_this_request
      from werkzeug import secure_filename
      from keras.preprocessing import image
      from lib.JsonToXML import convert

      from flask_dropzone import Dropzone
      from flask_cors import CORS, cross_origin



      app = Flask(__name__)
      CORS(app)
      app.config['CORS_HEADERS']='Content-Type'
      app.config.update(
      DROPZONE_ALLOWED_FILE_CUSTOM = True,
      DROPZONE_ALLOWED_FILE_TYPE = '.JPG,.JPEG,.jpg,.jpeg',
      DROPZONE_UPLOAD_ON_CLICK = True,
      DROPZONE_UPLOAD_MULTIPLE = True,
      DROPZONE_DEFAULT_MESSAGE = 'Drop files here to upload or click here to open File Explorer. Allowed file extensions: .jpg, .jpeg'
      )



      dropzone = Dropzone(app)

      @app.route('/horus/predict/v1', methods=['POST','GET'])

      def predict():

      if request.method == 'POST':


      for key,files in request.files.items():
      if key.startswith('file'):
      print(files)
      files.save('output/'+ secure_filename(files.filename))


      return redirect(url_for('download'))
      else:
      return render_template('interface.html')

      @app.route('/horus/download',methods=['GET'])
      @cross_origin(origin='*')
      def download():

      uploads = os.path.join(current_app.root_path,'output/')
      zfile = zipfile.ZipFile('output/Annotations.zip','w',zipfile.ZIP_DEFLATED)

      for xfile in os.listdir(uploads):
      if xfile.endswith('.jpg'):
      zfile.write('output/'+xfile)

      zfile.close()

      for files in os.listdir(uploads):
      if files.endswith('.zip')==False:
      os.remove(uploads+files)
      print(files + ' deleted.')

      return send_from_directory(uploads,'Annotations.zip',as_attachment=True)


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


      Prior to this, i tested the API with a normal form and it worked just fine. This issue happened after i implemented flask-dropzone. I also tried implementing flask-cors but the result is the same. I am currently at a dead end and any help is greatly appreciated.







      python http flask flask-cors






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 22 '18 at 7:23









      imran khanimran khan

      12




      12
























          0






          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53425754%2fflask-returns-http-code-0-when-sending-file%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53425754%2fflask-returns-http-code-0-when-sending-file%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

          Alcedinidae

          RAC Tourist Trophy