Tools Import / Export

main
Bryan Cerrati 2025-03-07 08:51:10 -05:00
parent 578d053386
commit 0be541be85
2 changed files with 77 additions and 0 deletions

56
app/routes/tools.py Normal file
View File

@ -0,0 +1,56 @@
import json
from flask import Blueprint, render_template, request, redirect, url_for, flash, Response
from app.models import Domain
from app import db
tools_bp = Blueprint('tools', __name__)
@tools_bp.route('/tools', methods=['GET'])
def tools():
return render_template('tools.html')
@tools_bp.route('/tools/export', methods=['GET'])
def export_data():
# Query all domain data from the database.
domains = Domain.query.all()
data = []
for d in domains:
data.append({
'id': d.id,
'domain': d.domain,
'expiration_date': d.expiration_date,
'ssl_expiration_date': d.ssl_expiration_date,
'ssl_only': d.ssl_only
})
json_data = json.dumps(data)
# Create a response that prompts the user to download the JSON file.
response = Response(json_data, mimetype='application/json')
response.headers['Content-Disposition'] = 'attachment; filename=domains_data.json'
return response
@tools_bp.route('/tools/import', methods=['GET', 'POST'])
def import_data():
if request.method == 'POST':
file = request.files.get('file')
if file:
try:
data = json.load(file)
# Insert each record if the domain doesn't already exist.
for record in data:
existing = Domain.query.filter_by(domain=record.get('domain')).first()
if not existing:
new_domain = Domain(
domain=record.get('domain'),
expiration_date=record.get('expiration_date'),
ssl_expiration_date=record.get('ssl_expiration_date'),
ssl_only=record.get('ssl_only', False)
)
db.session.add(new_domain)
db.session.commit()
flash("Data imported successfully", "success")
except Exception as e:
flash(f"Error importing data: {str(e)}", "danger")
else:
flash("No file uploaded", "warning")
return redirect(url_for('tools.tools'))
return render_template('tools.html')

21
app/templates/tools.html Normal file
View File

@ -0,0 +1,21 @@
{% extends "base.html" %}
{% block title %}Tools{% endblock %}
{% block content %}
<h1>Tools</h1>
<div>
<h2>Import / Export Data</h2>
<div>
<form action="{{ url_for('tools.import_data') }}" method="post" enctype="multipart/form-data">
<label for="file">Import Data:</label>
<input type="file" name="file" id="file">
<button type="submit">Import</button>
</form>
</div>
<div style="margin-top:20px;">
<a href="{{ url_for('tools.export_data') }}">
<button type="button">Export Data</button>
</a>
</div>
</div>
{% endblock %}