티스토리 뷰

2022.07.04 ~ 07.15

 

처음 1주차, 2주차는 코드잇 강의들을 보며 

 

파이썬과 장고를 공부했다.

 

Django는 설치..?와 쓰는 방법 정도만 배웠던 것 같다!

 

아무튼 3주차가 되어서야 정말.찐.실습을 시작했다!

 

2022.07.18

 

나도 드디어 이제 서버를 받았당!

 

이름은 gr_server ㅎㅅㅎ 왜 gr인지 고민하다가 다른 사원님 서버 보고 이유를 알았다ㅋㅋㅋ다들 그렇게 쓰나보다.

 

또다시 아무튼 내가 해야할 일은 

 

Postgresql에 있는 시군구 데이터를 geohash의 형태로 바꾸는 것이었다!

 

사실 geohash 자체도 처음들은 개념이다.

 

hash, 즉 해시함수의 의미는 임의의 길이를 갖는 임의의 데이터에 대해 고정된 길이의 데이터로 매핑하는 함수를 말한다.
따라서 geohash는 공간 상의 좌표값을 일정한 값으로 치환하는 것을 의미한다. 

 

 

 

 

지도에 나타내면 

 

 

이런 형태로 사각형 각이 진 형태로 나타난다.

 

 

 

 

 

 

import psycopg2
from shapely.geometry import MultiPolygon
from shapely.wkb import loads
from polygon_geohasher.polygon_geohasher import polygon_to_geohashes, geohashes_to_polygon
from shapely import geometry

conn = None
try:
    # read connection parameters

    # connect to the PostgreSQL server
    print('Connecting to the PostgreSQL database...')
    conn = psycopg2.connect("host=192.168.10.239 dbname=safelife user=postgres password=postgres port=5432")

    # create a cursor
    cur = conn.cursor()

    # execute a statement
    print('PostgreSQL database version:')
    #cur.execute('SELECT version()')

     
    sql = "SELECT * FROM sigungu ORDER BY gid ASC"
    cur.execute(sql)
    result = cur.fetchall()
    wkt = []
    outer_geohashes_polygon = []
    res = []

    sql = "DELETE FROM sigungu WHERE sig_cd IS NULL;"
    cur.execute(sql)
    conn.commit()
    sql = "ALTER TABLE sigungu ALTER COLUMN geom_id TYPE text;"
    cur.execute(sql)
    conn.commit()
    a = []
    b = []

    for i in range(0, 250):
        wkt.append(MultiPolygon(loads(result[i][4], hex=True)))
        outer_geohashes_polygon.append(geohashes_to_polygon(polygon_to_geohashes(wkt[i], 5, False)))
        res.append(polygon_to_geohashes(outer_geohashes_polygon[i], 5, inner=True))
        a.append(str(res[i]).replace("{", "("))
        b.append(str(a[i]).replace("}", ")"))
        sql = "UPDATE sigungu SET geom_id = "+b[i]+"WHERE gid ="+str(i+1)+";"
        cur.execute(sql)
        conn.commit()
   
   
    # display the PostgreSQL database server version
    db_version = cur.fetchone()
    print(db_version)

    # close the communication with the PostgreSQL
    #cur.close()
except (Exception, psycopg2.DatabaseError) as error:
    print(error)


finally:
    if conn is not None:
        conn.close()
        print('Database connection closed.')

 

 

코드리뷰를 받기 전이라 코드가.. 거지같다..ㅎ

 

 

코드를 대충 기록하자면

 

1. python - PostgreSQL 연동

2. polygon_to_geohashes 함수를 이용해 geometry형태로 존재하던 시군구 데이터를 구별로 geohash 값으로 바꿔 주는 것이다.

 

 

나온 geohash 값들을 DB에 컬럼으로 추가해주었다.

 

 

geohash 값을 지도에 표시해 주려면 다시 polygon의 형태로 나타내야 한다.

 

같은 라이브러리에 있는 geohashes_to_polygon을 쓰면 되는데

 

함수를 찾는데만 며칠씩이 걸렸다..

 

하루하루 나의 무지함과 무능력함에 놀라는 중이다..

 

 

import psycopg2
from shapely.geometry import MultiPolygon
from shapely.wkb import loads
from polygon_geohasher.polygon_geohasher import polygon_to_geohashes, geohashes_to_polygon
from shapely import geometry
import geohash

conn = None
try:
    # read connection parameters

    # connect to the PostgreSQL server
    print('Connecting to the PostgreSQL database...')
    conn = psycopg2.connect("host=192.168.10.239 dbname=safelife user=postgres password=postgres port=5432")

    # create a cursor
    cur = conn.cursor()

    # execute a statement
    print('PostgreSQL database version:')
    #cur.execute('SELECT version()')

     
    sql = "SELECT * FROM sigungu ORDER BY gid ASC"
    cur.execute(sql)
    result = cur.fetchall()
    wkt = []
    outer_geohashes_polygon = []
    res = []

    sql = "DELETE FROM sigungu WHERE sig_cd IS NULL;"
    cur.execute(sql)
    conn.commit()
    sql = "ALTER TABLE sigungu ALTER COLUMN geom_id TYPE text, ALTER COLUMN latlng TYPE text;"
    # sql2 = "ALTER TABLE sigungu ALTER COLUMN latlng TYPE geometry"
    cur.execute(sql)
    # cur.execute(sql2)
    conn.commit()
    a = []
    b = []
    res2 = []

    for i in range(0, 250):
        wkt.append(MultiPolygon(loads(result[i][4], hex=True)))
        outer_geohashes_polygon.append(geohashes_to_polygon(polygon_to_geohashes(wkt[i], 5, False)))
        res.append(polygon_to_geohashes(outer_geohashes_polygon[i], 5, inner=True))
        res2.append((wkt[i], 5, False))
        a.append(str(res[i]).replace("{", "("))
        b.append(str(a[i]).replace("}", ")"))
        sql = "UPDATE sigungu SET geom_id = " + b[i] + "WHERE gid =" + str(i+1) + ";"
        sql2 = "UPDATE sigungu SET latlng = '" + str(geohashes_to_polygon(res[i])) + "' WHERE gid =" + str(i+1) + ";"

        cur.execute(sql)
        cur.execute(sql2)
        conn.commit()
 
# ==========================================================================
   


    # display the PostgreSQL database server version
    db_version = cur.fetchone()
    print(db_version)

    # close the communication with the PostgreSQL
    #cur.close()
except (Exception, psycopg2.DatabaseError) as error:
    print(error)


finally:
    if conn is not None:
        conn.close()
        print('Database connection closed.')

 

 

코드를 쓰고 원하는 출력값을 찾고 나니 현타가 더 심하게 왔다,,,ㅎ

 

이 간단한걸 몇날며칠 씩이나 붙들고 있었다니...

 

 

 

 

아무튼 바꿔준 값 또한 res컬럼으로 추가 해주었다.

 

 

geometry의 형태로 sql에서 바꿔주었기 때문에 

 

지도 모양을 클릭하면 지도위에서 바로 확인이 가능하다.

'🐳 Experience > 현장실습' 카테고리의 다른 글

[현장실습] 5주차 회고록  (0) 2022.08.04
[현장실습] 4주차 회고록  (0) 2022.08.04
[현장실습] 4주차 회고록  (0) 2022.08.04
[현장실습] 4주차 회고록  (0) 2022.08.01
댓글
최근에 올라온 글
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Total
Today
Yesterday