Flask配送费用计算器功能异常,请求技术排查帮助
配送费用计算器无法返回结果排查求助
我是一名初级Python开发者,搭建了一个基于Flask的配送费用计算器,计算公式为:配送费用 = 距离系数×距离 + 包裹重量系数×重量,系数从MongoDB中读取。运行应用时可正常访问首页,但点击计算按钮后无法得到结果,不确定是公式错误、index.html逻辑问题还是AJAX请求存在疏漏,相关代码如下:
Project/app.py
from flask import Flask, render_template, request, jsonify from flask_pymongo import PyMongo app = Flask(__name__) app.config['MONGO_URI'] = 'mongodb://localhost:27017/delivery_db' mongo = PyMongo(app) @app.route('/') def index(): return render_template('index.html') @app.route('/price', methods=['POST']) def get_price(): distance = int(request.form['distance']) weight = int(request.form['weight']) coefficients = mongo.db.coefficients.find_one() distance_coefficient = coefficients['distance_coefficient'] weight_coefficient = coefficients['weight_coefficient'] price = distance_coefficient * distance + weight_coefficient * weight return jsonify({'price': price}) @app.route('/admin', methods=['GET', 'POST']) def admin(): if request.method == 'POST': distance_coefficient = float(request.form['distance_coefficient']) weight_coefficient = float(request.form['weight_coefficient']) mongo.db.coefficients.update_one({}, {'$set': {'distance_coefficient': distance_coefficient, 'weight_coefficient': weight_coefficient}}) coefficients = mongo.db.coefficients.find_one() return render_template('admin.html', coefficients=coefficients) if __name__ == '__main__': app.run()
Project/templates/index.html
<!DOCTYPE html> <html> <head> <title>Delivery Calculator</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { $('form').submit(function(event) { // Stop form from submitting normally event.preventDefault(); // Get the distance and weight values var distance = $('input[name=distance]:checked').val(); var weight = $('input[name=weight]').val(); // Send an AJAX POST request to the Flask web service $.ajax({ type: 'POST', url: '/delivery_price', data: {'distance': distance, 'weight': weight}, success: function(response) { // Display the delivery price $('#delivery-price').text('$' + response['delivery_price'].toFixed(2)); }, error: function(error) { console.log(error); } }); }); }); </script> </head> <body> <h1>Delivery Calculator</h1> <form> <p>Select the distance:</p> <label><input type="radio" name="distance" value="10">10 km</label><br> <label><input type="radio" name="distance" value="25">25 km</label><br> <label><input type="radio" name="distance" value="50">50 km</label><br> <label><input type="radio" name="distance" value="100">100 km</label><br> <label><input type="radio" name="distance" value="101">Over 100 km</label><br> <p>Enter the package weight:</p> <input type="text" name="weight"><br><br> <button type="submit">Calculate</button> </form> <p>Delivery price: <span id="delivery-price"></span></p> </body> </html>
Project/static/js/script.js
$(document).ready(function() { // Handle form submission $('form').submit(function(event) { // Stop form from submitting normally event.preventDefault(); // Get the selected distance and package weight var distance = $('input[name=distance]:checked').val(); var weight = $('#weight').val(); // Send an AJAX request to the Flask web service to retrieve the delivery price $.ajax({ type: 'GET', url: '/price', data: {'distance': distance, 'weight': weight}, success: function(response) { // Display the delivery price $('#result').text('Delivery Price: ' + response['price']); }, error: function(error) { // Display an error message $('#result').text('Error: Unable to retrieve delivery price.'); console.log(error); } }); }); });
核心问题排查
- AJAX接口路径不匹配:index.html中AJAX请求的URL是
/delivery_price,但Flask后端的接口是/price,路径完全错误。 - 响应字段不匹配:后端返回的字段是
price,但index.html的AJAX成功回调中尝试读取response['delivery_price'],字段名不对应。 - 请求方法不匹配:后端
/price接口只接受POST方法,但script.js中用了GET请求,会直接返回405错误。 - DOM选择器不一致:
- index.html中重量输入框的选择器是
$('input[name=weight]'),但script.js中用了$('#weight'),而输入框并没有设置id="weight",导致无法获取重量值。 - 结果展示的元素ID:index.html中是
#delivery-price,但script.js中用了#result,两者不对应。
- index.html中重量输入框的选择器是
- MongoDB数据缺失风险:如果
coefficients集合中没有任何文档,find_one()会返回None,访问coefficients['distance_coefficient']会直接抛出异常,导致接口崩溃。 - 未处理未选择距离的情况:如果用户没选任何距离单选框,
$('input[name=distance]:checked').val()会返回undefined,传到后端转int时会报错。
修复建议
- 统一AJAX请求路径:将index.html中的AJAX URL改为
/price。 - 统一响应字段:将index.html回调中的
response['delivery_price']改为response['price']。 - 统一请求方法:要么把后端
/price的methods改成['GET', 'POST'],要么把script.js中的请求类型改为POST(推荐POST,因为是计算操作)。 - 修正DOM选择器:
- 给重量输入框添加
id="weight",或者统一选择器为$('input[name=weight]')。 - 统一结果展示元素的ID,比如都用
#delivery-price。
- 给重量输入框添加
- 处理MongoDB空数据:在
get_price()中先判断coefficients是否存在,不存在则返回错误提示,比如:coefficients = mongo.db.coefficients.find_one() if not coefficients: return jsonify({'error': 'Coefficients not found, please set them in admin page'}), 400 - 添加前端校验:在发送AJAX前检查是否选择了距离、重量是否为空,比如:
if (!distance || !weight) { alert('Please select distance and enter weight'); return; }
内容的提问来源于stack exchange,提问作者CcLoooS
相关产品推荐
相关产品推荐

