简体   繁体   English

如何使用 Flask 在 PostgreSQL 中存储线路?

[英]How I can store line in PostgreSQL using Flask?

I have a problem.我有个问题。 I'm building an application using Flask, database in PostgreSQL and Leaflet.我正在使用 Flask、PostgreSQL 和 Leaflet 中的数据库构建应用程序。 In the application the user can draw a line by clicking on the map all points are added to array and create a line( all code in js).在应用程序中,用户可以通过单击 map 来绘制一条线,所有点都添加到数组中并创建一条线(所有代码在 js 中)。 I created a columns in database in Flask using SQLAlchemy.我使用 SQLAlchemy 在 Flask 的数据库中创建了一个列。 I wonder how I can store this road as a line in database?我想知道如何将这条道路作为一条线存储在数据库中? Does such a type exists in SQLAlchemy? SQLAlchemy中是否存在这种类型?

Function in js js中的Function

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)

Minimal working code which uses modern fetch() to send data from browser to Flask, and it keep it on list.使用现代fetch()将数据从浏览器发送到 Flask 的最小工作代码,并将其保留在列表中。 Later you can load it back and it also use fetch() to get it from Flask.稍后您可以将其加载回来,它还使用fetch()从 Flask 获取它。

I use render_template_string instead of render_template only to make it simpler for test.我使用render_template_string而不是render_template只是为了简化测试。 Everyone can copy code to one file and test it.每个人都可以将代码复制到一个文件中并进行测试。

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM