上传,下载,====

原创 2018年04月16日 14:52:39
# coding:utf-8
import inspect
import hashlib
import xlrd
import threading
import logging
import os, datetime
from django.conf import settings
from django.core.cache import cache
from django.http import HttpResponse
from libs.utils.common import render_template
from libs.utils.lib_page import Page
from libs.utils.DB_SQL import db
log = logging.getLogger(__name__)


def deal_user(request):
    """
    功能说明:手机号为空的查询
    """
    context = {}
    user = request.user
    try:
        if request.method == 'POST':
            page_no = int(request.POST.get('page_no', 1))
            # province = request.POST.get('province')  #             province = '410000'
            city = request.POST.get('city')  #             county = request.POST.get('county')  # 县区
            and_where = ''
            if province:
                and_where = "AND mor.province= %s" % province
            if city:
                and_where = "AND mor.city= %s" % city
            if county:
                and_where = "AND mor.city= %s" % county
            sql_no_phone = """
                SELECT
                mor.city, 
                mor.county, 
                mor.school_name,
                au.real_name,
                au.id,
                au.phone                 
                FROM tbkt_user.auth_user au 
                INNER JOIN tbkt_ketang.mobile_order_region mor ON au.id = mor.user_id
                %(and_where)s
                AND LENGTH (au.phone) < 11
                GROUP BY 
                 au.id
                """ %{"and_where":and_where}
            # AND au.real_phone is None   上线时修改
            head_title = ['地市', '县区', '学校', '姓名', '用户ID', '手机号']
            context['head_title'] = head_title
            # 设置缓存
            m = hashlib.md5()
            m.update('%s%s' % (sql_no_phone, user.id))
            key = context['key'] = m.hexdigest()
            cache_name = "key_%s" % key
            log.info("cache_name:%s" % cache_name)
            if cache.has_key(cache_name):
                _data = cache.get(cache_name)
                data_list = _data['data_list']
            else:
                # 查询用户手机号为空的用户信息
                data_tuple = db.slave.fetchall(sql_no_phone, None)
                data_list = [[v for v in obj] for obj in data_tuple]
                # 生成地市县区名称数据
                area_dict = get_mobile_name()
                # 对用户的地市id进行匹配
                for obj_area in data_list:
                    obj_area[0] = area_dict.get(obj_area[0],'---')
                    obj_area[1] = area_dict.get(obj_area[1],'---')
                cache.set(cache_name, {'data_list': data_list, 'head_title': head_title}, 60 * 10)
            # 分页查询结果
            page = Page(data_list, request, paginate_by=20, pageno=page_no)
            context["page"] = page
            return render_template(request, 'school/block/deal_user.html', context)
    except Exception as e:
        import traceback
        traceback.print_exc()
        log.error("%s:%s" % (inspect.stack()[0][3], e))

    return render_template(request, 'school/deal_user.html', context)


def deal_user_down(request):
    """
    功能说明:                 下载导入处理结果的Excel
    -----------------------------------------------
    """
    from excel_response3 import ExcelResponse
    if request.method == 'GET':
        key = request.GET.get('key')
        file_name = u'手机号有问题的用户数据'
        # 获取缓存
        cache_name = "key_%s" % key
        cache_dict = None
        if cache.get(cache_name):
            cache_dict = cache.get(cache_name)
        data_list = cache_dict['data_list']
        th_title = cache_dict['head_title']
        area_title = []  # 地区列头
        area_one = []  # 地区名称
        data = []
        row_one = area_title
        for i in range(len(th_title)):
            row_one.append(th_title[i])
        data.append(row_one)
        for row in data_list:
            row_one = [] + area_one
            for i in range(0, len(row)):
                if row[i]:
                    row_one.append(row[i])
                else:
                    row_one.append(0)
            data.append(row_one)
        return ExcelResponse(data, file_name.encode('gbk'))


def update_user(request):
    """
    功能说明:对手机号为空的用户进行更新
    """
    context = {}
    user = request.user
    try:
        if request.POST:
            file_obj = request.FILES.get('import_data',None)
            file_name = conserve_file(file_obj, 'batch')
            print "file_name:", file_name
            m = hashlib.md5()
            key = context['key'] = m.hexdigest()
            if file_name:
                # 启动多线程处理数据
                t = threading.Thread(target=manager_handle, args=(file_name, key))
                t.start()
            #处理结束删除数据
            return render_template(request, 'school/block/update_user.html', context)
    except Exception as e:
        import traceback
        traceback.print_exc()
        log.error("%s:%s" % (inspect.stack()[0][3], e))
    return render_template(request, 'school/update_user.html', context)


def update_user_phone(real_phone,user_id):
    sql_user= """
        SELECT au.phone 
        FROM tbkt_user.auth_user au 
        WHERE au.id =%(user_id)s
    """ % {"user_id":user_id}
    # 记得修改是real_phone-----------------------------------
    phone = db.slave.fetchone(sql_user, None)
    if len(phone) > 0:
        result = db.tbkt_user.auth_user.filter(id=user_id).update(phone=real_phone)
        return result
    else:
        return u"已存在电话"


def manager_handle(url, key):
    data = xlrd.open_workbook(url)
    table = data.sheets()[0]
    data_list = [table.row_values(r) for r in range(1, table.nrows)]
    print data_list
    for data in data_list:
        user_id = data[4]
        real_phone = data[5]
        result = update_user_phone(real_phone, user_id)

    # 缓存结果数据表头
    th_title = [u'地市', u'县区', u'学校', u'姓名', u'用户ID', u'手机号']
    # 设置下载处理结果数据缓存
    cache_name = "key_%s" % key
    cache.set(cache_name, {'data_list': data_list, 'th_title': th_title}, 60 * 3)



def get_mobile_name():
    """
    功能:获取区域名称
    """
    # sql = """SELECT id,`name` FROM tbkt_com.common_provincecity WHERE cityId LIKE "32%";"""
    sql = """SELECT cityId,`name` FROM tbkt_com.common_provincecity WHERE cityId LIKE "41%";"""
    data_list = db.slave.fetchall(sql, None)
    area_dict = {obj[0]: obj[1] for obj in data_list}
    return area_dict


def rename(filename, prefix=''):
    """
    返回以日期命名的文件名
    """
    x = filename.rindex('.') + 1
    y = len(filename)
    ext_name = filename[x:y]
    now_time = datetime.datetime.now()
    retval = '%s.%s' % (now_time.strftime("%Y%m%d%H%M%S") + str(now_time.microsecond), ext_name)
    if prefix:
        retval = prefix + retval
    return retval


def getfilename(filename, subdir=''):
    """
    返回路径字符串
    """
    if subdir:
        return os.path.join(settings.MEDIA_ROOT, subdir, filename)
    else:
        return os.path.join(settings.MEDIA_ROOT, filename)


def conserve_file(file_obj, conserve_path):
    """
    功能:文件保存并返回文件路径名
    """
    try:
        file_path = rename(file_obj.name)
        file_name = getfilename(file_path, "%s/" % conserve_path)
        destination = open(file_name, 'wb+')
        for chunk in file_obj.chunks():
            destination.write(chunk)
        destination.close()
        return file_name
    except Exception as e:
        import traceback
        traceback.print_exc()
        return None


def market_test(request):
    """
    功能说明:生成数据检测
    """
    if request.method == "POST":
        key = request.GET.get('key')
        cache_name = "key_%s" % key
        if cache.get(cache_name):
            info = "ok"
            return HttpResponse(info)
        else:
            info = "wait"
            return HttpResponse(info)

文件的上传与下载---下载

Web应用中实现文件下载的两种方式    1.超链接直接指向下载资源。    2.程序实现下载需设置两个响应头。       1--设置Content-Type 的值为:application/...
  • wyd458549392147
  • wyd458549392147
  • 2011-11-22 21:05:22
  • 460

上传和下载

  • 2015年03月16日 19:18
  • 305KB
  • 下载

上传,下载

 //检查上传文件不为空if(File1.PostedFile!=null){stringnam=File1.PostedFile.FileName;//取得文件名(抱括路径)里最后一个"."的索引i...
  • wk122348545
  • wk122348545
  • 2008-09-25 10:50:00
  • 219

上传与下载

  • 2014年03月28日 20:04
  • 653KB
  • 下载

上传、下载

上传 public class AddFoodServlet extends HttpServlet { private static final long serialVersionUID = 1...
  • panhaigang123
  • panhaigang123
  • 2017-11-02 16:43:37
  • 66

上传 与下载

上传 与下载package org.wanda.work.controller; import java.io.BufferedInputStream; import java.io.Buffere...
  • qq_33075157
  • qq_33075157
  • 2016-08-24 19:13:45
  • 200

上传&下载

上传upload.html:      do_upload.jsp: 
  • shunri
  • shunri
  • 2010-01-13 15:20:00
  • 141

上传 下载

1.xutils依赖 compile 'org.xutils:xutils:3.3.36' 2.布局:button按钮
  • mmjjj022
  • mmjjj022
  • 2017-03-19 18:26:27
  • 295

上传及下载

/** * 导入脚本接口 * @param request */ @RequestMapping(value = &quot;/importRule.json&quot;) @ResponseB...
  • XiaoHanZuoFengZhou
  • XiaoHanZuoFengZhou
  • 2018-03-02 19:33:49
  • 28

上传和下载系统 上传和下载系统

  • 2010年06月20日 22:30
  • 883KB
  • 下载
收藏助手
不良信息举报
您举报文章:上传,下载,====
举报原因:
原因补充:

(最多只允许输入30个字)