|
5 | 5 | What is this code: An example Flask connection
|
6 | 6 | Why?: For me to remember later
|
7 | 7 | """
|
| 8 | +import os |
| 9 | +from flask import jsonify |
| 10 | +from http import HTTPStatus |
8 | 11 |
|
| 12 | +from flask import Flask, request |
| 13 | +from werkzeug.utils import secure_filename |
| 14 | + |
| 15 | +app = Flask(__name__) |
| 16 | + |
| 17 | +ALLOWED_EXTENSIONS = ['zip', 'gz', 'bz2'] |
| 18 | + |
| 19 | +def allowed_filename(filename: str) -> bool: |
| 20 | + return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS |
| 21 | + |
| 22 | +@app.route('/upload', methods=['POST']) |
| 23 | +def upload_csv() -> str: |
| 24 | + submitted_file = request.files['file'] |
| 25 | + if submitted_file and allowed_filename(submitted_file.filename): |
| 26 | + filename = secure_filename(submitted_file.filename) |
| 27 | + directory = os.path.join(app.config['UPLOAD_FOLDER']) |
| 28 | + if not os.path.exists(directory): |
| 29 | + os.mkdir(directory) |
| 30 | + basedir = os.path.abspath(os.path.dirname(__file__)) |
| 31 | + submitted_file.save(os.path.join(basedir,app.config['UPLOAD_FOLDER'], filename)) |
| 32 | + out = { |
| 33 | + 'status': HTTPStatus.OK, |
| 34 | + 'filename': filename, |
| 35 | + 'message': f"{filename} saved successful." |
| 36 | + } |
| 37 | + return jsonify(out) |
| 38 | + |
| 39 | +if __name__=="__main__": |
| 40 | + app.config['UPLOAD_FOLDER'] = "flaskme/" |
| 41 | + app.run(port=6969, debug=True) |
| 42 | + |
| 43 | +# run curl http://localhost:6969 |
| 44 | +# run curl -X POST -F file=@"/path/to/my/file/test.txt" http://localhost:6969/print_filename |
9 | 45 |
|
0 commit comments