Flask应用程序对Chrome扩展工具500内部服务器错误
我刚开始学习Flask,正在尝试制作一个Chrome扩展工具,用于检测钓鱼邮件。我想象这个系统的工作方式是,点击一个“提取”按钮,这个按钮会提取发件人、主题和邮件正文的文本,然后还有一个“扫描”按钮,它会分析提取出来的邮件正文,判断这封邮件是否是钓鱼邮件。
我可以提取邮件的信息,但当我点击“分析”按钮时,控制台显示500内部服务器错误。我尝试了一些方法来解决这个问题,但还是没能成功。
backend.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错误
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.'}, 400