底下說明在 d:\server\pyweb下產生一個網頁,用來顯示歷年來的台灣股市資料。開啟的網頁為
http://localhost:7000/twstock
新增 templates
templates是置放 html 文件的地方,請先在d:\server\pyweb 下新增 templates目錄,然後 settings.py 新增如下藍色的地方
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates').replace('\\','/')],
'APP_DIRS': True,
'OPTIONS': {
新增app
每一個網頁都是一個 app,每個 app可能由好幾個 .py檔所組成,這個觀念一定要記住。請進入 d:\server\pyweb下,執行如下指令
python manager.py startapp twstock
todo
設定連結
urls.py 修改如下
import twstock.views as twstock
urlpatterns = [
path('admin/', admin.site.urls),
path("", index.html),
path("twstock/", twstock.html),
]
todo
views.py
twstock/views.py 代碼如下
todo
import plotly
from django.shortcuts import render
import mysql.connector as mysql
import plotly.graph_objects as go
import numpy as np
def html(request):
conn=mysql.connect(host="ip"
,user="account",
password="password",
database="db")
cursor=conn.cursor()
cursor.execute("select * from 台灣股市 order by 日期")
rs=cursor.fetchall()
point=[r[5] for r in rs]
dates=[r[1] for r in rs]
x=list(range(len(rs)))
f=np.poly1d(np.polyfit(x, point, 10))
reg=f(x)
fig = go.Figure()
fig.add_trace(
go.Scatter(
x=dates,
y=point,
mode='lines+markers',
name='大盤指數',
line=dict(color='royalblue', width=2)
)
)
fig.add_trace(
go.Scatter(
x=dates,
y=reg,
mode='lines',
name='日K線',
line=dict(color='orange', width=2))
)
fig.update_layout(
dragmode="pan",
title_text="台灣股市分析",
xaxis=go.layout.XAxis(
rangeselector=dict(
buttons=[
dict(count=1, label="1 month", step="month", stepmode="backward"),
dict(count=6, label="6 month", step="month", stepmode="backward"),
dict(count=1, label="1 year", step="year", stepmode="backward"),
dict(count=1, label="1 day", step="day", stepmode="todate"),
dict(step="all")
]
),
rangeslider=dict(visible=True),
type="date"
),
yaxis=dict(fixedrange=False)
)
plotly.offline.plot(fig, filename="c:/server/pyweb/templates/stock.html", auto_open=False)
return render(request, 'stock.html')
