TinyDB
https://tinydb.readthedocs.io/en/latest/getting-started.html#installing-tinydb
- NoSql
- 문서형 데이터베이스
- 스키마 정의 없이 사용 가능 (NoSql과 RDB의 가장 큰 차이점)
- 설치 : pip install tinydb
설치 : pip install tinydb
pip install tinydb

버전 확인
import tinydb
tinydb.__version__

In [1]:
from tinydb import TinyDB, Query
db = TinyDB('./data/db.jason')
상대경로로 파일을 생성했습니다.
참고) 아래 두 경로는 같은 나 자신 을 가리키는 것.
db = TinyDB('./db.jason')
db = TinyDB('db.jason')

In [2]:
# insert
db.insert({'type': 'apple', 'count': 7})
db.insert({'type': 'peach', 'count': 3})
Out[2]:
4
In [3]:
# select all
db.all()
Out[3]:
[{'type': 'apple', 'count': 7},
{'type': 'peach', 'count': 3},
{'type': 'apple', 'count': 7},
{'type': 'peach', 'count': 3}]
리스트의 다큐먼트 객체..


for t in total :
print(t['type'])

datas = []
for t in total :
datas.append(dict(t))
리스트의 딕셔너리 형태

In [8]:
# iter
for item in db:
item
datas = [dict(item) for item in db]
datas
Out[8]:
[{'type': 'apple', 'count': 7},
{'type': 'peach', 'count': 3},
{'type': 'apple', 'count': 7},
{'type': 'peach', 'count': 3}]
In [7]:
# search
Fruit = Query()
search = db.search(Fruit.type == 'peach')
search
쿼리 객체를 만들어서
칼럼을 키값 처럼 사용.
Out[7]:
[{'type': 'peach', 'count': 3}, {'type': 'peach', 'count': 3}]

In [9]:
db.remove(Fruit.count < 5)
db.all()
Out[9]:
[{'type': 'apple', 'count': 7}, {'type': 'apple', 'count': 7}]
In [12]:
# all remove
db.truncate()
db.all()
Out[12]:
[]
In [15]:
# create table
table = db.table('table_name')
table.insert({'value': True})
table.all()
Out[15]:
[{'value': True}]
In [16]:
# drop table
db.drop_table('table_name')
In [22]:
table.all()
Out[22]:
[]
In [ ]:
로또 번호 정보 수집 및 저장
- import requests

#json 데이터
{
"totSellamnt":107150089000,
"returnValue":"success",
"drwNoDate":"2022-09-24",
"firstWinamnt":2868856209,
"drwtNo6":40,
"drwtNo4":33,
"firstPrzwnerCo":9,
"drwtNo5":38,
"bnusNo":11,
"firstAccumamnt":25819705881,
"drwNo":1034,
"drwtNo2":31,
"drwtNo3":32,
"drwtNo1":26
}
In [18]:
# 로또 번호 가져오기
import requests
URL_GetLottoNumber = "https://www.dhlottery.co.kr/common.do?method=getLottoNumber&drwNo=" # 현재 동행로또 주소
drwNo = input("당첨번호를 확인할 회차 번호를 입력해주세요 : ")
resp = requests.get(URL_GetLottoNumber + drwNo)
jsResult = resp.json()
if jsResult["returnValue"] == "success":
print(jsResult)
else:
print("존재하지 않는 회차 번호입니다. (입력됨 : %s)" % (drwNo))
for i in range(1,7):
lNo = 'drwtNo'+str(i)
print(jsResult[lNo])
당첨번호를 확인할 회차 번호를 입력해주세요 : 936
{'totSellamnt': 92246146000, 'returnValue': 'success', 'drwNoDate': '2020-11-07', 'firstWinamnt': 1492069179, 'drwtNo6': 29, 'drwtNo4': 17, 'firstPrzwnerCo': 14, 'drwtNo5': 18, 'bnusNo': 43, 'firstAccumamnt': 20888968506, 'drwNo': 936, 'drwtNo2': 11, 'drwtNo3': 13, 'drwtNo1': 7}
7
11
13
17
18
29
In [24]:
# 로또 번호 정보 가져오기
import requests
from tinydb import TinyDB, Query
def get_lotto_json(drwNo):
URL_GetLottoNumber = "https://www.dhlottery.co.kr/common.do?method=getLottoNumber&drwNo=" # 현재 동행로또 주소
resp = requests.get(URL_GetLottoNumber + drwNo)
jsResult = resp.json()
if jsResult["returnValue"] == "success":
return jsResult
else:
return None
In [25]:
# 정보 저장 테이블 생성
db = TinyDB('db.json')
table = db.table('lotto_info')
In [27]:
# 936회 정보 저장
lotto_info = get_lotto_json('936')
if lotto_info:
table.insert(lotto_info)
In [28]:
table.all()
Out[28]:
[{'totSellamnt': 92246146000,
'returnValue': 'success',
'drwNoDate': '2020-11-07',
'firstWinamnt': 1492069179,
'drwtNo6': 29,
'drwtNo4': 17,
'firstPrzwnerCo': 14,
'drwtNo5': 18,
'bnusNo': 43,
'firstAccumamnt': 20888968506,
'drwNo': 936,
'drwtNo2': 11,
'drwtNo3': 13,
'drwtNo1': 7}]
#로또 번호 가져오기
import requests
URL = "https://www.dhlottery.co.kr/common.do?method=getLottoNumber&drwNo=1034"
resp = requests.get(URL)
if resp.status_code == 200:
data = resp.json() # 요청한 데이터를 자신을 딕셔너리로 바꿔준다.
else :
print('error!!')
for i in range(1,7):
no = 'drwtNo' + str(i)
print(no)
for i in range(1,7):
no = 'drwtNo' + str(i)
print(data[no])
lottos = []
for i in range(1,7):
no = 'drwtNo' + str(i)
lottos.append(data[no])
lottos
'프로그래밍 언어 > Python' 카테고리의 다른 글
Flask - 운영 배포 / 플라스크로 파이썬 코드 실행(vs코드) (0) | 2022.09.29 |
---|---|
Python – Flask (0) | 2022.09.28 |
Python – Pymssql MSSQL 활용 (0) | 2022.09.27 |
실전 예제로 배우는 파이썬 프로그래밍 - 4장 연습문제 풀기 (0) | 2022.09.26 |
Python - Pandas(csv, excel 파일 처리) (0) | 2022.09.26 |