File size: 2,131 Bytes
0491fc6 33f8f7c 0491fc6 059bbb9 07d1566 0491fc6 059bbb9 33f8f7c 07d1566 0491fc6 33f8f7c 0491fc6 07d1566 0491fc6 059bbb9 0491fc6 |
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 |
from flask import Flask, request, jsonify, Response
import random
import string
from collections import deque
import threading
app = Flask(__name__)
transfers = {}
transfer_data = {}
transfer_lock = threading.Lock()
def generate_short_id(length=8):
while True:
token = ''.join(random.choices(string.ascii_letters + string.digits, k=length))
if token not in transfers:
return token
@app.route('/create_transfer', methods=['POST'])
def create_transfer():
filename = request.json.get('filename')
filesize = request.json.get('filesize', 0)
transfer_id = generate_short_id(8)
with transfer_lock:
transfers[transfer_id] = {
'filename': filename,
'filesize': filesize,
'completed': False
}
transfer_data[transfer_id] = deque(maxlen=100) # Ограничение буфера
return jsonify({'transfer_id': transfer_id})
@app.route('/upload/<transfer_id>', methods=['POST'])
def upload_file(transfer_id):
if transfer_id not in transfers:
return jsonify({'error': 'Invalid transfer ID'}), 404
data = request.data
with transfer_lock:
transfer_data[transfer_id].extend(data)
transfers[transfer_id]['completed'] = request.headers.get('X-Transfer-Complete') == 'true'
return jsonify({'status': 'chunk uploaded'})
@app.route('/download/<transfer_id>', methods=['GET'])
def download_file(transfer_id):
if transfer_id not in transfers:
return jsonify({'error': 'Invalid transfer ID'}), 404
def generate():
while True:
with transfer_lock:
if transfer_data[transfer_id]:
chunk = bytes(transfer_data[transfer_id].popleft())
yield chunk
elif transfers[transfer_id]['completed']:
break
return Response(
generate(),
mimetype='application/octet-stream',
headers={'Content-Disposition': f'attachment; filename="{transfers[transfer_id]["filename"]}"'}
)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860) |