python: request.json 无法获取请求body的json数据

1、http 请求header 增加 Content-Type:application/json 

2、或者使用 request.get_json(force=True) 忽略mimetype

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,在Flask中创建一个API端点,以从前端接收JSON数据。然后,使用Leaflet和JavaScript将数据可视化。 以下是实现的基本步骤: 1. 创建一个Flask应用程序,并使用以下代码创建一个API端点: ```python from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/data', methods=['POST']) def get_data(): data = request.get_json() # 对数据进行处理 # ... return jsonify({'success': True}) ``` 2. 在前端使用JavaScript和Leaflet发送JSON数据到API端点: ```javascript // 假设数据存储在一个名为data的数组中 const url = '/data'; const options = { method: 'POST', body: JSON.stringify(data), headers: { 'Content-Type': 'application/json' } }; fetch(url, options) .then(response => response.json()) .then(json => console.log(json)) .catch(error => console.error(error)); ``` 3. 在API端点中处理数据,并将其转换为可用于Leaflet的格式: ```python @app.route('/data', methods=['POST']) def get_data(): data = request.get_json() # 将数据转换为Leaflet格式 features = [] for item in data: feature = { "type": "Feature", "geometry": { "type": "Point", "coordinates": [item['x'], item['y']] }, "properties": { "label": item['label'] } } features.append(feature) geojson = { "type": "FeatureCollection", "features": features } return jsonify(geojson) ``` 4. 在前端使用Leaflet绘制聚类轨迹: ```javascript const map = L.map('map').setView([42.7373900, 123.2885100], 13); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: 'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' + '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' + 'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>', maxZoom: 18 }).addTo(map); fetch('/data') .then(response => response.json()) .then(geojson => { L.geoJSON(geojson, { pointToLayer: function (feature, latlng) { return L.circleMarker(latlng, { radius: 5, fillColor: getColor(feature.properties.label), color: "#000", weight: 1, opacity: 1, fillOpacity: 0.8 }); } }).addTo(map); }) .catch(error => console.error(error)); function getColor(label) { switch (label) { case 1: return "#ff0000"; case 2: return "#00ff00"; default: return "#0000ff"; } } ``` 这样,您就可以将JSON数据转换为Leaflet格式,并在地图上绘制聚类轨迹。请注意,这只是一个基本示例,您需要根据您的数据结构和要求进行更改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值