コード例 #1
0
def test(request):
    # basic_auth = request.META.get('HTTP_AUTHORIZATION')
    # userpk = request.POST.get('userpk', request.GET.get('userpk'))
    # token = request.POST.get('token', request.GET.get('token'))
    # print userpk,token
    # if not (userpk and token) and basic_auth:
    #         auth_method, auth_string = basic_auth.split(' ', 1)
    #
    #         if auth_method.lower() == 'basic':
    #             auth_string = b64decode(auth_string.strip())
    #             userpk, token = auth_string.decode().split(':', 1)
    # if not (userpk and token):
    #     # print request.body
    #     request_data= json.loads(request.body)
    #     userpk = request_data['userpk']
    #     token = request_data['token']
    # print userpk,token
    # us = None
    # pw = None
    # print request.method
    # if request.method == 'POST':
    #     print "POST"
    #     # print request.META
    #     print request.POST
    #     us = request.POST.get('userpk')
    #     pw = request.POST.get('token')
    # print us,pw

    return JsonResponse({})
コード例 #2
0
def get_month_res(request):
    # data = MONTH_REQUEST
    try:
        data = json.loads(request.body)
        id = data["id"]
        month = data["month"]
        user = AuthUser.objects.get(id=1)
        # print user.username
        year, month = data["month"].split("-")[0], data["month"].split("-")[1]
        rs = user.runningresult_set.filter(
            running_result_starttime__year=year,
            running_result_starttime__month=month)

        # from django.core import serializers
        # data =serializers.serialize("json",rs)
        # print data
        # print "````````````````````````"
        # print rs[0].toJSON()
        result = []
        # print rs
        if rs != None:
            for every_res in rs:
                #每个跑步结果的坐标集
                res = {}
                res["distance"] = every_res.running_result_distance

                sp = every_res.running_result_duration

                # print str(every_res.running_result_duration)
                # sp = time.strptime(str(every_res.running_result_duration),'%H:%M:%S')
                # res["duration"]=str(sp.tm_sec+sp.tm_min*60+sp.tm_hour*3600)
                res["duration"] = str(sp.second + sp.minute * 60 +
                                      sp.hour * 3600)
                res["starttime"] = str(every_res.running_result_starttime)
                res["endtime"] = str(every_res.running_result_endtime)
                res["running_result_id"] = str(every_res.running_result_id)
                # print res["duration"]
                res["locations"] = []
                loc_set = every_res.locations_set.all()
                # from django.core import serializers
                # data =serializers.serialize("json",loc_set)
                # print data
                for every_loc in loc_set:
                    el = {}
                    el["latitude"] = every_loc.latitude
                    el["longitude"] = every_loc.longitude
                    # el["time"]=time.mktime(time.strptime(every_loc.time, '%Y-%m-%d %H:%M:%S'))
                    el["time"] = str(
                        int(time.mktime(every_loc.time.timetuple())))
                    # print el["time"]
                    res["locations"].append(el)
                result.append(res)

        return JsonResponse({"run": result})
    except Exception, e:
        return JsonError(e.message)
コード例 #3
0
def walk_test(request):
    return JsonResponse(DOMAIN)
    try:
        walk = WALK
        user = AuthUser.objects.get(id=walk["id"])
        time_tmp = datetime.datetime.now()
        walk_set = walk["walk"]
        for i in walk_set:
            oneDayAgo = (time_tmp - datetime.timedelta(days=1))
            otherStyleTime = oneDayAgo.strftime("%Y-%m-%d")
            time_tmp = oneDayAgo
            walk_obj = Walk(time=otherStyleTime, value=i)
            walk_obj.user = user
            walk_obj.save()
    except Exception, e:
        return JsonError("fail")
コード例 #4
0
def get_month_ranking(request):
    try:
        # data = MONTH_RANK
        data = json.loads(request.body)
        # year,month =data["time"].split("-")
        # rs_sort =RunningResult.objects.filter(running_result_starttime__year=year)\
        #         .filter(running_result_starttime__month=month)\
        #         .extra({'running_result_distance_de':"CAST(running_result_distance as DECIMAL)"})\
        #         .order_by('-running_result_distance_de')\
        #         .values('user_id').annotate(ds=Count("user_id"))
        # print rs_sort
        year_month = data["time"]
        res = my_custom_sql(year_month)  #获取当月的所有记录。然后再找自己的记录
        # print res
        result = {}
        #得到自身排名
        for index, values in enumerate(res):
            if values["user_id"] == int(data["id"]):
                result["my_ranking"] = str(index + 1)
                # print index,type(values["user_id"])
        page = int(data["page"])
        interval = int(data["interval"])
        strat = (page - 1) * interval
        #获取排名列表
        r = res[strat:strat + 5]
        for i in r:
            sum = str(i.pop("amount_sum"))
            id = i.pop("user_id")
            user = AuthUser.objects.get(id=id)
            i["username"] = user.username
            i["sum"] = sum
            #获取头像
            user_inf_set = user.userinformation_set.all()
            if len(user_inf_set) == 0:
                res_avatar = defalut_avatar
            else:
                user_inf = user_inf_set[0]
                res_avatar = defalut_avatar if user_inf.user_avatar == "" else user_inf.user_avatar
            i["avatar"] = DOMAIN + res_avatar

        result["ranking"] = r
        return JsonResponse(result)
    except Exception, e:
        return JsonError(e.message)
コード例 #5
0
def return_first_three(my_rs):
    # RunningResult.objects.all()
    #返回距离前三名
    #将mysql里面的distance(varchar)转换为小数
    try:
        rs_sort =RunningResult.objects.all()\
        .extra({'running_result_distance_de':"CAST(running_result_distance as DECIMAL)"})\
        .order_by('-running_result_distance_de')
        rs_fir_thr = rs_sort[:3]

        # my_rs = RunningResult.objects.get(running_result_id=9)
        result = {}
        run = []
        #个人排名
        my_ranking = list(rs_sort.values_list(
            'running_result_id', flat=True)).index(my_rs.running_result_id) + 1
        result["my_ranking"] = str(my_ranking)
        result["running_result_id"] = my_rs.running_result_id
        #返回前三
        for i in rs_fir_thr:
            data = {}
            data['username'] = i.user.username
            data['distance'] = i.running_result_distance
            run.append(data)
        result["three"] = run

        # print type(rs_sort)
        # print rs_sort.index(my_rs)
        # print rs_sort[2] ==my_rs
        # for index, item in enumerate(rs_sort):
        #     # print index,type(item)
        #     print my_rs.running_result_id,item.running_result_id
        #     if item.running_result_id == my_rs.running_result_id:
        #         print index
        #         break
        #     print "end"

        # print rs_sort.index(my_rs)
        return JsonResponse(result)
    except Exception, e:
        # print e.message
        return JsonError("get the first three fail")
コード例 #6
0
def check_token_in_cache(data):
    token = data['token']
    userpk= data['userpk']
    userpk_origin = get_userpk(token)
    if userpk_origin:
        # try :
        user_str = "userpk"+"-"+str(userpk_origin)
        value = user_str+":"+token
        try:
            time_signer.unsign(value,max_age=max_age)
        except Exception,e:
            # print e.message
            delete_token(token)
            return None,JsonError("expired please login in again")
        else:
            if userpk ==userpk_origin:
                user = User.objects.get(pk=userpk_origin)
                return user,JsonResponse({})
            else:
                return None,JsonError("Login in Fail PK ")
コード例 #7
0
def upload_mul_result(request):
    try:
        mul_res = json.loads(request.body)
        # mul_res=RUNNING_MUL_RESULT
        result = []
        for i in mul_res["run"]:
            one_res = {}
            one_res["id"] = mul_res["id"]
            one_res["run"] = i
            ret = upload_one_result(one_res)
            content = ret.content
            ret_dic = json.loads(content)
            if ret_dic["success"] == "0":
                return ret
            else:
                result.append(ret_dic['running_result_id'])
            # if isinstance(ret,JsonError):
            #     pass
        return JsonResponse({"running_result_id": result})
    except Exception, e:
        return JsonError(e.message)
コード例 #8
0
def get_ranking(request):
    try:
        # data=RANK
        data = json.loads(request.body)
        r_r_id = data["running_result_id"]
        r_r = RunningResult.objects.get(running_result_id=r_r_id)
        r_r_start = str(r_r.running_result_starttime)
        # r_r_start
        day = time.strptime(r_r_start, '%Y-%m-%d %H:%M:%S').tm_mday
        month = time.strptime(r_r_start, '%Y-%m-%d %H:%M:%S').tm_mon
        year = time.strptime(r_r_start, '%Y-%m-%d %H:%M:%S').tm_year
        # print r_r_start,day,month,year

        rs_sort =RunningResult.objects.filter(running_result_starttime__year=year)\
            .filter(running_result_starttime__month=month)\
            .filter(running_result_starttime__day=day)\
            .extra({'running_result_distance_de':"CAST(running_result_distance as DECIMAL)"})\
            .order_by('-running_result_distance_de')
        result = {}
        #个人排名
        my_ranking = list(rs_sort.values_list(
            'running_result_id', flat=True)).index(r_r.running_result_id) + 1
        result["my_ranking"] = str(my_ranking)
        #根据需求返回列表
        page = int(data["page"])
        interval = int(data["interval"])
        start = (page - 1) * interval
        rs_list = rs_sort[start:start + interval]
        print rs_sort, rs_list
        rank = []
        for i in rs_list:
            evr = {}
            rs_user = i.user
            evr["username"] = rs_user.username
            evr["distance"] = i.running_result_distance
            rank.append(evr)
        result["ranking"] = rank
        return JsonResponse(result)
    except Exception, e:
        return JsonError(e.message)
コード例 #9
0
def change_pwd(request):
    try:
        # data=PWD
        data = json.loads(request.body)
        id = data["id"]
        a_user = AuthUser.objects.get(id=id)
        username = a_user.username
        password = data["old_password"]
        new_password = data["new_password"]

        if username and password:
            user = authenticate(username=username, password=password)

            if user and user.is_active:
                user.set_password(new_password)
                user.save()
                return JsonResponse()
            else:
                return JsonError("password is not valid")
        else:
            return JsonError("Fail")

    except Exception, e:
        return JsonError(e.message)
コード例 #10
0
                loc_value = {
                    "latitude": ls["latitude"],
                    "longitude": ls["longitude"],
                    "time": change_time_from_str_to_datatime(ls["time"]),
                    # "time":213
                }

                loc_obj = Locations(**loc_value)
                loc_obj.running_result = re
                loc_obj.save()
            # print "loc success"
    except Exception, e:
        # print e.message
        return JsonError("upload fail")
    else:
        return JsonResponse({"running_result_id": str(running_result_id)})


#返回本次排名和前三名
def return_first_three(my_rs):
    # RunningResult.objects.all()
    #返回距离前三名
    #将mysql里面的distance(varchar)转换为小数
    try:
        rs_sort =RunningResult.objects.all()\
        .extra({'running_result_distance_de':"CAST(running_result_distance as DECIMAL)"})\
        .order_by('-running_result_distance_de')
        rs_fir_thr = rs_sort[:3]

        # my_rs = RunningResult.objects.get(running_result_id=9)
        result = {}
コード例 #11
0
def signup(request):
    data = {}
    # print request.method
    try:
        if request.method == "POST":
            username = request.POST.get('username', None)
            password = request.POST.get('password', None)
            realname = request.POST.get('realname', None)

            if not (username and password and realname):
                # print request.body
                try:
                    request_data = json.loads(request.body, "utf-8")
                    # request_data= simplejson.loads(request.body)
                    username = request_data["username"]
                    password = request_data["password"]
                    realname = request_data["realname"]
                except Exception, e:
                    # print e
                    return JsonError(e.message + "is required")
                # email =request_data['email']
            # print username,password,realname
            if username and password and realname:
                try:
                    # print "test get user"
                    user = User.objects.get(username=username)
                    # print user
                except User.DoesNotExist, e:
                    # print repr(realname)
                    user = User.objects.create_user(username,
                                                    password=password,
                                                    first_name=realname[:-2],
                                                    last_name=realname[-2:])
                    # user = User.objects.create_user(username,password=password,first_name=realname.encode('unicode_escape'))
                    # user = User.objects.create_user(username,password=password,first_name=u"尹子勺")

                    if user and user.is_active:
                        login(request, user)
                        token = make_token_in_cache(user).split(":", 1)[1]

                        #将{token:id}放在redis内
                        redis_data = {
                            'token': token,
                            'userpk': user.pk,
                        }
                        insert_token(redis_data)
                        #将pk加密

                        # userpk_encode = user_signer.sign(user.pk).split(":",1)[1]
                        # data = {
                        #     'token':token,
                        #     'userpk':userpk_encode,
                        # }

                        ##默认值
                        data = {
                            'token': token,
                            'id': str(user.pk),
                            'username': username,
                            'realname': realname,
                            'avatar': DOMAIN + defalut_avatar,
                            'height': "165",
                            'weight': "55",
                            'sex': "男",
                            'birth': "1990-01-01",
                        }
                        user = AuthUser.objects.get(id=user.pk)
                        inf = user.userinformation_set.all()
                        if len(inf) != 0:
                            inf = inf[0]
                            data["avatar"] = DOMAIN + inf.user_avatar
                            data["height"] = inf.user_height
                            data["weight"] = inf.user_weight
                            data["sex"] = inf.user_sex
                            data["birth"] = str(inf.user_birth)
                        return JsonResponse(data)
                    else:

                        return JsonError("用户被关进小黑屋")
                else:
                    return JsonError("用户已经存在")
            else:
コード例 #12
0
def login_from_pwd(request):
    try:
        username = None
        password = None
        if request.method == 'POST':
            username = request.POST.get('username')
            password = request.POST.get('password')
            # username="******"fhttp://127.0.0.1/
            # password="******"
            if not (username and password):
                # print request.body
                request_data = json.loads(request.body)
                username = request_data["username"]
                password = request_data["password"]
                # print username,password
            if username and password:
                user = authenticate(username=username, password=password)

                if user and user.is_active:
                    login(request, user)
                    token = make_token_in_cache(user).split(":", 1)[1]

                    #将{token:id}放在redis内
                    redis_data = {
                        'token': token,
                        'userpk': user.pk,
                    }
                    insert_token(redis_data)
                    #将pk加密

                    # userpk_encode = user_signer.sign(user.pk).split(":",1)[1]
                    # data = {
                    #     'token':token,
                    #     'userpk':userpk_encode,
                    # }
                    #不加密
                    username = user.username
                    realname = user.first_name + user.last_name

                    data = {
                        'token': token,
                        'id': str(user.pk),
                        'username': username,
                        'realname': realname,
                        'avatar': DOMAIN + defalut_avatar,
                        'height': "165",
                        'weight': "55",
                        'sex': "男",
                        'birth': "1990-01-01",
                    }
                    user = AuthUser.objects.get(id=user.pk)
                    inf = user.userinformation_set.all()
                    if len(inf) != 0:
                        inf = inf[0]
                        if inf.user_avatar != None:
                            data["avatar"] = DOMAIN + inf.user_avatar
                        if inf.user_weight != None:
                            data["weight"] = inf.user_weight
                        if inf.user_sex != None:
                            data["sex"] = inf.user_sex
                        if inf.user_birth != None:
                            data["birth"] = str(inf.user_birth)
                        if inf.user_height != None:
                            data["height"] = inf.user_height

                    # print data
                    return JsonResponse(data)
                else:
                    return JsonError("Fail")
            else:
                return JsonError("username and password is required")
        else:
            return JsonError("POST is required")
    except Exception, e:
        return JsonError(e.message)
コード例 #13
0
        except Exception, e:
            # print e.message
            return JsonError("inf Fail")

        result = {}
        if user_inf.user_avatar == "":
            res_avatar = defalut_avatar
        else:
            res_avatar = user_inf.user_avatar
        result["avatar"] = DOMAIN + res_avatar
        result["height"] = user_inf.user_height
        result["weight"] = user_inf.user_weight
        result["sex"] = user_inf.user_sex
        result["birth"] = str(user_inf.user_birth)
        result["realname"] = user.first_name + user.last_name
        return JsonResponse(result)
        # avatar = getattr(data,"user_avatar",None)
    except Exception, e:
        # print e.message
        return JsonError("Fail")


#上传头像
@token_cache_required
def upload_ava(request):
    try:
        # data =UPLOAD_PIC_2
        data = json.loads(request.body)
        avatar = data["avatar"]
        id = data["id"]
        user = AuthUser.objects.get(id=id)