LoginSignup
0
1

More than 3 years have passed since last update.

Djangoでbitflyerの収支管理アプリを作ってみる(04_02.ダッシュボード画面を作成する。)

Last updated at Posted at 2019-12-31

前の。
Djangoでbitflyerの収支管理アプリを作ってみる(04_01.ダッシュボード画面を作成する。)
https://qiita.com/redmeteor777/items/64f2288457c850666221

views.pyの編集。

1.bitflyerのAPIを叩いて必要なデータを取得します。
2.取得したデータをHTMLに埋め込めるように成型します。
 forループで1行ずつ取り出し、HTMLタグを埋め込んでいきます。
3.出来上がった文字列をparamsにdict形式で格納し、引数として渡します。

いきなりコードが長くなりましたが、やってることはそんなに複雑じゃないので…

あ、見ての通りAPIキーはダミーです。
まだモデル(データベース)を作成していない為、コード内に直接埋め込んでいます。
試してみたい方は、自力でAPIキーとシークレットを発行してくださいね。

views.py
from django.shortcuts import render
from django.http import HttpResponse
from .forms import LoginForm
from .forms import RegistrationForm

import ccxt

def login(request):
    params = {
        'title': 'Login_Form',
        'message': 'input your e-mail and pass.',
        'form': LoginForm()
    }

    if (request.method == 'POST'):
        params['message'] = \
            'メールアドレス:' + request.POST['user_id'] + \
            '<br>パスワード:' + request.POST['password']
        params['form'] = LoginForm(request.POST)

    return render(request, 'bfmonitor/login.html', params)

def registration(request):
    params = {
        'title': 'Registration_Form',
        'message': 'input your e-mail, pass, API and Secret.',
        'form': RegistrationForm()
    }

    if (request.method == 'POST'):
        params['message'] = \
            'メールアドレス:' + request.POST['user_id'] + \
            '<br>パスワード:' + request.POST['password'] + \
            '<br>API_Key:' + request.POST['api_key'] + \
            '<br>API_Secret:' + request.POST['api_secret']
        params['form'] = RegistrationForm(request.POST)

    return render(request, 'bfmonitor/registration.html', params)

def dashboard(request):

    bitflyer = ccxt.bitflyer()
    bitflyer.apiKey = 'xxxxxxxxxxxxxxxxxxxxxxxxx'
    bitflyer.secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

    """
    累計収支の作成
    """
    # 累計収支の計算
    collateral = bitflyer.private_get_getcollateralhistory(params={"count":10000})

    # 累計収支計算用の変数
    collateral_result = 0

    # HTMLに出力する文字列を作成
    collateral_text = "累計収支<br><table>"

    # 取引に関わる資産変動のみ加算(入出金はカウントしない)
    for i in collateral:
        if i['reason_code'] == 'CLEARING_COLL':
            collateral_result = collateral_result + i['change']

    collateral_text = collateral_text + "<tr><td>" + str(collateral_result) + "</td></tr></table>"

    """
    資産情報の作成
    """
    # 資産情報の取得
    balance = bitflyer.private_get_getbalance()

    # HTMLに出力する文字列を作成
    balance_text = "資産情報<br><table>"

    for i in balance:
        balance_text = balance_text + "<tr><td>" + i['currency_code'] + "</td><td>" + str(i['amount']) + "</td></tr>"

    balance_text = balance_text + "</table>"

    """
    取引履歴の作成
    """
    # 取引履歴の取得
    history = bitflyer.private_get_getbalancehistory(params={"count":10000})

    # HTMLに出力する文字列を作成
    history_text = "取引履歴<br><table>"
    for i in range(len(history)):
        if history[i]['trade_type'] == "BUY" or history[i]['trade_type'] == "SELL":
            history_text = history_text + "<tr><td>" + history[i]['trade_date'] + \
                "</td><td>" + history[i]['trade_type'] +\
                "</td><td>" + str(history[i]['price']) +\
                "</td><td>" + str(history[i]['amount']) + "</td></tr>"
        elif history[i]['trade_type'] == "FEE":
            history_text = history_text + "<tr><td>" + history[i]['trade_date'] + \
                "</td><td>" + history[i]['trade_type'] + "</td><td></td><td></td></tr>"

    history_text = history_text + "</table>"



    params = {
        'title': 'Dashboard',
        'message': 'This is dashboard.',
        'balance': balance_text,
        'collateral': collateral_text,
        'history': history_text
    }

    return render(request, 'bfmonitor/dashboard.html', params)

一番↓あたりにある、この部分ですね。

    params = {
        'title': 'Dashboard',
        'message': 'This is dashboard.',
        'balance': balance_text,
        'collateral': collateral_text,
        'history': history_text
    }

    return render(request, 'bfmonitor/dashboard.html', params)

こうやって渡してやることで、HTML内でparamsがあっちこっちに展開されます。
展開した変数を受け取れるように、dashboard.htmlも編集します。

dashboard.htmlの編集

dashboard.html
{% load static %}
<!doctype html>
<html lang="ja">
<head>
    <meta charset="uth-8">
    <title>{{title}}</title>
    <link rel="stylesheet" type="text/css"
        href="{% static 'login/css/style.css' %}" />
</head>
<body>
    <h1>{{title}}</h1>
    <p>{{message|safe}}</p>
    <div class="parent">
    <div class="collateral">{{ collateral | safe }}</div>
    <div class="balance">{{ balance | safe }}</div>
    <div class="history">{{ history | safe }}</div>
    </div>

</body>
</html>
<div class="collateral">{{ collateral | safe }}</div>

ってやってやると、paramsに格納されているcollateralの値が読み込まれます。
[| safe]はエスケープ処理?って言うんでしたっけ?
[| safe]を付けることで、タグに使う不等号とかをそのまま出力してくれます。

同じくbalance、historyを受け取れるように記述することで、必要情報がそれっぽくテーブルに展開されて表示されます。

前回作ったやつだとちょっと文字列埋め込むのにサイズ不足なので、CSSを編集して対応しました。

style.cssの編集。

style.css
body {
    color:gray;
    font-size:16pt;
}

h1 {
    color:red;
    opacity:0.2;
    font-size:60pt;
    margin-top:-20px;
    margin-bottom:0px;
    text-align:right;
}
p {
    margin: 10px;
}
.parent {
    color:black;
    font-size:8pt;
    position: relative;
    width: 90%;
}
.parent > div {
    width: 50%;
}
.parent > div:not(.history) {
    height: 20em;
}
.history {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
}
.collateral { background-color: #e89; }
.balance { background-color: #8e9; }
.history { background-color: red; }

ではサーバーを起動して確認してみましょう。

>python manage.py runserver

ダッシュボード画面にアクセスして表示を確認します。

http://localhost:8000/dashboard/

左に色違いで二段、右に縦ぶちぬきの赤塗り枠、それぞれの中に情報が出ればOKです。
次回は画面遷移やモデルの作成について勉強していきます。

が、その前に一度ディレクトリ構成などを再確認します。
あっちこっちでファイル作ったりディレクトリ追加したりで複雑になってますからね。

いやー、難産だった…(フラグ完全回収)

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1