首页 > 解决方案 > 如何使用 Flask 在 PostgreSQL 中存储行?

问题描述

我有个问题。我正在使用 Flask、PostgreSQL 和 Leaflet 中的数据库构建一个应用程序。在应用程序中,用户可以通过单击地图绘制一条线,所有点都添加到数组中并创建一条线(js中的所有代码)。我使用 SQLAlchemy 在 Flask 中的数据库中创建了一个列。我想知道如何将这条道路作为一条线存储在数据库中?SQLAlchemy 中是否存在这种类型?

js中的函数

function clickonMap(event){
        dict = event.latlng
        coordintates.push(Object.values(dict))
        if(mymap.hasLayer(polyline)){
            polyline.remove()
        }
        mark = L.marker(event.latlng,{icon: markerIcon}).addTo(mymap);
        markers.push(mark)
        polyline = L.polyline(coordintates,{color: 'red'}).addTo(mymap)

标签: javascriptpythonhtmlpostgresqlflask

解决方案


fetch()使用现代将数据从浏览器发送到 Flask 的最小工作代码,并将其保留在列表中。稍后您可以将其加载回来,它也可以fetch()用于从 Flask 获取它。

我使用render_template_string而不render_template只是为了简化测试。每个人都可以将代码复制到一个文件中并进行测试。

from flask import Flask, request, render_template_string, jsonify

app = Flask(__name__)


@app.route('/')
def index():
    return render_template_string('''
<!DOCTYPE html>

<html>

<head>
 <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
   integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
   crossorigin=""/>       
<!-- Make sure you put this AFTER Leaflet's CSS -->
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"
   integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
   crossorigin=""></script>       
</head>

<body>

<div id="map" style="width:400px; height: 300px;"></div>   

<button onclick="save();">Save</button>
<button onclick="clean();">Clean</button>
<button onclick="load();">Load</button>

<script>

    var mymap = L.map('map').setView([51.505, -0.09], 13);

    L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
        maxZoom: 18,
        attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, ' +
            'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
        id: 'mapbox/streets-v11',
        tileSize: 512,
        zoomOffset: -1
    }).addTo(mymap);
    
    var coordintates = [];
    var polyline = [];
    
    function clickOnMap(event){
        latlng = event.latlng;
        
        coordintates.push(Object.values(latlng));
        
        if(mymap.hasLayer(polyline)){
            polyline.remove();
        }
        
        // mark = L.marker(event.latlng, {icon: markerIcon}).addTo(mymap);
        // markers.push(mark);
        
        polyline = L.polyline(coordintates, {color: 'red'}).addTo(mymap);
    }

    mymap.on('click', clickOnMap);

    function save() {
        // console.log(coordintates);
        
        fetch('/save', {
            method: 'POST',
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(coordintates)
        });
    }
    
    function clean() {
        if(mymap.hasLayer(polyline)){
            polyline.remove();
            coordintates = [];
        }
        
        // console.log(coordintates);
    }

    function load() {
        fetch('/load')
        .then(res => res.json())
        .then(data => {
                
            coordintates = data;

            // console.log(coordintates);
            
            if(mymap.hasLayer(polyline)){
                polyline.remove();
            }
            
            polyline = L.polyline(coordintates, {color: 'red'});
            // console.log(polyline);
            polyline.addTo(mymap);
        });
    }
    
</script>
</body>
</html>
''')

database = []

@app.route('/save', methods=['GET', 'POST'])
def save():
    data = request.json 
    print('save:', data)
    database.append(data)
    return "OK"

@app.route('/load', methods=['GET', 'POST'])
def load():
    if database:
        data = database[-1]
    else:
        data = []        
    print('load:', data)
    return jsonify(data)
    
if __name__ == '__main__':
    app.debug = True
    app.run() #debug=True 

推荐阅读