关键词
Django Python
GitHub
创建project
Django的文档非常的详细,参考这个就可以
Django创建project
这里咱们创建一个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前。
然后还有一些其他的设置。
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',
)
配置路由
设置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')),
]
实现stockserver
其实Django最好是用model来对应数据库,但是考虑到这个项目只需要拿股票日K数据和指标数据,直接pd.read_sql()更方便,所以就不设置model了
- 获取股票指标
输入是前端传过来的request,需要传递specname,order和abs,这里我们设置一些默认值。
这里specname就是第二篇里创建数据库的stock_spec表的那一些列名,像贝塔系数这个正和负都表示跟大盘偏离比较大,所以需要加abs,大多数参数不需要加abs。
limit 0,50 就是取最大或最小的50只股票, 然后用DataFrame.to_json方法生成json格式返回前端。注意to_json方法里的orient参数,根据自己的需求来设置。
# 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 应该就能看到返回的json数据。