반응형

sqlalchemy는 파이썬에서 DB에 접근하기 위한 ORM 라이브러리다.

 

ORM은 Object Relational Mapping의 약어로써 객체(Object)와 관계형 DB(Relational)을 연결(Mapping) 해주는 것을 의미한다.

객체지향언어에서 객체(클래스)에 DB 테이블을 매핑시켜 사용한다고 생각하면 이해가 쉽다.

ORM은 설계에 따라 사용이 용이할 수도 어려워질 수가 있다.

 

* sqlalchemy

사이트 : https://www.sqlalchemy.org/

 

SQLAlchemy - The Database Toolkit for Python

The Python SQL Toolkit and Object Relational Mapper SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL. It provides a full suite of well known enterprise-level persisten

www.sqlalchemy.org

지원하는 Databases : SQLite, Postresql, MySQL, Oracle, MS-SQL, Firebird, Sybase 등..

사용가능한 Python 버전 : 2.5이후 또는 3.x 버전

 

SQLAlchemy를 사용하기 위해 우선적으로 DB Engine을 생성해야 한다

from sqlalchemy import create_engine
#engine 생성
#password 특수문자 포함 시 password에 url 인코딩 필요
engine = create_engine("postgresql://{username}{password}@{host}/{database}")

#password 인코딩 예시
import urllib.parse
print(urllib.parse.quote_plus("kx@jj5/g")) #'kx%40jj5%2Fg' 출력

from sqlalchemy import URL
#URL을 이용한 engine생성
#password에 특수문자가 포함 시 인코딩 하지 않고 사용할 수 있음.
url_object = URL.create(
	drivername="",
    username={username},
    password={password},
    host={host},
    database={database},
    query={"charset":"cp949"}
    )
engine = create_engine(url_object)

위와 같이 생성한다.

 

* 각 DB별 engine 생성 샘플

# mysql default
engine = create_engine("mysql://scott:tiger@localhost/foo")

# mysqlclient (a maintained fork of MySQL-Python)
engine = create_engine("mysql+mysqldb://scott:tiger@localhost/foo")

# PyMySQL
engine = create_engine("mysql+pymysql://scott:tiger@localhost/foo")

#Oracle
engine = create_engine("oracle://scott:tiger@127.0.0.1:1521/sidname")
engine = create_engine("oracle+cx_oracle://scott:tiger@tnsname")

# mssql pyodbc
engine = create_engine("mssql+pyodbc://scott:tiger@mydsn")

# pymssql
engine = create_engine("mssql+pymssql://scott:tiger@hostname:port/dbname")

# sqlite://<nohostname>/<path>
# where <path> is relative:
engine = create_engine("sqlite:///foo.db")

# Unix/Mac - 4 initial slashes in total
engine = create_engine("sqlite:////absolute/path/to/foo.db")

# Windows
engine = create_engine("sqlite:///C:\\path\\to\\foo.db")

# Windows alternative using raw string
engine = create_engine(r"sqlite:///C:\path\to\foo.db")

참고 문서 : https://docs.sqlalchemy.org/en/20/core/engines.html#supported-databases

반응형

'프로그래밍 > Python' 카테고리의 다른 글

[PYTHON] 파이썬 함수 매개변수  (0) 2022.08.11
[Python] flask_restful fields  (0) 2021.10.08
Single Linked list 구현  (0) 2018.03.22
창원시 버스 API 사용하기  (1) 2016.02.22
반응형

파이썬에서 사용하는 함수 매개변수 종류에 대해 작성

 

파이썬에서는 아래 5가지 종류의 함수 매개변수를 선언해서 사용할 수 있다.

1. default arguments

2. keyword arguments

3. positional arguments

4. arbitrary positional arguments

5. arbitrary keyword arguments

 

1. default arguments

  • 기본 매개변수는 함수가 정의되는 동안 제공된는 값이다.
  • "=" 기호를 사용해 매개변수의 기본값을 설정한다.
  • 기본 매개변수는 함수 호출 동안 선택적으로 사용된다.
  • 함수 호출 시 기본 매개변수에 값을 제공하면 기본 매개변수에 덮어 씌여진다.
  • 함수는 기본 매개변수를 원하는 만큼 가질 수 있다. (갯수 제한 없음)
  • 기본값 설정이 필수적이지 않다.

예시)

def add(a, b=5, c=10):
	return (a+b+c)

위 예시는 b,c가 기본 매개변수로 설정되어 있는 것을 보여준다.

아래 함수 호출 예시를 참고

print(add(3)) #return 18 a = 3, b = 5, c = 10
print(add(3,4)) #return 17 a = 3, b = 4, c = 10
print(add(2,3,4)) #return 9 a = 2, b = 3, c =4

 

2. Keyword Arguments

  • key = value 형식으로 사용하는 매개변수
  • 함수에 정의된 매개변수 순서를 따르지 않아도 값이 통과된다.
  • 키워드 매개변수는 함수에 정의 된 매개변수랑 일치해야한다.
  • 함수 호출시 사용되는 매개변수 타입 중 하나이다.

예시)

def add(a,b=5,c=10):
    return (a+b+c)

위와 같이 함수를 선언한다.

아래 예시와 같이 함수 호출시 매개변수를 key=value 로 사용하는 것을 keyword arguments 라 한다.

정의된 매개변수 순서를 지키지 않고 매개변수 키 값만 알맞게 설정하여 호출 가능하다.

print (add(b=10,c=15,a=20)) #return 45
print (add(a=10)) #return 25

 

3. Positional Arguments

  • 위치 매개변수 함수 호출 시 매개변수 위치에 값을 대입하여 호출하는 것을 의미한다.

예시)

def add(a,b,c):
    return (a+b+c)
    
print (add(10,20,30)) #return 60
print (add(10,c=30,b=20)) #return 60

위 첫번째 print 문과 같이 매개변수 위치에 값을 설정하여 호출 가능하다.

두번째 print 문처럼 keyword 매개변수와 섞어서 사용이 가능하다.

 

위 세가지 매개변수 사용에 대해 주의할 점!

 

#1. default 매개변수는 non-defualt 매개변수보다 앞에 선언할 수 없다.
def add(a=5,b,c):
    return (a+b+c)
#Output:SyntaxError: non-default argument follows default argument

#2. keyword 매개변수는 positional 매개변수보다 앞에 선언할 수 없다.
def add(a,b,c):
    return (a+b+c)
print (add(a=10,3,4))
#Output:SyntaxError: positional argument follows keyword argument

#3. 선언되지 않은 keyword 매개변수는 사용불가
def add(a,b,c):
    return (a+b+c)
print (add(a=10,b1=5,c=12))
#Output:TypeError: add() got an unexpected keyword argument 'b1'

#4. 중복된 keyword 매개변수 사용 불가
def add(a,b,c):
    return (a+b+c)
print (add(a=10,b=5,b=10,c=12))
#Output:SyntaxError: keyword argument repeated

 

4. arbitrary positional arguments

  • 매개변수 앞에 *를 사용하여 선언한 매개변수
  • 매개변수 선언을 가변적으로 설정할 때 사용한다.
  • 매개변수를 list 타입과 동일하게 사용

예시)

def add(*b):
    result=0
    for i in b:
         result=result+i
    return result

print (add(1,2,3,4,5)) #return 15
print (add(10,20)) #return 30

위 예시처럼 add 함수에 매개변수를 가변적으로 설정하여 호출이 가능하다

 

5. arbitrary keyword arguments

  • 매개변수 앞에 **를 사용하여 선언한 매개변수
  • 4번과 같이 매개변수를 가변적으로 설정할 수 있고 key:value 매개변수를 dictionary 타입과 동일하게 사용

예시)

def fn(**a):
    for i in a.items():
        print (i)
fn(numbers=5,colors="blue",fruits="apple")
'''
return
('numbers', 5)
('colors', 'blue')
('fruits', 'apple')
'''

 

참고 사이트 : https://levelup.gitconnected.com/5-types-of-arguments-in-python-function-definition-e0e2a2cafd29

반응형

'프로그래밍 > Python' 카테고리의 다른 글

[Python]sqlalchemy 사용법  (0) 2022.12.07
[Python] flask_restful fields  (0) 2021.10.08
Single Linked list 구현  (0) 2018.03.22
창원시 버스 API 사용하기  (1) 2016.02.22
반응형

Python Flask api 앱을 만드는 도중 marshal_with 와 fields 라이브러를 이용해

output 데이터 타입을 설정할 떄 찾은 팁 공유

 

아래와 같이 사용하면 특정한 타입으로 응답필드 값을 설정하여 사용할 수 있다.

from flask_restful import fields

class MyDateFormat(fields.Raw):
    def format(self, value):
        return value.strftime('%Y-%m-%d')

resource_fields = {
    'id': fields.Integer,
    'date': MyDateFormat
}

참조

https://stackoverflow.com/questions/65982519/custom-date-format-for-flask-restful-fields-datetime-for-marshal-with

 

Custom date format for flask_restful fields.DateTime for marshal_with

I am using flask_restful's fields and marshal_with to serialize my APIs output data. But I am having problems with my date format. I am storing the date as an SQLAlchemy DateTime type, for example,...

stackoverflow.com

https://flask-restplus.readthedocs.io/en/stable/marshalling.html

 

Response marshalling — Flask-RESTPlus 0.13.0 documentation

Response marshalling Flask-RESTPlus provides an easy way to control what data you actually render in your response or expect as in input payload. With the fields module, you can use whatever objects (ORM models/custom classes/etc.) you want in your resourc

flask-restplus.readthedocs.io

 

반응형

'프로그래밍 > Python' 카테고리의 다른 글

[Python]sqlalchemy 사용법  (0) 2022.12.07
[PYTHON] 파이썬 함수 매개변수  (0) 2022.08.11
Single Linked list 구현  (0) 2018.03.22
창원시 버스 API 사용하기  (1) 2016.02.22
반응형

Python 2.7 Single Linked list 구현


참고자료 : starmooc.kr kaist 문일철 교수 데이터구조 및 분석 인강


class Node:

value = ''

nextnode = ''

binhead = False

bintail = False


def __init__(self, value='', nextnode='', binhead=False, bintail=False):

self.value = value

self.nextnode = nextnode

self.binhead = binhead

self.bintail = bintail

def getValue(self):

return self.value

def setValue(self, value=''):

self.value = value

def getNext(self):

return self.nextnode

def setNext(self, nextnode=''):

self.nextnode = nextnode

def isTail(self):

return self.bintail

def isHead(self):

return self.binhead




class SinglyLinkedlist:

nodehead = ''

nodetail = ''

size = 0


def __init__(self):

self.nodetail = Node(bintail = True)

self.nodehead = Node(binhead = True, nextnode = self.nodetail)

def insertAt(self, objInsert, idxInsert):

nodeNew = Node(value=objInser)

nodePrev = self.get(idxInsert - 1)

nodeNext = nodePrev.getNext()

nodePrev.setNext(nodeNew)

nodeNew.setNext(nodeNext)

self.size = self.size+1

def removeAt(self, idxRemove):

nodePrev = self.get(idxRemove - 1)

nodeRemove = nodePrev.getNext()

nodeNext = nodeRemove.getNext()

nodePrev.setNext(nodeNext)

self.size = self.size - 1

return nodeRemove.getValue()

def get(self, idxRetrieve):

nodeReturn = self.nodeHead

for itr in range(idxRetreve + 1):

nodeReturn = nodeReturn.getNext()

return nodeReturn

def printStatus(self):

nodeCurrent = self.nodehead

while nodeCurrent.getNext().isTail() == False:

nodeCurrent = nodeCurrent.getNext()

print nodeCurrent.getValue(),

print

def getSize(self)

return self.size


반응형

'프로그래밍 > Python' 카테고리의 다른 글

[Python]sqlalchemy 사용법  (0) 2022.12.07
[PYTHON] 파이썬 함수 매개변수  (0) 2022.08.11
[Python] flask_restful fields  (0) 2021.10.08
창원시 버스 API 사용하기  (1) 2016.02.22
반응형

class BUS():

        def __init__(self):

                self.key = "KQdls/1w4hLXiAkOO8N46/1rvqV26sMnIvRYj1cg75yCl5aR9yRRJtMkxeOJ8Zx2MlKIVajs4ZVJMrNEgnGOUA=="; # 창원시 버스 API홈페이지 샘플 key사용.

                self.url = "http://openapi.changwon.go.kr/rest/bis/"

# 문서로 저장된 기반정보 열기

                BusI2N = open("./howie/BusID-NM.txt","r") 

                BusN2I = open("./howie/BusNM-ID.txt","r")

                StatI2N = open("./howie/StationID-NM.txt","r")

                StatN2I = open("./howie/StationNM-ID.txt","r")


                self.BusI2N_dic = {}


                self.BusN2I_dic = {}


                self.StatI2N_dic = {}


                self.StatN2I_dic = {}




                for BIN in BusI2N:

                        tmp = BIN.split(':')

                        self.BusI2N_dic[tmp[0]] = tmp[1].replace('\n','')


                for BNI in BusN2I:

                        tmp = BNI.split(':')

                        self.BusN2I_dic[tmp[0]] = tmp[1].replace('\n','')


                for SIN in StatI2N:

                        tmp = SIN.split(':')

                        self.StatI2N_dic[tmp[0]] = tmp[1].replace('\n','')


                for SNI in StatN2I:

                        tmp = SNI.split(':')

                        self.StatN2I_dic[tmp[0]] = tmp[1].replace('\n','')



        def station(self,station):

                station = station.replace(" ","")

                if station not in self.StatN2I_dic.keys():

                        print "no station"

                        return


                station = self.StatN2I_dic[station]

                full = self.url + "BusArrives/?serviceKey=" + self.key + "&station="+station       # 정류장 도착정보 url

 data = requests.get(full).content                                                                        # requests라이브러리를 사용하여 xml 데이터 획득


                temp = minidom.parseString(data)                                                                     #  minidom라이브러리를 사용하여 스트링 파싱


                row = temp.getElementsByTagName('row') # row요소를 찾는다


                arrive_set = set()


                for el in row:

                        TMP = el.getElementsByTagName('ROUTE_ID')[0].childNodes[0].data        # row안 ROUTE_ID를 찾아 저장된 값을 얻는다.

                        if TMP in self.BusI2N_dic.keys():

                                arrive_set.add(self.BusI2N_dic[TMP])


                return arrive_set

반응형

'프로그래밍 > Python' 카테고리의 다른 글

[Python]sqlalchemy 사용법  (0) 2022.12.07
[PYTHON] 파이썬 함수 매개변수  (0) 2022.08.11
[Python] flask_restful fields  (0) 2021.10.08
Single Linked list 구현  (0) 2018.03.22

+ Recent posts