'파이썬/Python 활용'에 해당되는 글 3건

728x90

class 에서 db 를 호출하고 처리하는 코드를 구현하기 위한 샘플을 작성했다.

 

class Config(object):
  DATABASE_CONFIG = {
          'server''localhost',
          'user''root',
          'password''autoset',
          'dbname''pythondb',
          }
 
 
from config import Config
import mariadb
import sys
 
class DbConnection:
    def __init__(self):
        self._conn=mariadb.connect(
            user=Config.DATABASE_CONFIG['user'],
            password=Config.DATABASE_CONFIG['password'],
            host=Config.DATABASE_CONFIG['server'],
            port=3306,
            database=Config.DATABASE_CONFIG['dbname']
        )
        self._cursor = self._conn.cursor()
 
    def __enter__(self):
        return self
 
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()
 
    @property
    def connection(self):
        return self._conn
 
    @property
    def cursor(self):
        return self._cursor
 
    def commit(self):
        self.connection.commit()
 
    def close(self, commit=True):
        if commit:
            self.commit()
        self.connection.close()
 
    def execute(self, sql, params=None):
        self.cursor.execute(sql, params or ())
 
    def fetchall(self):
        return self.cursor.fetchall()
 
    def fetchone(self):
        return self.cursor.fetchone()
 
    def query(self, sql, params=None):
        self.cursor.execute(sql, params or ())
        return self.fetchall()
 
    def rows(self):
        return self.cursor.rowcount

 

 

 
# pip install pymysql or pip install mariadb
 
from dbconn import DbConnection
 
db = DbConnection()
 
class LoginClass:
    def WebLogin(self,userid, password):
        pass
 
    def sampleQuery(self,sql):
        rows = db.query(sql)
        print(rows)
        print(db.rows())
 
    def sampleQueryResult(self,sql):
        rs = db.query(sql)
        # print(db.rows())
        return rs
 

 

테스트를 위해서 위와 같은 샘플 함수를 만들어서 테스트했다.

DB와 다른 기능을 혼용하여 함수를 구현하기 위한 목적이다.

from loginclass import LoginClass
 
if __name__ == '__main__':
 
    params = tuple([1,3,4])
    sql = 'select * from errorcode where codeID IN {}'.format(params)
 
    auth = LoginClass()
    auth.sampleQuery(sql)
 
    rs = auth.sampleQueryResult('select * from errorcode')
    print(rs)
 

 

 

'파이썬 > Python 활용' 카테고리의 다른 글

[Python] Naver API 주소 좌표변환 예제  (0) 2022.03.16
[파이썬] 엑셀 파일 읽고 쓰기  (0) 2021.07.02
블로그 이미지

Link2Me

,
728x90

Naver API 를 이용하여 주소를 위치좌표로 변환하는 예제 코드이다.

 

https://link2me.tistory.com/1832 를 참조하고, geocoding API 를 신청하고 나서 인증정보를 눌러보면 아래와 같은 key 정보를 알 수 있다.

 

 

Client ID, Client Secret 키를 복사해서 아래 코드에 붙여넣기 한다.

# python.exe -m pip install --upgrade pip
# pip install requests
# pip install openpyxl
class
 NaverAPI:
    def geocoding(self, addr):
        import requests
 
        client_id = ""
        client_secret = ""
 
        url = f"https://naveropenapi.apigw.ntruss.com/map-geocode/v2/geocode?query={addr}"
        headers = {'X-NCP-APIGW-API-KEY-ID': client_id,
                   'X-NCP-APIGW-API-KEY': client_secret
                   }
 
        r = requests.get(url, headers=headers)
 
        if r.status_code == 200:
            data = r.json()
            lat = data['addresses'][0]['y']  # 위도
            lng = data['addresses'][0]['x']  # 경도
            stAddress = data['addresses'][0]['roadAddress'# 도로명 주소
            list = [lat,lng,stAddress]
            return list
 

 

class 를 만든 후 아래와 같이 인스턴스를 생성하여 사용하면 된다.

엑셀 처리를 해도 되고 DB와 연동하여 다량의 데이터를 처리해도 된다.

from NaverAPI import NaverAPI
 
if __name__ == '__main__':
    addr = '서울시 서초구 서초대로50길 8'
    naverapi = NaverAPI()
    arr = naverapi.geocoding(addr)
 
    print(arr)
    print(arr[0])
    print(arr[1])
    print(arr[2])
 

 

 

'파이썬 > Python 활용' 카테고리의 다른 글

[Python] mariadb connection in a class  (0) 2022.03.16
[파이썬] 엑셀 파일 읽고 쓰기  (0) 2021.07.02
블로그 이미지

Link2Me

,
728x90

파이썬을 이용하여 엑셀을 읽고 특정 셀에 기록하는 코드 간단 예제이다.

 

# pip install requests
# pip install openpyxl
 
import requests
import openpyxl
import json
 
## 엑셀 파일 오픈
filename = "address.xlsx"
wb = openpyxl.load_workbook(filename)
 
## 시트 설정
# sheet = wb.worksheets[0] # active 시트 열기
sheet = wb['Sheet3']  # 시트명 직접 적어주기
 
## 데이터 가져오기
rowCount = 2
for row in sheet.rows:    
 
    try:
        ## 엑셀 읽어오기
        read_cell = row[1].value
        print(read_cell)
 
        ## cell 설정 
        lat_cell = sheet.cell(row = rowCount, column = 3)  # C열은 3
        lng_cell = sheet.cell(row = rowCount, column = 4)
 
        ## 데이터 추가
        lat_cell.value = "위도"
        lng_cell.value = "경도"
 
    except KeyError as ke:
        lat_cell.value = 0
        lng_cell.value = 0
    except TypeError as te:
        lat_cell.value = 0
        lng_cell.value = 0
        
    rowCount = rowCount + 1
 
## 데이터 저장 (엑셀 파일이 열린 상태에서는 저장 실패)
wb.save("address.xlsx")
 
# 닫기
wb.close()
 

 

'파이썬 > Python 활용' 카테고리의 다른 글

[Python] mariadb connection in a class  (0) 2022.03.16
[Python] Naver API 주소 좌표변환 예제  (0) 2022.03.16
블로그 이미지

Link2Me

,