django框架运用--------股票系统
这个系统是我和几个队友两天做出来的,可能功能方面没有实现太多,但足够体现django框架的运用,我是主要负责后端,所以这里只讲一下后端的代码。
创建django框架后,里面会有一堆文件(之前我也写过了每一个文件是干嘛的了,这里也不多说https://blog.csdn.net/FOKJECKT/article/details/96906103)
接着创建股票系统所要用到的app,这里创建了5个app,不过只有两个有对应功能的实现,其他的还没做好。
下面开始介绍app中对应的功能
1、stock本身
- urls.py(主路由)
from django.conf.urls import url,include
from django.contrib import admin
from django.views.generic import TemplateView
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'getdata/',include('stocks.urls')),
url(r'userinfo',include('userinfo.urls')),
url(r'stocks',include('stocks.urls')),
url(r'deal',include('deal.urls')),
url(r'front_register', TemplateView.as_view(template_name='front_register.html'), name='front_register'),
url(r'front_login', TemplateView.as_view(template_name='front_login.html'), name='front_login'),
url(r'index', TemplateView.as_view(template_name='index.html'), name='index'),
]
通过正则匹配到相应的url上
2、stocks(股票)
from django.db import models
# Create your models here.
AREA_CHOICES=(
(0,'医药'),
(1,'房地产'),
(2,'游戏'),
(3,'教育'),
(4,'旅游'),
(5,'餐饮'),
(6,'金融'),
)
class Stock(models.Model):
sto_name=models.CharField(verbose_name="股票名称",max_length=20,null=True)
sto_No=models.CharField(verbose_name="股票编码",max_length=30,null=True)
sto_company=models.CharField(verbose_name="公司名称",max_length=30,null=True)
sto_update=models.DateField(verbose_name="上市日期")
sto_area=models.IntegerField(verbose_name="领域",choices=AREA_CHOICES,default=0)
def __str__(self):
return self.sto_name
数据库中股票信息表的创建
from django.contrib import admin
from.models import Stock
# Register your models here.
class StockAdmin(admin.ModelAdmin):
list_display = ("sto_name","sto_No","sto_company",)
search_fields = ("sto_name",)
admin.site.register(Stock,StockAdmin)
表创建后要进行注册
templates文件中的html这里先不写,代码在文章后会发出来。
from django.conf.urls import url
from .views import SqlTest,_GetKlines,GetAllStockView,GetKlines
urlpatterns = [
url(r'klines/',GetKlines,name='klines'), #通过前端定义的url找到GetKlines方法
url(r"sqltest",SqlTest,name="sql_test"),
url(r'find/',_GetKlines,name='find'),
url(r'allstock/', GetAllStockView, name='allstock'),
]
通过前端定义的url找到视图中对应的方法对数据进行处理
from django.shortcuts import render
from django.http import HttpResponse
import json
from .models import Stock
from userinfo.models import UserInfo
from .stockdata import GetStockData
import datetime
# Create your views here.
def SqlTest(request):
data="python"
username=request.POST.get('username')
realname = request.POST.get('realname')
user_info = UserInfo.objects.get(realname=realname)
print(user_info)
return HttpResponse(json.dumps({"result":True,"data":data,"error":""}))
def _GetKlines(request):
code=request.GET.get('code') #得到前端输入的数值
start=request.GET.get('start')
end=request.GET.get('end')
print(end)
klines_data=GetStockData().getkdata(code,start,end) #通过调用事先写好的方法进行数据
name = GetStockData().getStockName(code)
return HttpResponse(json.dumps({"result":True,"data":klines_data,"ts_name":name,"error":""}))
def GetAllStockView(request):
stock_data = GetStockData().getAllData()[0:10] #筛选前10只股票
return HttpResponse(json.dumps({"result": True, "data": stock_data, "error": ""}))
def GetKlines(request):
print(request.user)
ts_code = request.GET.get("ts_code")
code = ts_code
start = '20190101'
end = '20190630'
klines_data = GetStockData().getkdata(code, start, end)
return HttpResponse(json.dumps({"result":True,"data":klines_data,"error":""}))
import tushare as ts
class GetStockData(object):
def getkdata(self,code,start,end):
pro = ts.pro_api('56103e300f9c9fbbd93f71272c14da043aa6e0f44825f3982b51a138') #继承tushare的API接口,以便获取数据
df = pro.daily(ts_code=code, start_date=start, end_date=end)
result = []
for index,idx in enumerate(df.index):
re = []
re.append(df.ix[idx]['trade_date']) #获取对应每点的相关数据
re.append(df.ix[idx]['open'])
re.append(df.ix[idx]['close'])
re.append(df.ix[idx]['low'])
re.append(df.ix[idx]['high'])
result.append(re)
# print(result)
return result
def getAllData(self):
pro = ts.pro_api('56103e300f9c9fbbd93f71272c14da043aa6e0f44825f3982b51a138')
df = pro.stock_basic(exchange='', list_status='L', fields='ts_code,symbol,name,area,industry,list_date')
result = []
for index, idx in enumerate(df.index):
item = {}
item['ts_code'] = df.ix[idx]['ts_code']
item['name'] = df.ix[idx]['name']
item['area'] = df.ix[idx]['area']
item['industry'] = df.ix[idx]['industry']
item['list_date'] = df.ix[idx]['list_date']
result.append(item)
return result
def getStockName(self,code):
pro = ts.pro_api('56103e300f9c9fbbd93f71272c14da043aa6e0f44825f3982b51a138')
df = pro.namechange(ts_code=code, fields='ts_code,name,start_date,end_date,change_reason')
for index,idx in enumerate(df.index):
end = df.ix[idx]['end_date']
if end == None:
name = df.ix[idx]['name']
return name
if __name__ == "__main__":
# print(GetStockData().getStockName('000002.SZ'))
print(GetStockData().getAllData())
视图中通过stockdata中的方法得到股票的数据,这里的数据是通过继承tushare提供的接口获取股票数据,接口API要自己去创,如果我这边页面刷新了,这个API就不能用了
3、userinfo(用户)
from django.db import models
from django.contrib.auth.models import AbstractUser
from stocks.models import Stock
BANKCARD_CHOICES=(
(0,'未绑定'),
(1,'ICBC'),
(2,'CBC'),
(3,'ABC'),
(4,'BC'),
(5,'CCB'),
)
BANK_STATUS_CHOICES=(
(0,'未激活'),
(1,'已激活'),
(2,'激活失败'),
(3,'冻结')
)
class UserInfo(AbstractUser): #通过models在数据库中创建表及字段
realname =models.CharField(verbose_name="真实姓名",max_length=100,null=True)
email=models.EmailField(verbose_name="邮箱")
phone =models.CharField(verbose_name="电话",max_length=20,null=True)
identify=models.CharField(verbose_name="身份证",max_length=50,null=True)
def __str__(self):
return self.username #返回的是在ORM上想要显示的字段
class Meta:
verbose_name_plural='UserInfo'
class BankCard(models.Model):
bank_name=models.IntegerField(verbose_name="银行名称",choices=BANKCARD_CHOICES,default=0)
bank_no=models.CharField(verbose_name="银行卡号",max_length=30,null=True)
bank_pwd=models.CharField(verbose_name="交易密码",max_length=200,null=True)
bank_status=models.IntegerField(verbose_name="状态",choices=BANKCARD_CHOICES,default=0)
user=models.ForeignKey(UserInfo)
def __str__(self):
return self.user.username
class Wallet(models.Model):
money=models.DecimalField(verbose_name='账户余额',max_digits=8,decimal_places=2)
frozen_money=models.DecimalField(verbose_name='冻结金额',max_digits=8,decimal_places=2)
pay_pwd=models.CharField(verbose_name='交易密码',max_length=200,null=True)
user=models.OneToOneField(UserInfo)
def __str__(self):
return self.user.username
class HoldStock(models.Model):
stock=models.OneToOneField(Stock)
hold_amount=models.IntegerField(verbose_name="持有数量",default=0)
frozen_stock=models.IntegerField(verbose_name="冻结数量",default=0)
user = models.ForeignKey(UserInfo)
def __str__(self):
return self.user.username
用户对应数据库表的创建
admin这里省略,更上面那个app类似
from django.conf.urls import url
from .views import SelfReisterView
from .views import selfLoginview
urlpatterns=[
url(r'myregister',SelfReisterView,name='myregister'),
url(r'mylogin', selfLoginview, name='mylogin'), #mylogin是前端html写的一个url,通过这个url进行路由匹配,接收前端请求,通过selfLoginview方法进行数据处理
]
总体代码就是这样了,很多功能也还没完善,但足够体现MVT的使用及django的使用,这个项目本身难度不高,就是书写代码的时候如果不规范就会陷入找bug阶段,这个项目也告诉我一点,代码书写规范很重要,该tab就tab,不然一个个括号对不齐找死人。控制台是个好东西,要好好利用进行调试。
这个是整个项目的代码,需要的看一下
链接:https://pan.baidu.com/s/1Oq7_MHbOJ-7NkN0obQW-jQ
提取码:6lkv
复制这段内容后打开百度网盘手机App,操作更方便哦