[자산관리 day-4.2] 한국거래소(KRX) Open API Django에 셋팅하기(Django) 1
출처: https://jsistory.tistory.com/50 [쉰몬의 IT 정리 노트:티스토리]
에 이어서 Django에 적용시키위해 해당 인증키를 적용시켜야된다. 지금은 발급이 되었지만 그전에는 셈플 인증키를 가지고 진행했기 때문에 해당 블로그에는 셈플 인증키로 테스트 한 것을 공유한다.
현재 내가 만든 Django 의 프로젝트 구조는 이렇다.
AssetsMgrToyProjectInternal/
├── manage.py
├── AssetsMgrToyProjectInternal/
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
├── AsStock/
│ ├── __init__.py
│ ├── views.py
│ ├── urls.py
│ ├── templates/
│ │ └── AsStock/
│ │ └── stock_volume.html
└── db.sqlite3
현재 프로젝트 : AssetsMgrToyProjectInternal
main이되는 프로젝트 : ├── AssetsMgrToyProjectInternal/
main이되는 프로젝트의 주요 기능 :
- settings.py : App에 필요할 기능 구현
- urls.py : 각 Django에 사용할 App 경로설정
- requirements.txt : 의존성을 위해 나중에 프로젝트에 설치될 프로그램
각 자산관리에 필요할 프로젝트에 필요기능
- AsStock/ : 자산관리 프로젝트에 필요한 것 중 주식 관련해서 사용할 App 명
- ├── AsStock/ │ ├── views.py : view KRX open API 관련 view.py 구현
- ├── AsStock/ │ ├── urls.py : view 에서 호출될 관련 구현
- ├── AsStock/ │ ├──models.py : KRX open API 에서 받은 공공자료를 DB화 시키기 위해 가져옴
- │ ├── templates/ │ │ └── AsStock/ : Views.py 받을 AsStock 템플릿 자료 모음
※ ├── AsStock/ │ ├── views.py KRX open api 코드
from django.shortcuts import render
from django.http import JsonResponse
import requests
#KRX open api url
def get_stk_kdx_volume():
basDd="20241230"
url = "http://data-dbg.krx.co.kr/svc/sample/apis/idx/kospi_dd_trd?"+f"basDd={ basDd }"
api_key ="74D1B99DFBF345BBA3FB4476510A4BED4C78D13A"
params = {
"Authorization": f"Bearer {api_key}"
}
# get request json data
response = requests.get(url, params=params)
print(response.status_code);
# Event processing related to authentication key connection
if response.status_code == 401:
return JsonResponse({"error" : "인증 오류 API키를 확인해주세요"}, status=401)
elif response.status_code == 200:
data = response.json()
return data
else:
return {"error" : "Failed to get data"}
# stock KRX return view
def stk_kdx_volume(request):
volumn_data = get_stk_kdx_volume()
return JsonResponse(volumn_data)
# View that renders the stock trading volume page
def stock_volume_page(request):
return render(request,'AsStock/stock_volume.html')
※ ├── AsStock/ │ ├──urls.py 코드
from django.urls import path
from . import views
urlpatterns = [
path('stk-kdx-volume/',views.stk_kdx_volume,name='stk_kdx_volume'), # kdx open api url
path('stock-volume-page/',views.stock_volume_page,name='stock_volume_page'), # stock trading volume page
]
※ ├── AsStock/ │ ├── templates/ │ │ └── AsStock/ 관련 템플릿 코드
여기에다가 해당 json으로 받은 자료를 리턴시켜준다.
<!DOCTYPE html>
<html leng="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Stock Volume</title>
</head>
<body>
<h1> trading volume 여긴가?</h1>
<div id="stock-volume">Loading...</div>
<script>
fetch('/asstock/stk-kdx-volume/')
.then(response => response.json())
.then(data => {
document.getElementById('stock-volume').innerText = JSON.stringify(data,null,2);
});
</script>
</body>
</html>
※ ├── AssetsMgrToyProjectInternal/ │ ├──urls.py
여기는 메인 url AsStock App 경로 설정
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path("admin/", admin.site.urls),
path('asstock/', include('AsStock.urls'))
]
※ ├── AssetsMgrToyProjectInternal/ │ ├──settings.py
AsStock App 추가
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"AsStock"
]
※ 테스트 결과이다.
http://127.0.0.1:8000/asstock/stock-volume-page/ templates 경로에 설정한 open api 가 잘 테스트 되는걸 확인 할 수 있다.
이제 Django 로 인증키 API 작업을 완료 했으니 본격적으로 Model에 들어갈 DB 설계 작업을 시작해야지.
'IT > toy project' 카테고리의 다른 글
[자산관리 day-4.4] Docker에 있는 PostgreSQL을 Django (맥, PyCharm)에서 연결하는 방법 (1) | 2025.02.02 |
---|---|
[자산관리 day-4.2] 한국거래소(KRX) Open API Django에 셋팅하기(Django) 1 (0) | 2025.01.01 |
[자산관리 day-4.1.1] Django로 주식 관련 Investing.com의 API 설정(Chat gpt) (0) | 2024.12.30 |
[자산관리 day-4.1] 주식(Stock)관련 Chat gpt로 알아보기 (0) | 2024.12.30 |
[자산관리 day-2.5] 마인드맵 그리기 2 (1) | 2024.10.13 |