搭建简单的flask框架,并连接postgresql进行postgis操作

一、网站结构如下:

搭建简单的flask框架,并连接postgresql进行postgis操作_第1张图片

注意html页面需要放在名为templates的文件夹下,这是flask的规定。

二、Postgis操作

位于pgConnect.py中,代码如下:

#encoding: utf-8
import psycopg2
def insertGeo(start_time,end_time,reg_name,reg_radius,valid_time,reg_gov,guid,geom):
    conn = psycopg2.connect(database="noFly",user="postgres",password="123",host="192.168.0.236",port="5433")
    cur = conn.cursor()
    sql="insert into tablename (is_enable,start_time,end_time,reg_name,reg_radius,valid_time,reg_gov,guid,geom) values ('1','{0}','{1}','{2}',{3},'{4}','{5}','{6}',ST_GeomFromGeoJson('{7}'))".format(start_time,end_time,reg_name,reg_radius,valid_time,reg_gov,guid,geom)
    print(sql)
    cur.execute(sql)
    conn.commit()
    print('更新成功')

三、模板页:

base.html代码:




    
    Title
    

    


    
    {% block main %}

    {% endblock %}

update.html代码:

{% extends "base.html" %}

{% block main %}
    
开始时间:
结束时间:
区域名称:
区域半径:
有效时间:
发布单位:
唯一值:
geojson:
{% endblock %}

启动文件,flaskTest.py代码:

# -*- coding: utf-8 -*-
# manman.py 一个简单的小程序
from flask import Flask,url_for,redirect,render_template,request
import pgConnect
import sys
reload(sys)
sys.setdefaultencoding('utf8')
app = Flask(__name__)
@app.route('/')
def index():
    return render_template('update.html')
@app.route('/api/update/',methods=['POST','GET'])
def update():
    try:
        # pgConnect.insertGeo(start_time,end_time,reg_name,reg_radius,valid_time,reg_gov,guid,geom)
        # return "{'success':'true','mess':'更新成功'}"
        if request.method == 'GET':
            return render_template('update.html')
        else:
            start_time = request.form.get('start_time')#post请求。获取模版语言中输入框输入的值
            end_time = request.form.get('end_time')
            reg_name = request.form.get('reg_name')
            reg_radius = request.form.get('reg_radius')
            valid_time = request.form.get('valid_time')
            reg_gov = request.form.get('reg_gov')
            guid = request.form.get('guid')
            geom = request.form.get('geom')
            pgConnect.insertGeo(start_time,end_time,reg_name,reg_radius,valid_time,reg_gov,guid,geom)
            return "{'success':'true','mess':'更新成功'}"
    except Exception, e:
        return "{'success':'false','mess':'更新失败:'"+str(e)+"}"

if __name__ == '__main__':
    app.run(debug=True)#开启调试模式,这样就不必在修改代码之后手动重启了

完整代码地址:https://gitee.com/mingjingzhishui/python-flask/tree/postgis-insert/

你可能感兴趣的:(python,flask,Flask+GIS)