Chrome 扩展工具的 Flask App 500 内部服务器错误

问题描述 投票:0回答:1

我是 Flask 新手,我正在尝试为网络钓鱼电子邮件检测系统创建一个 chrome 扩展工具。我想象该系统的工作原理是单击“提取”按钮,该按钮将提取发件人、主题和电子邮件正文文本,以及一个扫描按钮,该按钮将分析提取的电子邮件正文以确定它是否是网络钓鱼电子邮件。

我可以提取电子邮件的信息,但是当我单击分析按钮时,它在控制台中显示 500 内部服务器错误。尝试研究一些方法来解决这个问题,但仍然不行。

后端.py

import traceback
from flask import Flask, request, jsonify
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from flask_cors import CORS
import json
import logging
from http import HTTPStatus


app = Flask(__name__)


# Load the dataset
dataset = pd.read_csv("mail_data.csv")

# replace null value with null string
mail_data = dataset.where((pd.notnull(dataset)), '')

# label spam mail as 0; authentic as 1
mail_data.loc[mail_data['Category'] == 'spam', 'Category',] = 0
mail_data.loc[mail_data['Category'] == 'authentic', 'Category',] = 1

# Assuming your dataset has a 'text' column containing the email content and a 'label' column for phishing or not
X = mail_data['Message']
Y = mail_data['Category']

# Feature Extraction
feature_extraction = TfidfVectorizer(min_df=1, stop_words='english', lowercase=True)
X_features = feature_extraction.fit_transform(X)

# Convert Y values as integers
Y = Y.astype('int')

# Train the model
model = LogisticRegression()
model.fit(X_features, Y)


@app.route('/', methods=['GET', 'POST'])
def predict_phishing():
    if request.method == 'POST':
        email_content = request.json.get('email_content', '')
        # Feature extraction for the input data

        email_content_feature = feature_extraction.transform([email_content])
        # Make prediction using the trained model
        prediction = model.predict(email_content_feature)[0]

        

        return jsonify({'prediction': prediction})
    # If the request method is GET, return a message
    else:
        return jsonify({'message': 'Please use POST method to make predictions.'})
    

   
if __name__ == '__main__':
    app.run(debug=True)
    
    
 

popup.js

// Variable to store email subject, sender, and message
let emailSubjectSenderMessage = {};

// Function to send a message to content.js to extract email content
function extractEmailContent() {
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    if (tabs && tabs.length > 0 && tabs[0].id) {
      const activeTab = tabs[0];
      chrome.tabs.sendMessage(activeTab.id, { action: 'extractEmailContent' }, (response) => {
        if (chrome.runtime.lastError) {
          // Handle any errors in sending the message

        } else {
          // Check if the response contains emailContent
          if (response && response.emailContent) {
            // Extracted email content
            const emailContent = response.emailContent;

            // Extracted sender's email address
            const senderEmail = emailContent.senderEmail;

            // Store the email subject, sender, and message in the variable
            emailSubjectSenderMessage = {
              subject: emailContent.subject,
              sender: senderEmail,
              message: emailContent.body
            };

            // Display the extracted content including the sender's email address
            displayEmailContent(emailContent, senderEmail);
          } else {
            displayErrorMessage('No email data found on this page.');
          }
        }
      });
    } else {
      console.error('Invalid tab or tab ID not available.');
    }
  });
}


// Function to display the extracted email content
function displayEmailContent(emailContent, senderEmail) {
  const emailContentDiv = document.getElementById('emailContent');
  emailContentDiv.innerHTML = `<strong>Sender:</strong> ${senderEmail}<br><strong>Subject:</strong> ${emailContent.subject}<br><strong>Message:</strong> ${emailContent.body}`;
}

// Function to display an error message
function displayErrorMessage(message) {
  const emailContentDiv = document.getElementById('emailContent');
  emailContentDiv.textContent = message;
}




// Add a click event listener to the extract button
document.getElementById('extractButton').addEventListener('click', extractEmailContent);

// Add a click event listener to the scan button
document.getElementById('scanButton').addEventListener('click', scanEmailContent);


// Function to send the extracted email content to the Flask server for prediction
function scanEmailContent() {
  // Check if email content is available
  if (Object.keys(emailSubjectSenderMessage).length === 0) {
    displayErrorMessage('Please extract email content first.');
    return;
  }

  // Extracted email content
  const emailContent = emailSubjectSenderMessage.message;

  // Make an HTTP POST request to Flask server for prediction
  fetch('http://127.0.0.1:5000', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      email_content: emailContent,
    }),
  })
    .then(response => response.json())
    .then(data => {
      // Handle the prediction result
      const prediction = data.prediction;

      // Display the prediction result
      displayPredictionResult(prediction);
    })
    .catch(error => {
      console.error('Error in predicting phishing:', error);
      console.log('Response Content:');
      displayErrorMessage('Error in predicting phishing. Please try again.');
    });
}


// Function to display the prediction result
function displayPredictionResult(prediction) {
  const emailContentDiv = document.getElementById('emailContent');
  let resultMessage;

  if (prediction === 0) {
    resultMessage = 'This email is predicted as a phishing email.';
  } else {
    resultMessage = 'This email is predicted as authentic.';
  }

  emailContentDiv.textContent = resultMessage;
}

我尝试过只使用“POST”

@app.route('/', methods=[ 'POST'])

但是我最终得到了错误 405

python flask google-chrome-extension gmail phishing
1个回答
0
投票

不需要做

jsonify()
。这应该有效

@app.route('/', methods=['GET', 'POST'])
def predict_phishing():
    if request.method == 'POST':
        email_content = request.json.get('email_content', '')
        # Feature extraction for the input data

        email_content_feature = feature_extraction.transform([email_content])
        # Make prediction using the trained model
        prediction = model.predict(email_content_feature)[0]

        

        return {'prediction': prediction}, 200
    # If the request method is GET, return a message
    else:
        return {'message': 'Please use POST method to make predictions.'}, 200
© www.soinside.com 2019 - 2024. All rights reserved.