Wrote basic upload folder
commit
70c480a7cd
|
@ -0,0 +1 @@
|
|||
__pycache__/
|
|
@ -0,0 +1,68 @@
|
|||
import os
|
||||
from flask import Flask, request
|
||||
from pathlib import Path
|
||||
from werkzeug.utils import secure_filename
|
||||
import subprocess
|
||||
|
||||
UPLOAD_FOLDER = './data'
|
||||
API_KEY = 'yeet'
|
||||
ALLOWED_EXTENSIONS = {'pkg.tar.zst', 'pkg.tar.gz'}
|
||||
|
||||
app = Flask(__name__)
|
||||
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
|
||||
|
||||
|
||||
def require_api_key(func):
|
||||
def inner(*args, **kwargs):
|
||||
print(request.headers)
|
||||
if request.headers.get('x-api-key') and request.headers.get('x-api-key') == API_KEY:
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return {'message': 'Unauthorized.'}, 401
|
||||
|
||||
return inner
|
||||
|
||||
|
||||
def allowed_file(filename):
|
||||
return any(filename.endswith(ext) for ext in ALLOWED_EXTENSIONS)
|
||||
|
||||
|
||||
@app.route('/publish', methods=['POST'])
|
||||
@require_api_key
|
||||
def upload_file():
|
||||
# check if the post request has the file part
|
||||
if 'file' not in request.files or not request.files['file']:
|
||||
return {'message': 'No file.'}, 400
|
||||
|
||||
file = request.files['file']
|
||||
|
||||
# Check wether a filename was provided
|
||||
if file.filename == '':
|
||||
return {'message': 'No filename.'}, 400
|
||||
|
||||
# Check wether the filename has an allowed file extension
|
||||
if not allowed_file(file.filename):
|
||||
return {'message': 'Invalid extension.'}, 400
|
||||
|
||||
# Create path for file & check if it already exists
|
||||
filename = secure_filename(file.filename)
|
||||
path = Path(app.config['UPLOAD_FOLDER']) / 'pkgs' / filename
|
||||
|
||||
if path.exists():
|
||||
return {'message': 'File already exists.'}, 400
|
||||
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Store the file
|
||||
file.save(path)
|
||||
|
||||
# Run repo-add on the file
|
||||
res = subprocess.run(["repo-add", path.parent.parent / "repo.db.tar.gz", path])
|
||||
|
||||
if res.returncode != 0:
|
||||
path.unlink()
|
||||
|
||||
return {'message': 'Failed to add file to repository.'}, 500
|
||||
|
||||
return {'message': 'Success.'}, 200
|
||||
|
Reference in New Issue