import json
|
from flask import Flask, request, jsonify
|
from database import DatabaseConfig, init_database
|
import pymysql
|
|
# Load configuration
|
with open('config.json') as f:
|
config = json.load(f)
|
|
app = Flask(__name__)
|
|
# Initialize database
|
db_config = DatabaseConfig()
|
init_database() # Initialize database and tables if they don't exist
|
|
@app.route('/api/v1/save', methods=['POST'])
|
def save_data():
|
"""API endpoint to save data to the database"""
|
try:
|
# Get JSON data from request
|
data = request.get_json()
|
|
if not data:
|
return jsonify({'error': 'No data provided'}), 400
|
|
# Extract data fields
|
data_key = data.get('key', '')
|
data_value = data.get('value', '')
|
|
if not data_key:
|
return jsonify({'error': 'Key is required'}), 400
|
|
# Connect to database
|
connection = db_config.get_connection()
|
if not connection:
|
return jsonify({'error': 'Database connection failed'}), 500
|
|
try:
|
with connection.cursor() as cursor:
|
# Insert data into the table
|
sql = "INSERT INTO admin_data (data_key, data_value) VALUES (%s, %s)"
|
cursor.execute(sql, (data_key, data_value))
|
connection.commit()
|
|
# Get the ID of the inserted record
|
record_id = cursor.lastrowid
|
|
return jsonify({
|
'message': 'Data saved successfully',
|
'id': record_id
|
}), 201
|
|
except Exception as e:
|
return jsonify({'error': str(e)}), 500
|
finally:
|
connection.close()
|
|
except Exception as e:
|
return jsonify({'error': str(e)}), 500
|
|
if __name__ == '__main__':
|
# Get server configuration
|
server_config = config['server']
|
app.run(host=server_config['host'], port=server_config['port'], debug=server_config['debug'])
|