關(guān)鍵詞
Django Python
GitHub
創(chuàng)建project
Django的文檔非常的詳細(xì)辩棒,參考這個就可以
Django創(chuàng)建project
這里咱們創(chuàng)建一個app叫stockserver
django-admin startproject mysite
python manage.py startapp stockserver
在mysite/settings.py的INSTALLED_APPS加上stockserver
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'stockserver'
]
配置跨域中間件
因為我們最后用Vue做前端颜阐,需要解決跨域的問題,需要安裝django-cors-headers
pip install django-cors-headers
在mysite/settings.py的MIDDLEWARE加上corsheaders鸯乃,注意順序乎赴,越靠前越好练般,尤其是在Django的CommonMiddleware前疲眷。
然后還有一些其他的設(shè)置齿风。
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = (
'*'
)
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
)
CORS_ALLOW_HEADERS = (
'XMLHttpRequest',
'X_FILENAME',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
'Pragma',
)
配置路由
設(shè)置mysite/urls.py, 將stockserver的urls加入project的urls
from django.contrib import admin
from django.urls import path
from django.conf.urls import include
urlpatterns = [
path('admin/', admin.site.urls),
path('stockserver/', include('stockserver.urls')),
]
實現(xiàn)stockserver
其實Django最好是用model來對應(yīng)數(shù)據(jù)庫药薯,但是考慮到這個項目只需要拿股票日K數(shù)據(jù)和指標(biāo)數(shù)據(jù),直接pd.read_sql()更方便聂宾,所以就不設(shè)置model了
- 獲取股票指標(biāo)
輸入是前端傳過來的request果善,需要傳遞specname,order和abs系谐,這里我們設(shè)置一些默認(rèn)值巾陕。
這里specname就是第二篇里創(chuàng)建數(shù)據(jù)庫的stock_spec表的那一些列名,像貝塔系數(shù)這個正和負(fù)都表示跟大盤偏離比較大纪他,所以需要加abs鄙煤,大多數(shù)參數(shù)不需要加abs。
limit 0,50 就是取最大或最小的50只股票, 然后用DataFrame.to_json方法生成json格式返回前端茶袒。注意to_json方法里的orient參數(shù)梯刚,根據(jù)自己的需求來設(shè)置。
# stockserver/views.py
def spec(request):
specname = request.GET.get('specname', 'amplitude_10')
order = request.GET.get('order', 'desc')
isAbs = request.GET.get('abs', 'false')
orderbyvalue = specname
if isAbs == 'true':
orderbyvalue = "abs(" + specname + ")"
print(specname, order, isAbs, orderbyvalue)
cx = sqlite3.connect(r'D:\codes\python\stock\mystock.db')
sql_cmd = "SELECT * FROM stock_spec where date=(select max(date) from stock_spec) and " + specname + " != 'NaN' order by " + orderbyvalue + " " + order + " limit 0,50"
result = pd.read_sql(sql=sql_cmd, con=cx)
df_json = result.to_json(orient = 'table', force_ascii = False)
data = json.loads(df_json)
return JsonResponse(data, safe=False)
- 獲取股票日k
# stockserver/views.py
def dayk(request):
codename = request.GET.get('code', 'sh.000001')
order = 'desc'
print(codename, order)
cx = sqlite3.connect(r'D:\codes\python\stock\mystock.db')
sql_cmd = "SELECT * FROM stock_day_k where code='" + codename +"' order by date desc limit 0,365"
result = pd.read_sql(sql=sql_cmd, con=cx)
df_json = result.to_json(orient = 'table', force_ascii = False)
data = json.loads(df_json)
return JsonResponse(data, safe=False)
- 配置路由
#stockserver/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('spec/', views.spec),
path('dayk/', views.dayk),
]
運行
python manage.py runserver
然后在瀏覽器輸入 127.0.0.1:8000/stockserver/spec 應(yīng)該就能看到返回的json數(shù)據(jù)薪寓。