简体   繁体   中英

File upload using Flask

I am trying to implement a python API in order to upload a file on my server but for an unknown reason, it doesn't run.

From my understanding, the app.py is not recognised

Here is my API.py

from flask_cors import CORS
from flask_restful import Api, Resource, reqparse
import sqlite3
import uuid
import os
import csv
import urllib.request
import threading
import queue as Queue
import subprocess
import json
import re
import datetime

app = Flask(__name__)
api = Api(app)
CORS(app)

class upload(Resource):
    def post(self):
    ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

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

    def upload_file():
        # check if the post request has the file part
        if 'file' not in request.files:
            resp = jsonify({'message' : 'No file part in the request'})
            resp.status_code = 400
            return resp
        file = request.files['file']
            int = str(request.form['int']) #true or false

        if file.filename == '':
            resp = jsonify({'message' : 'No file selected for uploading'})
            resp.status_code = 400
            return resp
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))  

                return json.dumps(data),   200
        else:
            resp = jsonify({'message' : 'Allowed file types are doc, etc.'})
            resp.status_code = 400
            return resp


api.add_resource(upload, "/api/v1/upload")
app.run(host='0.0.0.0', debug=True)

Here is my app.py

UPLOAD_FOLDER = '/home/xxxx/xxx/upload'
app = Flask(__name__)
#app.secret_key = "secret key"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

Can you please help? Any suggestions?

As per the comment, it looks like you have two sepearate applications here.

I would just stick with the first one API.py , but you'll need to move the lines where you set the config variables into API.py :

So after this line in API.py :

app = Flask(__name__)

Immediately set the config values:

UPLOAD_FOLDER = '/home/xxxx/xxx/upload'
#app.secret_key = "something super secret"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

Then execute with:

python API.py

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM