Skip to content

Instantly share code, notes, and snippets.

@armsp
Last active June 11, 2020 08:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save armsp/8b2bc13602b340d7792166b11998c8c9 to your computer and use it in GitHub Desktop.
Save armsp/8b2bc13602b340d7792166b11998c8c9 to your computer and use it in GitHub Desktop.
Upload files to flask restful server in two different ways. First is a proper upload and the other copies file from a given location to server's location by only providing the file path of file to copy in the URL itself.
import os
from flask import Flask, Response, request, jsonify, redirect, send_from_directory
from flask_restful import Api, Resource
from werkzeug.utils import secure_filename
class file_operation:
def __init__(self):
self.APP_ROOT = os.path.dirname(os.path.abspath(__file__))
self.UPLOAD_FOLDER = os.path.join(self.APP_ROOT, 'upload_folder_logreg')
self.ALLOWED_EXTENSIONS = set(['txt', 'csv'])
print(self.APP_ROOT)
print(self.UPLOAD_FOLDER)
os.makedirs(self.UPLOAD_FOLDER, exist_ok=True)
self.app = Flask(__name__)
self.api = Api(self.app)
self.app.config['UPLOAD_FOLDER'] = self.UPLOAD_FOLDER
self.server_file = None
#app.config['JSON_AS_ASCII'] = False
@self.app.route('/fileup', methods = ['GET', 'POST'])
def upload_file():
def allowed_file(filename):
#print('.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS)
return '.' in filename and filename.rsplit('.', 1)[1] in self.ALLOWED_EXTENSIONS
print("Method = ", request.method)
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
print("Post request doesn't have file. Reupload.")
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also
# submit a empty part without filename
if file.filename == '':
print('Empty Post request. Please upload with valid file.')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(self.app.config['UPLOAD_FOLDER'], filename))
print(filename)
server_file = os.path.join(self.UPLOAD_FOLDER, filename)
print(server_file)
self.server_file = server_file
return jsonify("Successfully Uploaded File")
return_html = '''<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>'''
return Response(return_html,mimetype='text/html')
@self.app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(self.app.config['UPLOAD_FOLDER'], filename)
if __name__ == '__main__':
self.app.run(host='0.0.0.0', port=5000, debug=True)
'''Upload file to a Flask Restful server'''
import os
from flask import Flask, Response, request, jsonify, redirect, send_from_directory
from flask_restful import Api, Resource
from werkzeug.utils import secure_filename
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLDER = os.path.join(APP_ROOT, 'upload_folder_logreg')
ALLOWED_EXTENSIONS = set(['txt', 'csv'])
print(APP_ROOT)
print(UPLOAD_FOLDER)
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app = Flask(__name__)
api = Api(app)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
#app.config['JSON_AS_ASCII'] = False
def allowed_file(filename):
#print('.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS)
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
class upload_file(Resource):
def get(self):
ret_htm = '''<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>'''
return Response(ret_htm,mimetype='text/html')
def post(self):
print("Method = ", request.method)
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
print("Post request doesn't have file. Reupload.")
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also
# submit a empty part without filename
if file.filename == '':
print('Empty Post request. Please upload with valid file.')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
print(filename)
server_file = os.path.join(UPLOAD_FOLDER, filename)
print(server_file)
return jsonify("Successfully Uploaded File")
class uploaded_file(Resource):
def get(self,filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
api.add_resource(upload_file, '/fileup')
api.add_resource(uploaded_file, '/uploads/<filename>')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
'''Upload file to server by passing only file path in Flask-RESTful.
It basically copies the file in the path to a folder created inside the folder where the script resides.'''
from flask import Flask, request, jsonify
from flask_restful import Api, Resource
import shutil
import os
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLDER = os.path.join(APP_ROOT, 'uploaded_file')
print(APP_ROOT)
print(UPLOAD_FOLDER)
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
api = Api(app)
class FileUpload(Resource):
def post(self, fname):
print("Copying file")
os.makedirs(UPLOAD_FOLDER,exist_ok=True)
shutil.copy2(fname,UPLOAD_FOLDER)
with open(fname, 'r') as f:
file_content = f.read()
return jsonify(file_content)
api.add_resource(FileUpload, '/fileup/<path:fname>')
if __name__ == '__main__':
app.run(debug=True)
'''Upload file to a Flask Restful server'''
from flask import Flask, request, jsonify, redirect, url_for, send_from_directory
from flask_restful import Api, Resource
import os
from werkzeug.utils import secure_filename
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLDER = os.path.join(APP_ROOT, 'upload_file')
ALLOWED_EXTENSIONS = set(['txt', 'csv'])
print(APP_ROOT)
print(UPLOAD_FOLDER)
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app = Flask(__name__)
api = Api(app)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
#app.config['JSON_AS_ASCII'] = False
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
@app.route('/fileup', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
print('Please upload valid file')
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also
# submit a empty part without filename
if file.filename == '':
print('Please upload valid file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
print(filename)
server_file = os.path.join(UPLOAD_FOLDER, filename)
print(server_file)
return jsonify("Successfully Uploaded File")
return '''
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
'''
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment