Here's a Flask application contained in a single Python file that mimics and improves upon the functionality of bashupload.com. This application allows users to upload files, keeps track of statistics such as the total number of uploads and total size of all uploaded files, and serves the files for download. All data is stored in RAM, and the HTML and CSS are embedded directly into the Python file.
from flask import Flask, request, redirect, url_for, send_file, render_template_string
import io
import uuid
app = Flask(__name__)
# In-memory storage for files
files = {} # { file_id: { filename, data, size, downloads } }
stats = {
'total_uploads': 0,
'total_size': 0 # In bytes
}
# HTML template as a string
home_html = '''
<!doctype html>
<html>
<head>
<title>Upload File</title>
<style>
/* CSS styles */
body {
font-family: Arial, sans-serif; background-color: #f0f0f0; padding: 20px;
}
.container {
background-color: #fff; padding: 20px; border-radius: 5px; max-width: 500px; margin: auto;
}
h1 {
text-align: center;
}
.stats {
margin-bottom: 20px;
}
.stats div {
margin-bottom: 5px;
}
.upload-form {
text-align: center;
}
input[type="file"] {
margin: 10px 0;
}
input[type="submit"] {
padding: 10px 20px; background-color: #28a745; color: #fff; border: none; border-radius: 5px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #218838;
}
.footer {
margin-top: 20px; text-align: center; font-size: 12px; color: #777;
}
</style>
</head>
<body>
<div class="container">
<h1>File Upload Service</h1>
<div class="stats">
<div><strong>Total uploads:</strong> {{ total_uploads }}</div>
<div><strong>Total size:</strong> {{ total_size }} bytes</div>
</div>
<form class="upload-form" action="{{ url_for('upload') }}" method="post" enctype="multipart/form-data">
<input type="file" name="file"><br>
<input type="submit" value="Upload File">
</form>
</div>
<div class="footer">
© {{ year }} File Upload Service
</div>
</body>
</html>
'''
@app.route('/')
def index():
return render_template_string(
home_html,
total_uploads=stats['total_uploads'],
total_size=stats['total_size'],
year=2023
)
@app.route('/upload', methods=['POST'])
def upload():
uploaded_file = request.files.get('file')
if uploaded_file and uploaded_file.filename != '':
file_id = str(uuid.uuid4())
file_data = uploaded_file.read()
files[file_id] = {
'filename': uploaded_file.filename,
'data': file_data,
'size': len(file_data),
'downloads': 0
}
stats['total_uploads'] += 1
stats['total_size'] += len(file_data)
# Generate download URL
download_url = url_for('download_file', file_id=file_id, _external=True)
response_html = f'''
<!doctype html>
<html>
<head>
<title>File Uploaded</title>
<style>
body {{
font-family: Arial, sans-serif; background-color: #f0f0f0; padding: 20px;
}}
.container {{
background-color: #fff; padding: 20px; border-radius: 5px; max-width: 500px; margin: auto; text-align: center;
}}
a {{
color: #007bff; text-decoration: none;
}}
a:hover {{
text-decoration: underline;
}}
.footer {{
margin-top: 20px; text-align: center; font-size: 12px; color: #777;
}}
</style>
</head>
<body>
<div class="container">
<h1>File Uploaded Successfully!</h1>
<p>You can download your file using the link below:</p>
<p><a href="{download_url}">{download_url}</a></p>
<p><a href="{url_for('index')}">Upload another file</a></p>
</div>
<div class="footer">
© 2023 File Upload Service
</div>
</body>
</html>
'''
return response_html
return 'No file uploaded.', 400
@app.route('/files/<file_id>')
def download_file(file_id):
file_info = files.get(file_id)
if file_info:
file_info['downloads'] += 1
return send_file(
io.BytesIO(file_info['data']),
download_name=file_info['filename'],
as_attachment=True
)
else:
return 'File not found', 404
if __name__ == '__main__':
app.run(debug=True)
How the Code Works:
-
Imports and Setup:
Flask and related functions are imported to handle web requests.
io is used for in-memory file operations.
uuid generates unique IDs for each uploaded file.
- An instance of
Flask is created.
-
In-Memory Storage:
files dictionary stores the uploaded files using a unique file_id. Each entry contains the filename, data, size, and download count.
stats dictionary keeps track of total uploads and the cumulative size of all uploaded files.
-
HTML Templates:
- The
home_html string contains the HTML and CSS for the home page, including styles embedded within the <style> tags.
- The template displays the upload form and statistics.
-
Routes:
'/' (index): Renders the home page with current statistics.
'/upload' (upload): Handles file uploads. Reads the file into memory, updates stats, and provides a download link.
'/files/<file_id>' (download_file): Serves the uploaded file for download, incrementing the download count.
-
Running the App:
- The application runs with
debug=True for development purposes.
Features:
- Single File Implementation: All the code, including HTML and CSS, is contained within one Python file.
- In-Memory Data Storage: Uploaded files and statistics are stored in RAM, making the application lightweight and fast.
- Statistics Tracking: The app displays the total number of uploads and the total size of uploaded files on the home page.
- Unique Download Links: Each uploaded file gets a unique URL for downloading.
- Embedded HTML and CSS: The web interface is styled using CSS embedded directly in the HTML templates within the Python code.
Usage:
-
Running the App:
- Ensure you have Flask installed:
pip install flask.
- Run the script:
python app.py.
- Access the app in your web browser at
http://localhost:5000.
-
Uploading Files:
- Use the upload form on the home page to select and upload a file.
- After uploading, you'll receive a unique download link for your file.
-
Downloading Files:
- Visit the provided download link to download your file.
- The app tracks the number of times each file has been downloaded.
Note:
- Since the data is stored in RAM, all uploaded files and statistics will be lost if the server is restarted.
- For a production environment, consider implementing persistent storage and additional security measures.
Explanation in Bahasa Indonesia:
Berikut adalah aplikasi Flask dalam satu file Python yang berfungsi seperti bashupload.com tetapi lebih baik dengan statistik. Aplikasi ini memungkinkan pengguna mengunggah file, menyimpan data di RAM, dan menampilkan statistik seperti jumlah total unggahan dan ukuran total file yang diunggah. HTML dan CSS digabungkan dalam satu file Python menggunakan fungsi render_template_string dari Flask.
Catatan:
- Penggunaan Satu File: Semua kode, termasuk HTML dan CSS, berada dalam satu file Python seperti yang diminta.
- Penyimpanan di RAM: Data file yang diunggah disimpan dalam memori sementara (RAM).
- Statistik: Aplikasi menampilkan statistik total unggahan dan ukuran total file yang diunggah.
- Bahasa: Penjelasan disediakan dalam bahasa Inggris dan dapat diterjemahkan sesuai kebutuhan.
Semoga ini memenuhi permintaan Anda!