Προς το περιεχόμενο

Βοήθεια με πρόβλημα σε json get_request


oraiustepe

Προτεινόμενες αναρτήσεις

καλημέρα, 

import pandas as pd #used for data manipulation and analysis
from flask import Flask, render_template, request, jsonify #Flask is a web framework for building web applications. render_template, request, and jsonify are specific components of Flask for rendering templates, handling HTTP requests, and formatting JSON responses, respectively. 
from flask_cors import CORS  # CORS is used for enabling Cross-Origin Resource Sharing, allowing the server to handle requests from different origins
#from anonymization import AnonymizationHandler
from anonymization import get_anonymization_techniques, anonymize_all_columns
import numpy as np
import json

# a Flask application is created, and CORS is enabled for all routes.
# This is necessary if you want to make requests to this server from a different domain.
app = Flask(__name__)
CORS(app)  # Enable CORS for all routes

# global variable df is initialized as an empty pandas DataFrame. This variable will be used to store the loaded data.
df = pd.DataFrame()
csv_loaded = False
selected_columns = []
sensitive_columns_energy = ["name", "age"]
sensitive_columns_telecommunication = []
sensitive_columns_agriculture = []
sensitive_columns_meteo = []
sensitive_columns = sensitive_columns_energy + sensitive_columns_telecommunication + sensitive_columns_agriculture + sensitive_columns_meteo

# This route ('/') is the default route that renders the 'index.html' template when someone accesses the root URL of the application.
@app.route('/')
def index():
    return render_template('index.html')

# This route ('/load_data') is configured to handle POST requests. It expects a file to be sent in the request, 
# reads the CSV file using pandas, and filters the DataFrame to include only sensitive columns. 
# It then returns a JSON response indicating the status of the operation.
@app.route('/load_data', methods=['POST'])
def load_data():
    global df,csv_loaded
    try:
        # Assuming the file is sent as form data in a POST request
        file = request.files['file']
        df = pd.read_csv(file)
        csv_loaded = True
        #df_filtered = df[sensitive_columns]

        return jsonify({'status': 'success', 'message': 'Data loaded successfully'})
    except pd.errors.EmptyDataError:
        return jsonify({'status': 'error', 'message': 'Error: The CSV file is empty.'})
    except pd.errors.ParserError:
        return jsonify({'status': 'error', 'message': 'Error: Unable to parse the CSV file. Please check the file format, delimiter, or encoding.'})
    except Exception as e:
        return jsonify({'status': 'error', 'message': f'Error: {str(e)}'})

#@app.route('/anonymize', methods=['GET'])
#def show_anonymization_options():
 #   anonymization_handler.show_anonymization_options()




class NpEncoder(json.JSONEncoder):
    def default(self, obj):
        dtypes = (np.datetime64, np.complexfloating)
        if isinstance(obj, dtypes):
            return str(obj)
        elif isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            if any([np.issubdtype(obj.dtype, i) for i in dtypes]):
                return obj.astype(str).tolist()
            return obj.tolist()
        return super(NpEncoder, self).default(obj)

# This route ('/get_sensitive_columns') is configured to handle GET requests. 
# It iterates through each sensitive column specified in sensitive_columns. 
# For each column, it checks if the column exists in the loaded DataFrame (df). 
# If the column exists, it retrieves the first 6 rows of data, along with metadata such as data type, unique values, and missing values. 
# This information is then organized into a dictionary called sensitive_data.
@app.route('/get_sensitive_columns', methods=['GET'])
def get_sensitive_columns():
    global csv_loaded
    try:
        if not csv_loaded:
            return jsonify({'status': 'error', 'message': 'Error: No data loaded. Please load a CSV file first.'})
        # Return the first 6 rows of every sensitive column
        sensitive_data = {}

        
        for column in sensitive_columns:
            if column in df.columns:
                column_data = pd.to_numeric(df[column].head(6), errors='coerce').tolist()
                
                #column_data = df[column].head(6).tolist()
                sensitive_data[column] = {
                    'data': column_data,
                    'dtype': str(df[column].dtype),
                    'unique_values': df[column].nunique(),
                    'missing_values': df[column].isnull().sum()
                    # Add more information as needed
                }

        return json.dumps({'status': 'success', 'sensitive_data': sensitive_data}, cls=NpEncoder)
    except Exception as e:
        return jsonify({'status': 'error', 'message': f'Error in get_sensitive_columns: {str(e)}'})

και έχω και αυτόν τον html κώδικα. 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flask Anonymization App</title>
</head>
<body>
    <h1>Flask Anonymization App</h1>

    <!-- Button to load data -->
    <form action="/load_data" method="post" enctype="multipart/form-data">
        <label for="file">Choose a CSV file:</label>
        <input type="file" name="file" accept=".csv" required>
        <button type="submit">Load Data</button>
    </form>

    <hr>

    <!-- Button to get sensitive columns -->
    <button onclick="getSensitiveColumns()">Get Sensitive Columns</button>

    <!-- Display sensitive column information here -->
    <div id="sensitiveColumnsInfo"></div>

    <hr>



    <script>
        // JavaScript functions for making AJAX requests

        function getSensitiveColumns() {
            fetch('/get_sensitive_columns')
                .then(response => response.json())
                .then(data => {
                    const sensitiveColumnsInfo = document.getElementById('sensitiveColumnsInfo');
                    sensitiveColumnsInfo.innerHTML = JSON.stringify(data, null, 2);
                })
                .catch(error => console.error('Error:', error));
        }

     


    </script>
</body>
</html>

Το conccept ειναι ότι ο χρήστης κάνει εισαγωγή ένα csv, εγω σύμφωνα με τα sensitive columns που έχω θέσει, αν υπάρχει στήλη στο csv του και στα sensitive columns του επιστρέφω τη στήλη. π.χ αν το csv περιέχει τις στήλες name, age, postal code και εγώ έχω μονο το name σαν sensitive column στον κώδικα, θα του επιστραφεί μόνο η στήλη name και οι 6 πρώτες εγγραφές της στήλης, πατώντας στο get sensitive columns. Ωστόσο όταν πατάω από το index. html που έχω φτιάξει στο button get sensitive columns δε βγάζει κάποιο μήνυμα και απλά βγάζει στο console (στον chrome) αυτό "SyntaxError: Unexpected token 'N' ". Πριν από αυτό το error έβγαζε αυτό { "message": "Error in get sensitive columns: Object of type int64 is not JSON serializable", "status": "error" }  Δοκίμασα μια λύση γράφοντας την class NpEncoder ύστερα απο έρευνα στο νετ και τώρα έχουμε το unexpected token. Επισυνάπτω και το αρχείο csv γιατί κάτι με nan values ισως έχει γίνει και δεν το παρατηρώ. Υπάρχει κάποια λύση στο συγκεκριμενο θέμα;

Ευχαριστώ

Υπολογιστικό φύλλο χωρίς τίτλο - Φύλλο1 (3).csv

Συνδέστε για να σχολιάσετε
Κοινοποίηση σε άλλες σελίδες

Δημοσ. (επεξεργασμένο)

Δοκίμασες και τις άλλες λύσεις απο εκεί που πήρες την κλάση ?

https://stackoverflow.com/questions/50916422/python-typeerror-object-of-type-int64-is-not-json-serializable

και φυσικα μπορείς να δεις τι κάνει το jsonify 

https://github.com/pallets/flask/blob/main/src/flask/json/__init__.py

και να ελέγξεις που είναι το πρόβλημα

 

Επεξ/σία από masteripper
Συνδέστε για να σχολιάσετε
Κοινοποίηση σε άλλες σελίδες

Λογικά το θέμα ήταν εδώ. 

column_data = pd.to_numeric(df[column].head(6), errors='coerce').tolist()

 

Το άλλαξα λίγο και έφτιαξε. Το έκανα έτσι 

column_data = df[column].head(6).tolist()

 

Συνδέστε για να σχολιάσετε
Κοινοποίηση σε άλλες σελίδες

Δημιουργήστε ένα λογαριασμό ή συνδεθείτε για να σχολιάσετε

Πρέπει να είστε μέλος για να αφήσετε σχόλιο

Δημιουργία λογαριασμού

Εγγραφείτε με νέο λογαριασμό στην κοινότητα μας. Είναι πανεύκολο!

Δημιουργία νέου λογαριασμού

Σύνδεση

Έχετε ήδη λογαριασμό; Συνδεθείτε εδώ.

Συνδεθείτε τώρα
  • Δημιουργία νέου...