yj
2026-03-31 4becf7b5eba5de2d9889f379eb88aeb6cb16f760
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
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'])