上次我们讲了一个很简单的python程序,这次我们复杂一点,通过python操作更加复杂点并配合具有更多算法功能的sql语句。

  首先,我们这个程序的功能为,通过python操作sql获取数据,并通过关联算法在服务器端对数据进行处理和筛选。然后返回前端,前端我们再用js通过ajax操作获取数据,并在前端再对数据进行二次处理。首先上一张效果图吧:

  

这里顺带用了日期插件跟分页插件。好了,废话不多说,还是直接上代码:

# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 NetEase SDC
#
# Author: LIJIAN <gzlijian@corp.netease.com>
# Version: 1.0 2014-03-18
from django.shortcuts import render_to_response
from authority.sys.sys_views import get_menu_name
from base.utils.request_utils import get_str, get_int
from base.utils import mysql_utils_psafe
from django.http import HttpResponse
from base.data.report_utils import get_menu_valid_time
import datetimedef query_libao_inter(request):u""" """para = {}game_id = get_int(request,'game_id',None)para['game_id'] = game_idfrom base.utils.data_utils import get_dimen_infopara['dimen_info'] = get_dimen_info([143])[143]para['valid_time'] = {'start':'20140430','end':str(datetime.datetime.now())[0:10].replace('-','')}template_name = '/specific/libao/query_libao.html'return render_to_response(template_name, para)def query_libao_use_data(request):game_id = get_int(request,'game_id',None)sn = get_str(request,'sn','')date_s = get_str(request,'date_s','')date_e = get_str(request,'date_e','')os = get_int(request,'os',None)page_conditions_str = get_str(request, 'page_conditions','')total_sql = """select  count(*)from report_ods.wscs_libao a left join info.game_host b on a.hostnum=b.id and b.game_id=%s """%game_idsql = """select  user_id,sn,registertime,if(b.host_name,b.host_name,hostnum),if(is_trade=1,'是','否'),if(is_valid_user=1,'是','否'),total_trade_cashfrom report_ods.wscs_libao a left join info.game_host b on a.hostnum=b.id and b.game_id=%s """%game_idwhere_sql = []if sn:where_sql.append("sn like '%%%s%%'"%sn)if date_s and date_e:where_sql.append("registertime between '%s-%s-%s 00:00:00' and '%s-%s-%s 23:59:59'"%(date_s[0:4],date_s[4:6],date_s[6:8],date_e[0:4],date_e[4:6],date_e[6:8]))if os:where_sql.append(' os_name=%s'%os)if where_sql:sql += 'where '+' and '.join(where_sql)total_sql += 'where '+' and '.join(where_sql)if page_conditions_str:import jsonpage_conditions = json.loads(page_conditions_str)sql += ' limit %d,%d'%((int(page_conditions['cursor'])-1)*int(page_conditions['size']),page_conditions['size'])print sqldata = mysql_utils_psafe.query_listlist(sql,value_decorator_list=str)total_num = mysql_utils_psafe.query_one(total_sql)return {'data':data,'total_num':total_num}def file_os(request):data = query_libao_use_data(request)['data']response = Nonetry:content=["\xEF\xBB\xBF",'用户ID, 礼包码, 使用时间, 服务器, 是否新增, 是否充值, 充值额, \n']for line in data:content.append(','.join([str(x) for x in line])+'\n')print data        response = HttpResponse(content, mimetype='application/octet-stream')response['Content-Disposition'] = 'attachment; filename=%s'%'礼包码.csv'except Exception,ex:print_error()finally:return responsejs代码:
require(['jquery', 'pt', 'bootstrap','table', 'datepicker'], function() {var $ = require('jquery');var pt = require('pt');var table = require('table');var datepicker = require('datepicker');var day_s=$ns.report_valid_times['start'],day_e=$ns.report_valid_times['end'];$ns.settings = {"size":15,"cursor":1,"sortingStatus":[]};$(document).ready(function() {// 初始化// 数据条件$ns.data_conditions = {};// 分页条件$ns.table_conditions = {};$ns.player_list = [];//生成日期插件$ns.start_dp = new datepicker.Datepicker({datepicker : {renderTo : 'query_date',onpick : function(type, start, end) {console.log(type, start, end, this);day_s=start;day_e=end;}},datetype : {onpick : function(type) {}},date : {day : {start : day_s,end : day_e,initial:[-60]}}});$("#search_btn").click();});//查询事件$("#search_btn").click(function(){query_libao_use_data();});function query_libao_use_data(){var sn = $("#sn").val();var os = $('#os').val();var para = new Object();var QUERY_URL = "/product_center/ajax_query/"; para.query_type = "query_libao_use_data";para.date_s = day_s;para.date_e = day_e;para.game_id = $ns.game_id;para.sn = sn;para.os = os;para.page_conditions = JSON.stringify($ns.settings);para.random = Math.random();console.log(day_s)$.ajax({type:'get',url:QUERY_URL,data:para,dataType:'json',async:false,success:function(data){$ns.total_num = data['total_num'];for(var i in data['data']){data['data'][i][2]=data['data'][i][2].replace(/T/," ");}tables([]);$(".navbar").css("margin-bottom","0");}, complete:function(){},error:function(){tables([]);alert('查询出错!');}});}    //复制数据$("#download_data").click(function(){var para = new Object();var query_url = "/product_center/specific/download_libao/"; query_url += '?date_s='+day_s;query_url += '&date_e='+day_e;query_url += '&game_id='+$ns.game_id;query_url += '&sn='+$("#sn").val();;query_url += '&os='+$("#os").val();;para.random = Math.random();window.open (query_url);});//加载表格function tables(item){$('.table').table({head : ['用户ID', '礼包码', '使用时间','服务器','是否新增','是否充值','充值额'],body : {rows:item,paging:{enabled : true,size : $ns.settings['size'],availableSizes : [15,20,50],totalNum : $ns.total_num,action : function(settings, allrows, comparers, body) {$ns.settings = settings;var sn = $("#sn").val();var os = $('#os').val();var para = new Object();var QUERY_URL = "/product_center/ajax_query/"; para.query_type = "query_libao_use_data";para.date_s = day_s;para.date_e = day_e;para.game_id = $ns.game_id;para.sn = sn;para.os = os;para.page_conditions = JSON.stringify($ns.settings);para.random = Math.random();$.ajax({type:'get',url:QUERY_URL,data:para,dataType:'json',async:false,success:function(data){$ns.total_num = data['total_num'];for(var i in data['data']){data['data'][i][2]=data['data'][i][2].replace(/T/," ");}item = data['data'];}, complete:function(){},error:function(){return [];}});return item;}},}});}
});

html代码:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>礼包码使用情况</title>
{% include "base/head_report.html" %}
<link rel="stylesheet" href="/static/product_center/specific/libao/css/query_libao.css?v=1.0" type="text/css" />
<script>
var $ns = {};
$ns.game_id = {{game_id|default:"''"}};
$ns.report_valid_times = {{valid_time|safe|default:'{}'}};
document.write('<script type="text/javascript" src="/static/product_center/specific/libao/js/query_libao.js?id='+Math.random()+'"><\/script>');//Math.random()
</script>
<script type="text/javascript" src="/static/base/js/util.js"></script>
<script type="text/javascript" src="/static/base/js/filter.js"></script>
</head>
<body>
<div>
<div class="wrapper">
<div class="row" style="">
<div class="conditions">
<div class="tips-options">
<div id="query_date"></div>
<div id="sel">
<input type="text" class="search_text" id="sn" placeholder="输入礼包码查询" />
<select class="input-mini" id="os">
<option value="">---请选择操作系统---</option>
{% for item in dimen_info %}
<option value="{{item.id}}">{{item.name}}</option>
{% endfor %}
</select>
<input type="button" class="btn" id="search_btn" value="查询" />
<input type="button" class="btn-primary copy" id="download_data" value="下载数据"/>
</div>
</div>

</div>
</div>
<div class="row" style="margin-bottom:20px;">
<div class="span12" style="">

<div>
<table id="player_list"
class="table table-condensed table-bordered table-fixed table-hover table-column-hover"
style="border-radius: 0">

</table>
</div>
</div>
</div>

</div>
</div>
</body>
</html>

转载于:https://www.cnblogs.com/qianyongV/p/4268884.html

python进阶(一)关联sql的算法操作相关推荐

  1. 【python进阶】_文件和目录操作

    创建目录 os.makedirs 可以递归的创建目录结构,比如 import os os.makedirs('tmp/python/fileop',exist_ok=True) 会在当前工作目录下面创 ...

  2. Python自学路线图之Python进阶

    Python自学路线图的第二个阶段是Python进阶学习,自学完后需要掌握的Python技能: 1.自学Linux操作系统,熟练使用Linux操作系统: 自学网络编程,掌握网络编程相关技术, 能够实现 ...

  3. Python进阶----表与表之间的关系(一对一,一对多,多对多),增删改查操作

    Python进阶----表与表之间的关系(一对一,一对多,多对多),增删改查操作,单表查询,多表查询 一丶表与表之间的关系 背景: ​ ​ ​  ​ ​ 由于如果只使用一张表存储所有的数据,就会操作数 ...

  4. Python --深入浅出Apriori关联分析算法(二) Apriori关联规则实战

    上一篇我们讲了关联分析的几个概念,支持度,置信度,提升度.以及如何利用Apriori算法高效地根据物品的支持度找出所有物品的频繁项集. Python --深入浅出Apriori关联分析算法(一) 这次 ...

  5. Python进阶6——序列操作

    1.序列的拼接和复制 Python中使用+对序列进行拼接,使用*对序列进行复制 s=str(1234) l=list(range(2,13)) print(s,l) print('---------- ...

  6. 【Python进阶】实战Python图形文件操作基本编程

    欢迎来到专栏<Python进阶>.在这个专栏中,我们会讲述Python的各种进阶操作,包括Python对文件.数据的处理,Python各种好用的库如NumPy.Scipy.Matplotl ...

  7. python bytes查找位置_Python进阶5---StringIO和BytesIO、路径操作、OS模块、shutil模块

    StringIO StringIO操作 BytesIO BytesIO操作 file-like对象 路径操作 路径操作模块 3.4版本之前:os.path模块 3.4版本开始 建议使用pathlib模 ...

  8. python调用sql数据库_Python3操作SQL Server数据库(实例讲解)

    1.前言 前面学完了SQL Server的基本语法,接下来学习如何在程序中使用sql,毕竟不能在程序中使用的话,实用性就不那么大了. 2.最基本的SQL查询语句 python是使用pymssql这个模 ...

  9. SQL进阶之关联子查询行间比较

    SQL进阶之关联子查询行间比较 关联子查询行间比较 越前须知(雾) 具体用法 与最近一年比较营收 移动平均值和移动累计值 查询重叠的时间区间 关联子查询行间比较 越前须知(雾) 本系列参考<SQ ...

  10. SQL进阶之关联子查询练习

    SQL进阶之关联子查询 一.关联子查询简介 二.关联子查询实操 1.CreateTable 2.Sample 一.关联子查询简介 通过关联表内部条件从而达到查询效果 二.关联子查询实操 注:版本使用: ...

最新文章

  1. 分布式服务框架Dubbo疯狂更新!阿里开源要搞大事情?
  2. 什么是SCRUM敏捷开发
  3. Oracle 摘去数据块的面纱
  4. 有一门课不及格的学生(信息学奥赛一本通-T1048)
  5. Spring – IoC 容器
  6. pythonmatplotlib共享绘图区域_在matplotlib绘图中,y标记右侧,共享x和y
  7. 台式计算机如何连接投影仪,台式机PC怎样与投影仪连接
  8. Oracle Spatial 空间分析之缓冲区分析
  9. 单片机控制ws2812b
  10. 【小沐学python】(二)Python常见问题汇总
  11. 字节面试:什么是责任链模式?
  12. SpringBoot之模板引擎
  13. Java多线程之线程池的参数和配置
  14. 同为aPaaS平台,华为云开天aPaaS与AppCube有何不同?
  15. “缓冲区溢出攻击”原理分析及实例演示
  16. 专攻心脑疾病AI市场,数坤科技完成创世伙伴领投2亿元B轮融资...
  17. 腾讯汤道生:2020年加大投入产业互联网生态建设
  18. push推送相关注意事项
  19. 计算机技术 食堂管理,食堂管理系统需求规格说明.doc
  20. 华为云modelarts平台使用

热门文章

  1. [C/C++]堆栈的概念与区别
  2. Tensorflow:安装和配置
  3. 深度学习:循环神经网络RNN的变体
  4. python for mac下载_Python for Mac
  5. msp430和stm32 dht11驱动程序
  6. Java String、StringBuffer、StringBuilder区别
  7. ubuntu安装deb软件包文件
  8. 客气:是礼貌,更是修养 — 《别输在不会表达上》
  9. 剑指offer 33 把数组排成最小的数
  10. HDOJ1181变形课 深搜回溯