-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
executable file
·161 lines (117 loc) · 5.14 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
#!flask/bin/python
# Author: Burak Ayvalli
# Email: ayvalli@itu.edu.tr
#############
# References
#############
# Boto3
# Git repository: https://github.com/ngoduykhanh/flask-file-uploader
# This work based on jQuery-File-Upload which can be found at https://github.com/blueimp/jQuery-File-Upload/
import os
import PIL
from PIL import Image
import simplejson
import traceback
from flask import Flask, request, render_template, redirect, url_for, send_from_directory
from flask_bootstrap import Bootstrap
from werkzeug.utils import secure_filename
from config import Config
from lib.s3controller import uploadfile, deletefile, md5
from lib.dynamoDBcontroller import dynamodbctrl
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(Config)
ALLOWED_EXTENSIONS = app.config['ALLOWED_EXTENSIONS']
IGNORED_FILES = app.config['IGNORED_FILES']
DYNAMODB_TABLENAME = app.config['DYNAMODB_TABLENAME']
bootstrap = Bootstrap(app)
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def gen_file_name(filename):
"""
If file was exist already, rename it and return a new name
"""
i = 1
while os.path.exists(os.path.join(app.config['UPLOAD_FOLDER'], filename)):
name, extension = os.path.splitext(filename)
filename = '%s_%s%s' % (name, str(i), extension)
i += 1
return filename
def create_thumbnail(image):
try:
base_width = 80
img = Image.open(os.path.join(app.config['UPLOAD_FOLDER'], image))
w_percent = (base_width / float(img.size[0]))
h_size = int((float(img.size[1]) * float(w_percent)))
img = img.resize((base_width, h_size), PIL.Image.ANTIALIAS)
img.save(os.path.join(app.config['THUMBNAIL_FOLDER'], image))
return True
except:
print(traceback.format_exc())
return False
@app.route("/upload", methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
files = request.files['file']
tablename = request.form.get('dynamo')
DYNAMODB_TABLENAME = "metadata" if (tablename == "" or tablename == "metadata") else tablename
if files:
filename = secure_filename(files.filename)
filename = gen_file_name(filename)
mime_type = files.content_type
if not allowed_file(files.filename):
result = uploadfile(name=filename, type=mime_type, size=0, not_allowed_msg="File type not allowed", dbtablename=DYNAMODB_TABLENAME)
else:
# save file to disk
uploaded_file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
files.save(uploaded_file_path)
# create thumbnail after saving
if mime_type.startswith('image'):
create_thumbnail(filename)
# get file size after saving
size = os.path.getsize(uploaded_file_path)
# return json for js call back
result = uploadfile(name=filename, type=mime_type, size=size, dbtablename=DYNAMODB_TABLENAME)
return simplejson.dumps({"files": [result.get_file()]})
if request.method == 'GET':
# get all file in ./data directory
files = [f for f in os.listdir(app.config['UPLOAD_FOLDER']) if os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'],f)) and f not in IGNORED_FILES ]
file_display = []
for f in files:
size = os.path.getsize(os.path.join(app.config['UPLOAD_FOLDER'], f))
file_saved = uploadfile(name=f, size=size)
file_display.append(file_saved.get_file())
return simplejson.dumps({"files": file_display})
return redirect(url_for('index'))
@app.route("/delete/<string:filename>", methods=['DELETE'])
def delete(filename):
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file_thumb_path = os.path.join(app.config['THUMBNAIL_FOLDER'], filename)
if os.path.exists(file_path):
try:
filehash = md5(file_path)
os.remove(file_path)
obj = deletefile(filename)
obj.deleteUploaded()
item = {'name': filename, 'md5': filehash}
dbitem = dynamodbctrl(item, DYNAMODB_TABLENAME)
dbitem.delete_item()
if os.path.exists(file_thumb_path):
os.remove(file_thumb_path)
obj = deletefile("thumbnail/{}".format(filename))
obj.deleteUploaded()
return simplejson.dumps({filename: 'True'})
except:
return simplejson.dumps({filename: 'False'})
# serve static files
@app.route("/thumbnail/<string:filename>", methods=['GET'])
def get_thumbnail(filename):
return send_from_directory(app.config['THUMBNAIL_FOLDER'], filename=filename)
@app.route("/data/<string:filename>", methods=['GET'])
def get_file(filename):
return send_from_directory(os.path.join(app.config['UPLOAD_FOLDER']), filename=filename)
@app.route('/', methods=['GET', 'POST'])
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)