add list endpoint
This commit is contained in:
parent
a69875aa32
commit
54a2eee795
1 changed files with 32 additions and 6 deletions
38
app.py
38
app.py
|
@ -2,6 +2,7 @@ import os
|
|||
import re
|
||||
import uuid
|
||||
from flask import Flask, request, jsonify, send_from_directory
|
||||
import datetime
|
||||
|
||||
app = Flask(__name__)
|
||||
app.config['UPLOAD_FOLDER'] = os.environ.get('UPLOAD_FOLDER', '/home/mg/api/python-api-server/uploads')
|
||||
|
@ -9,7 +10,7 @@ app.config['MAX_CONTENT_LENGTH'] = int(os.environ.get('MAX_CONTENT_LENGTH', '5')
|
|||
|
||||
VALID_FILENAME_REGEX = r'^[a-zA-Z0-9\-_\.]+$'
|
||||
|
||||
AUTH_TOKEN = os.environ.get('AUTH_TOKEN', 'myauthtoken')
|
||||
AUTH_TOKEN = os.environ.get('AUTH_TOKEN', 'myuploadtoken')
|
||||
|
||||
def is_valid_filename(filename):
|
||||
return bool(re.match(VALID_FILENAME_REGEX, filename))
|
||||
|
@ -51,13 +52,36 @@ def delete_file(filename):
|
|||
if request.headers['token'] != AUTH_TOKEN:
|
||||
return jsonify({'error': 'Invalid token supplied'}), 401
|
||||
|
||||
path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
|
||||
try:
|
||||
os.remove(path)
|
||||
return jsonify({'success': 'File \'{}\' successfully deleted'.format(filename)})
|
||||
except FileNotFoundError:
|
||||
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
|
||||
if not os.path.isfile(file_path):
|
||||
return jsonify({'error': 'File not found'}), 404
|
||||
|
||||
os.remove(file_path)
|
||||
return jsonify({'success': 'File \'{}\' successfully deleted'.format(filename)})
|
||||
|
||||
@app.route('/list', methods=['GET'])
|
||||
def list_files():
|
||||
if 'token' not in request.headers:
|
||||
return jsonify({'error': 'No token supplied'}), 401
|
||||
|
||||
if request.headers['token'] != AUTH_TOKEN:
|
||||
return jsonify({'error': 'Invalid token supplied'}), 401
|
||||
|
||||
files = []
|
||||
for filename in os.listdir(app.config['UPLOAD_FOLDER']):
|
||||
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
|
||||
if os.path.isfile(file_path):
|
||||
stats = os.stat(file_path)
|
||||
size = stats.st_size
|
||||
last_modified = datetime.datetime.fromtimestamp(stats.st_mtime).strftime('%Y-%m-%d %H:%M:%S')
|
||||
files.append({
|
||||
'name': filename,
|
||||
'size': size,
|
||||
'last_modified': last_modified
|
||||
})
|
||||
|
||||
return jsonify({'files': files})
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(debug=True, host='0.0.0.0', port=int(os.environ.get('PORT', 5000)))
|
||||
|
||||
|
@ -66,6 +90,8 @@ if __name__ == '__main__':
|
|||
# touch ../hallowelt && curl -X POST -H "token: myuploadtoken" -F "file=@../hallowelt" http://docker10.grote.lan:5040/upload
|
||||
# Download
|
||||
# wget http://docker10.grote.lan:5040/download/hallowelt
|
||||
# delete
|
||||
# curl -X DELETE -H "token: myuploadtoken" http://docker10.grote.lan:5040/delete/hallowelt
|
||||
|
||||
|
||||
|
||||
|
|
Reference in a new issue