Created
September 12, 2019 09:08
-
-
Save gtindo/1ffac2d3a6a1d39068fd51d5a63c62eb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Blueprint, request | |
from werkzeug.utils import secure_filename | |
from pandas import pandas as pd | |
from flask_cors import cross_origin | |
import os | |
import uuid | |
from .. import config | |
bp = Blueprint("process", __name__, url_prefix='/process') | |
def get_extension(filename): | |
try: | |
return filename.rsplit('.', 1)[1].lower() | |
except IndexError: | |
return None | |
def allowed_file(extension): | |
return extension in config.ALLOWED_EXTENSIONS | |
def convert_to_xls(data): | |
filename = str(uuid.uuid4())+".xlsx" | |
filepath = os.path.join(config.MEDIA_DIR, filename) | |
data.to_excel(filepath, index=None, header=True) | |
return filename | |
def convert_to_csv(data): | |
filename = str(uuid.uuid4())+".csv" | |
filepath = os.path.join(config.MEDIA_DIR, filename) | |
data.to_csv(filepath, index=None, header=True) | |
return filename | |
@bp.route('/upload/', methods=('POST', )) | |
@cross_origin() | |
def process_file(): | |
f = request.files['file'] | |
extension = get_extension(f.filename) | |
if allowed_file(extension): | |
filename = None | |
if extension == 'csv': | |
data = pd.read_csv(f) | |
filename = convert_to_xls(data) | |
else: | |
data = pd.read_excel(f) | |
filename = convert_to_csv(data) | |
return { | |
"url": "http://localhost:5000/medias/"+filename, | |
"success": True | |
} | |
else: | |
return { | |
"success": False, | |
"Error": "Bad file" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment