Flask API возвращает «Метод не разрешен (405)» для запроса POST [закрыто]Python

Программы на Python
Ответить
Anonymous
 Flask API возвращает «Метод не разрешен (405)» для запроса POST [закрыто]

Сообщение Anonymous »

Я создаю Flask API для системы рекомендаций по питанию, где я использую обученную модель машинного обучения, чтобы предлагать блюда на основе информации о пищевой ценности и ингредиентов, предоставленных в запросе. Ниже приведен код моего приложения Flask:

Код: Выделить всё

import numpy as np
import re
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import NearestNeighbors
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import FunctionTransformer
import joblib
from flask import Flask, request, jsonify

# Initialize Flask app
app = Flask(__name__)

# Function to scale the data
def scaling(dataframe):
scaler = StandardScaler()
prep_data = scaler.fit_transform(dataframe.iloc[:, 6:15].to_numpy())
return prep_data, scaler

# Function to train the Nearest Neighbors model
def nn_predictor(prep_data):
neigh = NearestNeighbors(metric='cosine', algorithm='brute')
neigh.fit(prep_data)
return neigh

# Build a pipeline with scaling and the Nearest Neighbors model
def build_pipeline(neigh, scaler, params):
transformer = FunctionTransformer(neigh.kneighbors, kw_args=params)
pipeline = Pipeline([('std_scaler', scaler), ('NN', transformer)])
return pipeline

# Extract data filtered by ingredients
def extract_data(dataframe, ingredients):
extracted_data = dataframe.copy()
extracted_data = extract_ingredient_filtered_data(extracted_data, ingredients)
return extracted_data

def extract_ingredient_filtered_data(dataframe, ingredients):
extracted_data = dataframe.copy()
regex_string = ''.join(map(lambda x: f'(?=.*{x})', ingredients))
extracted_data = extracted_data[
extracted_data['RecipeIngredientParts'].str.contains(regex_string, regex=True, flags=re.IGNORECASE)
]
return extracted_data

# Apply the pipeline to input data
def apply_pipeline(pipeline, _input, extracted_data):
_input = np.array(_input).reshape(1, -1)
return extracted_data.iloc[pipeline.transform(_input)[0]]

# Recommendation function
def recommend(dataframe, _input, ingredients=[], params={'n_neighbors': 5, 'return_distance': False}):
extracted_data = extract_data(dataframe, ingredients)
if extracted_data.shape[0] >= params['n_neighbors']:
prep_data, scaler = scaling(extracted_data)
neigh = nn_predictor(prep_data)
pipeline = build_pipeline(neigh, scaler, params)
return apply_pipeline(pipeline, _input, extracted_data)
else:
return None

# Format the output to include only meal names and nutritional content
def output_recommended_recipes(dataframe):
if dataframe is not None:
output = dataframe.copy()
output = output[[
"Name", "Calories", "FatContent", "SaturatedFatContent", "CholesterolContent",
"SodiumContent", "CarbohydrateContent", "FiberContent", "SugarContent", "ProteinContent"
]]
return output.to_dict("records")
else:
return None

# Save the pipeline
def save_model(pipeline, model_path):
joblib.dump(pipeline, model_path)
print(f"Model saved to {model_path}")

# Load the pipeline
def load_model(model_path):
return joblib.load(model_path)

# Load the dataset (adjust this path to your local setup)
dataset_path = "C:\\Users\\CompuHouse\\Desktop\\project\\dataset.csv"
dataset = pd.read_csv(dataset_path, compression="gzip")

# Main Flask API route to handle recipe recommendations
@app.route('/recommend', methods=['POST'])
def recommend_recipes():
data = request.json  # Get the input data as JSON

# Extract the nutritional information and ingredients from the request
try:
test_input = [
data['Calories'],
data['FatContent'],
data['SaturatedFatContent'],
data['CholesterolContent'],
data['SodiumContent'],
data['CarbohydrateContent'],
data['FiberContent'],
data['SugarContent'],
data['ProteinContent']
]
except KeyError as e:
return jsonify({'error': f'Missing key:  {str(e)}'}), 400

ingredients = data.get('ingredients', [])

# Extract and preprocess data
extracted_data = dataset.copy()  # You can adjust this if you want filtering by ingredients
prep_data, scaler = scaling(extracted_data)

# Train the Nearest Neighbors model
neigh = nn_predictor(prep_data)

# Build the pipeline
pipeline = build_pipeline(neigh, scaler, {'n_neighbors': 5, 'return_distance': False})

# Get recommendations
recommendations = apply_pipeline(pipeline, test_input, extracted_data)
output = output_recommended_recipes(recommendations)

if output:
return jsonify({'recommendations': output}), 200
else:
return jsonify({'message': 'No recommendations found'}), 404

# Main function to run the Flask app
if __name__ == '__main__':
# Save model (ensure save_model is defined before calling)
model_path = "recipe_recommendation_pipeline.pkl"
save_model(build_pipeline(nn_predictor(scaling(dataset)[0]), StandardScaler(), {'n_neighbors': 5, 'return_distance': False}), model_path)

# Run the Flask app
app.run(debug=True)

Когда я запускаю этот код, сервер успешно запускается:

Код: Выделить всё

Model saved to recipe_recommendation_pipeline.pkl
* Tip: There are .env or .flaskenv files present. Do "pip install python-dotenv" to use them.
* Serving Flask app "api_experiment" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with watchdog (windowsapi)
Model saved to recipe_recommendation_pipeline.pkl
* Tip: There are .env or .flaskenv files present. Do "pip install python-dotenv" to use them.
* Debugger is active!
* Debugger PIN: 375-382-198
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Однако, когда я делаю запрос к конечной точке /recommend с помощью клиента REST, такого как Postman или CURL, я получаю следующий ответ:

Код: Выделить всё

127.0.0.1 - - [27/Dec/2024 18:19:42] "GET /recommend HTTP/1.1" 405 -
введите здесь описание изображения
Я получаю сообщение «Метод запрещен»
так как я могу решить эту проблему

Подробнее здесь: https://stackoverflow.com/questions/793 ... st-request
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»