Example #1
0
def users_weibo_token(request):
    #接收 前端返回的code 并 去微博校验
    code = request.GET.get('code')
    oauth = OAuthWeibo()
    #向微博服务器提交code,若校验成功 返回该用户的token
    res = oauth.get_access_token_uid(code)
    res_obj = json.loads(res)
    access_token = res_obj['access_token']
    uid = res_obj['uid']

    #检查当前这个用户是否注册过我们博客
    try:
        bu = WeiboUser.objects.get(wuid=uid)
    except:
        #用户第一次 用微博账号登录

        WeiboUser.objects.create(wuid=uid, access_token=access_token)
        return JsonResponse({'code': 10999, 'wuid': uid})
    else:
        #检查是否真的绑定过
        buser = bu.buser
        if not buser:
            return JsonResponse({'code': 10999, 'wuid': uid})
        #生成token
        now = datetime.datetime.now()
        token = make_token(buser.username, 3600 * 24, now)
        return JsonResponse({
            'code': 200,
            'username': buser.username,
            'data': {
                'token': token.decode()
            }
        })
Example #2
0
def users(request,username=None):

    if request.method == 'GET':
        if username:
            users = Userprofile.objects.filter(username = username)
            user = users[0]
            #TODO 没用户  返回对用的提示
            #拿具体用户数据
            #有查询字符串[?nickname=1]  or  没查询字符串
            if request.GET.keys():
                #查询字符串
                data = {}
                print(request.GET.keys())
                for k in request.GET.keys():
                    if hasattr(user,k):
                        #过滤字段  若是密码  则跳出此次循环
                        if k == 'password':
                            continue
                        v = getattr(user,k)
                        data[k] = v
                res = {'code':200,'username':username,'data':data}
                return JsonResponse(res)

            else:
                #无查询字符串
                users = Userprofile.objects.filter(username=username)
                #print(users) #<QuerySet [<Userprofile: Userprofile object>]>拿出来的是QuerySet对象
                user = users[0]#拿出来的是:<Userprofile: Userprofile object>
                res = {'code':200,'username':username,'data':{'nickname':user.nickname,
                                                              'sign':user.sign,
                                                              'info':user.info,
                                                              'avatar':str(user.avatar)}}
            #拿具体用户数据
            return JsonResponse(res)

        else:
            #拿全部数据
            all_users = Userprofile.objects.all()   #拿全量数据
            users_data = []
            for user in all_users:
                dic = {}
                dic['nickname'] = user.nickname
                dic['username'] = user.username
                dic['sign'] = user.sign     #个人签名
                dic['info'] = user.info     #此乃个人描述
                users_data.append(dic)
            res = {'code':200,'data':users_data}
            return HttpResponse(res)

    #注册用户
    elif request.method == 'POST':
        #创建用户
        json_str = request.body  #获取到的数据为字节串的字典b'{"username":"******","email":"1321","password_1":"1321"}',
        json_obj = json.loads(json_str)         #将json格式的数据转为字典
        # json_obj返回的数据格式{'username': '******', 'email': '*****@*****.**', 'password_1': '123', 'password_2': '1321'}
        username = json_obj.get('username')
        password_1 = json_obj.get('password_1')
        password_2 = json_obj.get('password_2')
        email = json_obj.get('email')
        # nickname = json_obj.get('nickname')
        if not username or not password_1 or not password_2:
            return JsonResponse({'code':10101,'error':'Please give me username~'})
        if not email:
            return JsonResponse({'code':10102,'error':'请输入邮箱'})
        if password_1 != password_2:
            return JsonResponse({'code':10103,'error':'The password is error!'})
        #TODO 检查json dict 中的key 是否存在
        old_user = Userprofile.objects.filter(username  = username)
        if old_user:
            result = {'code':10104,'error':'用户名已存在'}
            return JsonResponse(result)
        #生成散列的密码
        pm = hashlib.md5()
        pm.update(password_1.encode())#加密动作,无返回值    pm.hexdigest()是取返回值
        #创建用户
        try:    #避免同时注册
            Userprofile.objects.create(username=username,password=pm.hexdigest(),nickname=username,email=email)
        except Exception as e:
            print('------create error------')
            print(e)
            result = {'code':10105,'error':'The username is already existed!!'}
            return JsonResponse(result)
        #生成令牌token
        token = make_token(username)    #设置token的携带用户名和过期时间
        result = {'code':200,'data':{'token':token.decode()},'username':username}
        return JsonResponse(result)

    # 更新 修改用户信息
    elif request.method == 'PUT':
        #更新     http://127.0.0.1:8000/v1/users/username
        if not username:
            res = {'code':10108,'error':'请输入具体用户'}
            return JsonResponse(res)
        json_str = request.body                 #PUT获取数据的方法,同POST
        #TODO 空body判断
        json_obj = json.loads(json_str)         #拿json串
        nickname = json_obj.get('nickname')
        info = json_obj.get('info')
        sign = json_obj.get('sign')
        #更新

        # users = Userprofile.objects.filter(username = username)
        # user = users[0]

        user = request.user
        #当前请求  token用户 修改自己的数据
        if user.username != username:
            result = {'code':10109,'error':'The username is error !'}
            return JsonResponse(result)
        to_update = False
        if user.nickname or user.info or user.sign: #判断用户是否有改动  避免数据做大量无效的动作
            to_update = True
        if to_update:
            #做更新    拿出每一条数据做更新
            user.nickname = nickname
            user.sign = sign
            user.info = info
            user.save() #保存
            # user.update(username = username,info=info,sign=sign,nickname=nickname)
        res = {'code':200,'username':username}
        return JsonResponse(res)

    return JsonResponse({'code': 200})
Example #3
0
def users(request, username=None):
    if request.method == "GET":
        # 拿数据
        if username:
            # 拿具体用户数据
            users = UserProfile.objects.filter(username=username)
            if not users:
                return JsonResponse({
                    'code': 208,
                    'error': 'The user is undefined!'
                })
            user = users[0]
            if request.GET.keys():
                # 有查询字符串
                data = {}
                for k in request.GET.keys():
                    if hasattr(user, k):
                        # 过滤字段
                        if k == 'password':
                            continue
                        v = getattr(user, k)
                        data[k] = v
                res = {'code': 200, 'username': username, 'data': data}
            else:
                # 无查询字符串
                res = {
                    'code': 200,
                    'username': user.username,
                    'data': {
                        'nickname': user.nickname,
                        'sign': user.sign,
                        'info': user.info,
                        'avatar': str(user.avatar)
                    }
                }

            return JsonResponse(res)
        else:
            all_users = UserProfile.objects.all()
            users_data = []
            for user in all_users:
                dic = {}
                dic['nickname'] = user.nickname
                dic['username'] = user.username
                dic['sign'] = user.sign
                dic['info'] = user.info
                users_data.append(dic)
            res = {'code': 200, 'data': users_data}
            return JsonResponse(res)

    elif request.method == "POST":
        # 创建用户
        json_str = request.body
        if not json_str:
            result = {'code': 10202, 'error': 'Please give me data~'}
            return JsonResponse(result)
        json_obj = json.loads(json_str)
        username = json_obj.get('username')
        if not username:
            result = {'code': 10203, 'error': 'Please give me username~'}
            return JsonResponse(result)
        email = json_obj.get("email")
        if not email:
            result = {'code': 10204, 'error': 'Please give me email~'}
            return JsonResponse(result)
        password1 = json_obj.get("password_1")
        password2 = json_obj.get("password_2")
        if not password1 or not password2:
            result = {'code': 10205, 'error': 'Please input password~'}
            return JsonResponse(result)
        if password1 != password2:
            result = {'code': 10206, 'error': 'The password is error!'}
            return JsonResponse(result)
        old_user = UserProfile.objects.filter(username=username)
        if old_user:
            result = {'code': 10207, 'error': 'The username is existed!'}
            return JsonResponse(result)
        # 生成散列密码
        pm = hashlib.md5()
        pm.update(password1.encode())
        password = pm.hexdigest()

        wuid = json_obj.get('wuid')
        # 创建用户
        try:
            with transaction.atomic():
                new_user = UserProfile.objects.create(username=username,
                                                      email=email,
                                                      password=password,
                                                      nickname=username)
                if wuid:
                    w_obj = WeiboUser.objects.get(wuid=wuid)
                    #绑定微博用户和博客用户
                    w_obj.buser = new_user
                    w_obj.save()
        except Exception as e:
            print('---create error---')
            print(e)
            result = {'code': 10208, 'error': 'The username is existed!!'}
            return JsonResponse(result)

        # 生成token
        now = datetime.datetime.now()
        token = make_token(username, 3600 * 24, now)
        result = {
            'code': 200,
            'data': {
                'token': token.decode()
            },
            'username': username
        }

        return JsonResponse(result)

    elif request.method == "PUT":
        # 更新
        if not username:
            res = {'code': 10108, 'error': 'Must be give me username!!'}
            return JsonResponse(res)
        json_str = request.body
        if not json_str:
            res = {'code': 10202, 'error': 'please put data'}
            return JsonResponse(res)
        json_obj = json.loads(json_str)
        sign = json_obj.get('sign')
        info = json_obj.get('info')
        nickname = json_obj.get('nickname')
        #查询用户
        # users = UserProfile.objects.filter(username=username)
        # user = users[0]
        user = request.user
        #当前请求,token用户 修改自己的数据
        if user.username != username:
            result = {'code': 20209, 'error': 'The username is error!'}
            return JsonResponse(result)
        to_update = False
        if user.nickname != nickname:
            to_update = True
        if user.info != info:
            to_update = True
        if user.sign != sign:
            to_update = True
        if to_update:
            #做更新
            user.sign, user.info, user.nickname = sign, info, nickname
            user.save()
        res = {'code': 200, 'username': username}
        return JsonResponse(res)
Example #4
0
def users(request, username=None):

    if request.method == 'GET':
        if username:
            users = UserProfile.objects.filter(username=username)
            user = users[0]
            #没用户 返回提示
            #拿具体用户数据
            #有查询字符串[?nickname=1] or 没查询字符串
            if request.GET.keys():
                #查询字符串
                data = {}
                for k in request.GET.keys():
                    if hasattr(user, k):
                        #过滤字段
                        if k == 'password':
                            continue
                        v = getattr(user, k)
                        data[k] = v
                res = {'code': 200, 'username': username, 'data': data}

            else:
                #无查询字符串
                res = {
                    'code': 200,
                    'username': username,
                    'data': {
                        'nickname': user.nickname,
                    }
                }

            return JsonResponse(res)
        else:
            #拿数据
            all_users = UserProfile.objects.all()
            users_data = []
            for user in all_users:
                dic = {}
                dic['nickname'] = user.nickname
                dic['username'] = user.username
                dic['sign'] = user.sign
                dic['info'] = user.info
                users_data.append(dic)
            res = {'code': 200, 'data': users_data}
            return JsonResponse(res)

    elif request.method == 'POST':
        #创建用户
        json_str = request.body
        if not json_str:
            result = {'code': 10102, 'error': 'Please give me data~'}
            return JsonResponse(result)

        json_obj = json.loads(json_str)
        username = json_obj.get('username')
        email = json_obj.get('email')
        if not username:
            result = {'code': 10101, 'error': 'Please give me username~'}
            return JsonResponse(result)
        #TODO 检查 json dict 中的key 是否存在
        password_1 = json_obj.get('password_1')
        password_2 = json_obj.get('password_2')
        if password_1 != password_2:
            result = {'code': 10103, 'error': 'The password is error!'}
            return JsonResponse(result)

        old_user = UserProfile.objects.filter(username=username)
        if old_user:
            result = {
                'code': 10104,
                'error': 'The username is already existed !'
            }
            return JsonResponse(result)

        #生成散列密码
        pm = hashlib.md5()
        pm.update(password_1.encode())

        #创建用户
        try:
            UserProfile.objects.create(username=username,
                                       password=pm.hexdigest(),
                                       nickname=username,
                                       email=email)
        except Exception as e:
            print('---create error---')
            print(e)
            result = {
                'code': 10105,
                'error': 'The username is already existed !!'
            }
            return JsonResponse(result)

        #生成token
        now_datatime = json_obj.get('login_time')
        token = make_token(username, 3600 * 24, now_datatime)
        result = {
            'code': 200,
            'data': {
                'token': token.decode()
            },
            'username': username
        }
        return JsonResponse(result)

    elif request.method == 'PUT':
        #更新  http://127.0.0.1:8000/v1/users/username
        if not username:
            res = {'code': 10108, 'error': 'Must be give me username !!'}
            return JsonResponse(res)

        json_str = request.body
        #TODO 空Body判断
        json_obj = json.loads(json_str)
        nickname = json_obj.get('nickname')
        #更新
        # users = UserProfile.objects.filter(username=username)
        # user = users[0]

        user = request.user
        #当前请求,token用户 修改自己的数据
        if user.username != username:
            result = {'code': 10109, 'error': 'The username is error !'}
            return JsonResponse(result)

        to_update = False
        if user.nickname != nickname:
            to_update = True

        if to_update:
            #做更新
            user.nickname = nickname
            user.save()
        return JsonResponse({'code': 200, 'username': username})

    return JsonResponse({'code': 200})
Example #5
0
def users(request, username=None):  #传过来的username是POST/PUT请求时要求前端从url中传过来的

    if request.method == 'GET':
        # 拿数据
        # 拿单个用户数据
        users = UserProfile.objects.filter(username=username)

        if username:
            # 如果有querystring[?nickname=1]传进来
            #先判断前端传过来的querystring的字段在我的数据范围内(因为他可以随意传)
            # 因为username是这个表的主键,有且只有一个,而且拿出来的queryset数据外面是列表
            user = users[0]
            if request.GET.keys():  #如果有querystring,拿这个用户的自定数据
                data = {}
                for k in request.GET.keys():
                    if hasattr(user, k):
                        #过滤字段,密码肯定是不能给的
                        if k == 'password':
                            continue
                        #拿querystring对应的字段的值
                        v = getattr(user, k)
                        data[k] = v
                res = {'code': 200, 'username': username, 'data': data}
            else:  #如果无querystring,拿这个用户的所有数据

                res = {
                    'code': 200,
                    'username': username,
                    'data': {
                        'nickname': user.nickname,
                        'sign': user.sign,
                        'info': user.info,
                        'avatar': str(user.avatar)
                    }
                }
            return JsonResponse(res)

        else:  #前端的url中没有用户名传进来,拿所有用户数据
            # 定义返回的数据格式:user = {'code': 200,'data': {'nickname': nickname, 'sign': sign, 'info': info}}
            all_users = UserProfile.objects.all()  #返回的是类字典对象
            #将单个用户的字典类型数据放到这个大列表容器中
            users_data = []
            for user in all_users:
                #用字典装每个用户的数据
                dic = {}
                dic['nickname'] = user.nickname
                dic['username'] = user.username
                dic['sign'] = user.sign
                dic['info'] = user.info
                users_data.append(dic)

            res = {'code': 200, 'data': users_data}
            return JsonResponse(res)

    elif request.method == 'POST':
        # 创建用户
        #创建用户需要做的事情:1取出浏览器发过来的信息2验证用户名是否存在等用户相关3信息正确后创建用户4给用户发门票token让他下次来不用在验证
        #前端设置的content_type=json,此时不能从表单中拿数据(form中是form),需要用request.body拿数据
        json_str = request.body
        if not json_str:
            #code的编码的意义都是团队内部自己定
            result = {'code': 10102, 'error': 'Please give me data~'}
            return JsonResponse(result)
        # 将json串(是字节串)先转为字符串,再转为Python对象
        json_obj = json.loads(json_str.decode())
        # get()方法取字典值
        username = json_obj.get('username')
        email = json_obj.get('email')
        if not username:
            # 返回给一个异常
            result = {'code': 10101, 'error': 'Please give me username~'}
            return JsonResponse(result)
            # 注册成功发个门票token
        # TODO 检查Json dict 中的key 是否存在
        #取出浏览器传过来的两个密码
        password_1 = json_obj.get('password_1')
        password_2 = json_obj.get('password_2')
        if password_1 != password_2:
            result = {'code': 10103, 'error': 'The password id error !'}
            return JsonResponse(result)
        old_user = UserProfile.objects.filter(username=username)
        if old_user:
            result = {
                'code': 10104,
                'error': 'The username is already existed!'
            }
            return JsonResponse(result)

        # 生成散列密码
        # 用md5生成散列密码,生成散列密码的语法
        # import hashlib
        #1.从前端或者浏览器传过来的数据中取密码
        # password = request.POST.get('password') / password = json_obj.get('password')
        # password += 'salt'  #加盐
        # #2.创建md5对象
        # m5 = hashlib.md5()
        # m5.update(password.encode())
        # pw_md5 = m5.hexdigest()
        pm = hashlib.md5()
        pm.update(password_1.encode())

        # 创建用户
        #由于username是主键,有可能别人注册时别人比你跑的快在你之前注册了这个用户名,会报错,所以一定要try一下
        try:
            UserProfile.objects.create(username=username,
                                       password=pm.hexdigest(),
                                       nickname=username,
                                       email=email)
        except Exception as e:
            print('---create error---')
            #自己捕获了一场,要打印出来告诉自己
            print(e)
            result = {
                'code': 10105,
                'error': 'The username is already existed !!'
            }
            return JsonResponse(result)

            #后端发门票(生成token),需要传入用户名和过期时间,token的函数单独定义
        token = make_token(username, 3600 * 24)
        result = {
            'code': 200,
            'data': {
                'token': token.decode()
            },
            'username': username
        }
        #通过装饰器从token中取出来的username需要和传进来的username一致,才真正是本人
        return JsonResponse(result)

    elif request.method == 'PUT':
        # 更新    http://127.0.0.1:8000/v1/users/username
        #put是更新用户信息,肯定只能更新单个用户的信息,全两更新就乱套了,所以必须得传入username
        if not username:
            res = {'code': 10108, 'error': 'Must be give me username !!'}
            return JsonResponse(res)

        json_str = request.body
        #TODO 空body判断
        json_obj = json.loads(json_str.decode())
        nickname = json_obj.get('nickname')
        sign = json_obj.get('sign')
        info = json_obj.get('info')
        #更新
        #将原先的查询用户这一段取代掉,取而代之的使用装饰器从门票token中取出的,通过request这个参数传过来的username
        # users = UserProfile.objects.filter(username=username)
        # #主键,肯定只有一个
        # user = users[0]

        #从装饰器中传过来的request中取出token对应的user
        user = request.user  #这个用户也是个数据行
        #当前请求,token用户 修改自己的数据
        if user.username != username:  #后面的username是url中传过来的
            result = {'code': 10109, 'error': 'The username is error !'}
            return JsonResponse(result)

        #校验下用户传过来的东西和原来是有变化的,不然不触发更新,这样会少很多无效的update
        to_update = False
        if user.nickname != nickname:
            to_update = True
        if user.info != info:
            to_update = True
        if user.sign != sign:
            to_update = True

        if to_update:
            #做更新
            # 方法1:
            #1.查:通过get()/filter()[索引]得到要修改的实例对象;
            #2.改:通过对象.属性的方式修改数据
            #3.保存:对象.save()

            # 方法2:
            # 1.查:books = Books.objects.filter(id__gt=3)
            # 2.更新: books.update(属性=值)
            user.sign = sign
            user.nickname = nickname
            user.info = info
            user.save()
        return JsonResponse({'code': 200, 'username': username})
Example #6
0
File: views.py Project: E-bi/Blog
def users(request, username=None):
    if request.method == 'GET':

        if username:
            user = UserProfile.objects.filter(username=username)
            user = user[0]
            # 拿用户具体数据
            # 有查询字符串[?nickname=allen]
            if request.GET.keys():
                # 查询字符串
                data = {}
                for k in request.GET.keys():
                    if k == 'password':
                        continue
                    if hasattr(user, k):
                        v = getattr(user, k)  # hasattr / getattr的使用
                        data[k] = v
                result = {'code': 200, 'username': username, 'data': data}

            # 没查询字符串
            else:
                if user:
                    result = {
                        'code': 200,
                        'username': user.username,
                        'data': {
                            'nickname': user.nickname,
                            'sign': user.sign,
                            'info': user.info,
                            'avatar': str(user.avatar)
                        }
                    }
                else:
                    result = {'code': 208}
            return JsonResponse(result)
        else:
            # 拿数据
            all_users = UserProfile.objects.all()
            users_data = []
            for user in all_users:
                dic = {}
                dic['nickname'] = user.nickname
                dic['username'] = user.username
                dic['sign'] = user.sign
                dic['info'] = user.info

                users_data.append(dic)
            result = {'code': 200, 'data': users_data}
            return JsonResponse(result)

    elif request.method == 'POST':
        # 创建用户

        json_str = request.body
        if not json_str:
            result = {'code': '10102', 'error': 'Please complete info'}
            return result
        json_obj = json.loads(json_str)
        username = json_obj.get('username')
        email = json_obj.get('email')
        if not username:
            result = {'code': '10101', 'error': 'Please write a username'}
            return JsonResponse(result)

        # TODO 检查json dict中的key是否存在
        password_1 = json_obj.get('password_1')
        password_2 = json_obj.get('password_2')
        if password_1 != password_2:
            result = {'code': '10103', 'error': 'The password is error!'}
            return JsonResponse(result)
        old_user = UserProfile.objects.filter(username=username)
        if old_user:
            result = {
                'code': 10104,
                'error': 'The username is already existed'
            }
            return JsonResponse(result)
        # 生成散列密码
        pm = hashlib.md5()
        pm.update(password_1.encode())

        # 创建用户
        try:
            UserProfile.objects.create(username=username,
                                       password=pm.hexdigest(),
                                       nickname=username,
                                       email=email)
        except Exception as e:
            print('----error----')
            print(e)
            result = {
                'code': 10105,
                'error': 'The username is already existed!!'
            }
            return JsonResponse(result)

        # 生成token
        now_datetime = datetime.datetime.now()
        token = make_token(username, 3600 * 24, now_datetime)
        result = {'code': 200, 'data': {'token': token}, 'username': username}
        return JsonResponse(result)

    elif request.method == 'PUT':
        # 更新 http://127.0.0.1:8000/v1/users/username
        if not username:
            result = {'code': 10107, 'error': 'Must give me username!!'}
            return JsonResponse(result)
        json_str = request.body
        # TODO 空body判断
        json_obj = json.loads(json_str)
        nickname = json_obj['nickname']
        sign = json_obj.get('sign')
        info = json_obj.get('info')
        # 更新
        # user = UserProfile.objects.filter(username=username)
        # user = user[0]
        user = request.user
        # 当前请求,token用户,修改自己的数据
        if user.username != username:
            result = {'code': 10109, 'error': 'The username is error!'}
            return JsonResponse(result)
        to_update = False
        if user.nickname != nickname: to_update = True
        if user.sign != sign: to_update = True
        if user.info != info: to_update = True
        if to_update:
            # 做更新
            user.nickname = nickname
            user.sign = sign
            user.info = info
            user.save()
        return JsonResponse({'code': 200, 'username': username})

    return JsonResponse({'code': 200})
Example #7
0
def users(request, username=None):

    if request.method == 'GET':
        if username:
            # 拿具体用户数据
            try:
                user = UserProfile.objects.get(username=username)
            except Exception as e:
                print(e)
                return JsonResponse({'code': 10108, 'error': 'Not user'})
            # 有查询字符串【?nickname=1】
            if request.GET.keys():
                # 有查询字符串
                data = {}
                for k in request.GET.keys():
                    if hasattr(user, k):
                        # 过滤字段
                        if k == 'password':
                            continue
                        v = getattr(user, k)
                        data[k] = v
                res = {'code': 200, 'username': user.username, 'data': data}
            else:
                # 无查询字符串
                user_data = {}
                user_data['nickname'] = user.nickname
                user_data['sign'] = user.sign
                user_data['info'] = user.info
                user_data['avatar'] = str(user.avatar)
                res = {
                    'code': 200,
                    'username': user.username,
                    'data': user_data
                }
            return JsonResponse(res)

        else:
            # 拿所有用户数据
            all_users = UserProfile.objects.all()
            users_data = []
            for user in all_users:
                user_dict = {}
                user_dict['username'] = user.username
                user_dict['nickname'] = user.nickname
                user_dict['sign'] = user.sign
                user_dict['info'] = user.info
                users_data.append(user_dict)
            res = {'code': 200, 'data': users_data}
            return JsonResponse(res)

    elif request.method == 'POST':
        # 创建用户
        json_str = request.body
        if not json_str:
            result = {'code': 10101, 'error': 'Please give me data !'}
            return JsonResponse(result)
        json_obj = json.loads(json_str)
        username = json_obj.get('username')
        if not username:
            result = {'code': 10102, 'error': 'Please give me username !'}
            return JsonResponse(result)
        email = json_obj.get('email')
        if not email:
            result = {'code': 10103, 'error': 'Please give me email !'}
            return JsonResponse(result)
        password_1 = json_obj.get('password_1')
        password_2 = json_obj.get('password_2')
        if password_1 != password_2:
            result = {
                'code': 10104,
                'error': 'The two password entries are not equal !'
            }
            return JsonResponse(result)

        old_user = UserProfile.objects.filter(username=username)
        if old_user:
            result = {
                'code': 10105,
                'error': 'The username is already existed !'
            }
            return JsonResponse(result)
        # 生成散列密码
        m5 = hashlib.md5()
        m5.update(password_1.encode())
        password = m5.hexdigest()
        # 创建用户
        try:
            user = UserProfile.objects.create(username=username,
                                              nickname=username,
                                              email=email,
                                              password=password)
        except Exception as e:
            print('-----create error-----')
            print(e)
            result = {
                'code': 10106,
                'error': 'The username is already existed !!'
            }
            return JsonResponse(result)
        # 可以生成令牌
        now_datetime = datetime.datetime.now()
        user.login_time = now_datetime
        user.save()
        token = make_token(username, now_datetime, 86400)
        result = {
            'code': 200,
            'data': {
                'token': token.decode()
            },
            'username': username
        }
        return JsonResponse(result)

    elif request.method == 'PUT':
        # 更新数据?
        # http://127.0.0.1:8000/v1/users/caoxudong
        if not username:
            res = {'code': 10107, 'error': 'Must be give me username'}
            return JsonResponse(res)

        json_str = request.body
        #TODO 空body判断
        json_obj = json.loads(json_str)
        # TODO 判断是否有值
        nickname = json_obj.get('nickname')
        sign = json_obj.get('sign')
        info = json_obj.get('info')
        # 获取用户
        # users = UserProfile.objects.filter(username=username)
        # user = users[0]
        user = request.user
        # 当前请求 token用户 修改自己的数据
        if user.username != username:
            result = {'code': 10108, 'error': 'The username is error !'}
            return JsonResponse(result)

        if user.nickname != nickname:
            user.nickname = nickname
        if user.info != info:
            user.info = info
        if user.sign != sign:
            user.sign = sign
        user.save()
        res = {'code': 200, 'username': username}
        return JsonResponse(res)
Example #8
0
def users(request, username=None):
    if request.method == 'GET':
        # 格式:{‘code’:200, ‘data’:{‘nickname’:’abc’, ’sign’:’hell
        # ow’,  ‘info’: ‘hahahahah’}}
        # 拿数据
        if username:
            user = UserProfile.objects.filter(username=username).first()
            if user:
                # 拿具体用户数据
                # 有查询字符串[?nickname] or 没查询字符串
                # python的反射机制 判断对象里面有没有这个属性hasattr(user,'nickname')  判断对象有没有属性有没有值getattr()
                if request.GET.keys():
                    data = {}
                    for k in request.GET.keys():
                        if hasattr(user, k):
                            if k == 'password':
                                continue
                            v = getattr(user, k)
                            data[k] = v
                    res = {'code': 200, 'username': username, 'data': data}
                else:
                    #'avatar':str(user.avatar)}
                    res = {
                        'code': 200,
                        'username': username,
                        'data': {
                            'nickname': user.nickname,
                            'sign': user.sign,
                            'info': user.info,
                            'avatar': str(user.avatar)
                        }
                    }
                return JsonResponse(res)
            else:
                return JsonResponse({'msg': '没有此用户'})
        else:
            users_data = []
            all_user = UserProfile.objects.all()
            for user in all_user:
                dic = {}
                dic['nickname'] = user.nickname
                dic['username'] = user.username
                dic['sign'] = user.sign
                dic['info'] = user.info
                users_data.append(dic)
            res = {'code': 200, 'data': users_data}
            return JsonResponse(res)

    elif request.method == 'POST':
        # 创建用户
        # 因为前端服务器是通过contentType:"application/json"请求的数据,
        # 而request.POST拿不到值,request.POST需要contentType是
        # Content-Type: (表单)application/x-www-form-urlencoded和数据格式要求: name=alex&age=18&gender=男
        # 所以拿值需要request.body--->不需要考虑contentType.
        json_str = request.body  #'{...}'
        if not json_str:
            result = {'code': 10102, 'error': 'Please Give me data !'}
            return JsonResponse(result)

        json_obj = json.loads(json_str)  #{...}
        username = json_obj.get('username')
        if not username:
            result = {'code': 10101, 'error': 'Please give me username~'}
            return JsonResponse(result)
        # 检查json中的dict中的key是否存在
        password_1 = json_obj.get('password_1')
        password_2 = json_obj.get('password_2')
        if password_1 != password_2:
            result = {'code': 10103, 'error': 'The password is error ! ! !'}
            return JsonResponse(result)
        old_user = UserProfile.objects.filter(username=username)
        if old_user:
            result = {
                'code': 10104,
                'error': 'The username is already exited ! '
            }
            return JsonResponse(result)
        # 生成散列的码
        pm = hashlib.md5()
        pm.update(password_1.encode())
        email = json_obj.get('email')
        # 创建用户
        # 并发
        try:
            UserProfile.objects.create(username=username,
                                       password=pm.hexdigest(),
                                       nickname=username,
                                       email=email)
        except Exception as e:
            print('---create error---')
            print(e)
            result = {
                'code': 10105,
                'error': 'The username is already existed!!'
            }
            return JsonResponse(result)
        # 生成令牌
        login_time = datetime.datetime.now()
        token = make_token(username, 3600 * 24, login_time)
        # print('token',token)# b'...'
        # print('token ',token.decode())#'...'
        result = {
            'code': 200,
            'data': {
                'token': token.decode()
            },
            'username': username
        }
        return JsonResponse(result)
    # 只有这个需要校验token
    elif request.method == 'PUT':
        # 更新:8000/v1/users/<username>
        if not username:
            res = {'code': 10108, 'error': 'Must be give me username !! '}
            return JsonResponse(res)
        json_str = request.body
        if json_str:
            # 反序列化成字典
            json_obj = json.loads(json_str)
            nickname = json_obj.get('nickname')
            sign = json_obj.get('sign')
            info = json_obj.get('info')

            # user=UserProfile.objects.filter(username=username).first()
            user = request.user

            to_update = False
            if user.nickname != nickname:
                to_update = True
            if user.info != info:
                to_update = True
            if user.sign != sign:
                to_update = True

            if to_update:
                # 更新
                user.sign = sign
                user.nickname = nickname
                user.info = info
                user.save()
            return JsonResponse({'code': 200, 'username': username})
        else:
            return JsonResponse({'msg': '请输入'})
    return JsonResponse({'code': 200})
Example #9
0
def users(request, username=None):
    if request.method == "GET":
        # 拿数据
        if username:
            # 拿具体用户数据
            users = UserProfile.objects.filter(username=username)
            user = users[0]
            if user:
                if request.GET.keys():
                    # 取字段数据
                    data = {}
                    for key in request.GET.keys():
                        # 过滤字段
                        if key == "password":
                            continue
                        if hasattr(user, key):
                            value = getattr(user, key)
                            data[key] = value
                    result = {"code": 200, "data": data}
                else:
                    data = {}
                    data["nickname"] = user.nickname
                    data["username"] = user.username
                    data["sign"] = user.sign
                    data["info"] = user.info
                    data["avatar"] = str(user.avatar)  # 第四步
                    result = {"code": 200, "data": data}
            else:
                result = {"code": 101, "error": "user is None"}
        else:
            # 拿所有用户数据
            all_users = UserProfile.objects.all()
            users_data = []
            print(all_users)
            for user in all_users:
                dic = {}
                dic['nickname'] = user.nickname
                dic['username'] = user.username
                dic['sign'] = user.sign
                dic['info'] = user.info
                users_data.append(dic)
            result = {"code": 200, "data": users_data}
            return JsonResponse(result)
        return JsonResponse(result)
    elif request.method == "POST":
        # 创建用户
        json_str = request.body
        if not json_str:
            result = {"code": 10101, "error": "please give me some datas!!"}
            return JsonResponse(result)
        json_obj = json.loads(json_str)
        username = json_obj.get("username")
        if not username:
            result = {'code': 10102, 'error': 'Please give me username~'}
            return JsonResponse(result)
        users = UserProfile.objects.filter(username=username)
        if users:
            result = {"code": 10103, "error": "The username already exists!"}
            return JsonResponse(result)

        # 获取手机号码
        phone = json_obj.get("phone")
        if not phone:
            result = {"code": 10104, "error": "Phone number cannot be empty!!"}
            return JsonResponse(result)
        # 验证手机号是否正确
        phone_re = re.compile('^1[3-9]\d{9}$')
        res = re.search(phone_re, phone)

        if not res:  # 不正确
            result = {"code": 10104, "error": "The phone number is error!!"}
            return JsonResponse(result)
        password_1 = json_obj.get("password_1")
        password_2 = json_obj.get("password_2")
        if password_1 == "" or password_2 == "":
            result = {"code": 10105, "error": "Password cannot be empty!!!"}
            return JsonResponse(result)
        if password_1 != password_2:
            result = {"code": 10106, "error": "Two passwords do not match!!"}
            return JsonResponse(result)

        ver_code = json_obj.get("ver_code")
        code_token = json_obj.get("code_token")
        if not ver_code:
            result = {"code": 10107, "error": "Verify code cannot be empty!"}
            return JsonResponse(result)
        if not code_token:
            result = {"code": 10108, "error": "Vertifying failed_01!"}
            return JsonResponse(result)
        try:
            json_obj = jwt.decode(code_token, key=CODE_TOKEN_KEY, algorithms="HS256")
        except Exception as e:
            result = {"code": 10109, "error": e}
            return JsonResponse(result)
        code_expired_time = json_obj.get("exp")
        if not code_expired_time:
            result = {"code": 10108, "error": "Vertifying failed_02!"}
            return JsonResponse(result)
        if time.time() > code_expired_time:
            result = {"code": 10108, "error": "Vertifying is overtime!"}
            return JsonResponse(result)
        code = json_obj.get("code")
        if not code:
            result = {"code":10108,"error":"Vertifying failed_03!"}
            return JsonResponse(result)
        if code != ver_code:
            result = {"code":10109,"error":"Vertifying failed_04!"}
            return JsonResponse(result)


        # 生成散列密码
        pm = hashlib.md5()
        pm.update(password_1.encode())  # 将字符串转为字节串

        # 创建用户
        try:
            UserProfile.objects.create(username=username, phone=phone, password=pm.hexdigest(),
                                       nickname=username)
        except Exception as e:
            print("----create error----")
            print(e)
            result = {"code": 10107, "error": "The username already exists!!!"}
            return JsonResponse(result)

        # 生成Token
        now_datetime = datetime.datetime.now()
        token = make_token(username, 3600 * 24, now_datetime)
        result = {"code": 200, "data": {"token": token.decode()}, 'username': username}
        return JsonResponse(result)
    elif request.method == "PUT":
        # 更新 http://127.0.0.1:8000/v1/users/username
        if username:
            user = request.user
            if user:
                if username != user.username:
                    result = {"code": 10109, 'error': 'The username is error!!'}
                else:
                    json_str = request.body
                    json_obj = json.loads(json_str)
                    nickname = json_obj.get('nickname')
                    sign = json_obj.get('sign')
                    info = json_obj.get('info')
                    # 更新
                    to_update = False
                    if user.nickname != nickname:
                        to_update = True
                    if user.info != info:
                        to_update = True
                    if user.sign != sign:
                        to_update = True
                    if to_update:
                        user.sign = sign
                        user.nickname = nickname
                        user.info = info
                        user.save()
                    result = {"code": 200, "username": username}
            else:
                result = {"code": 10110, "error": "The user not exists!!"}
        else:
            result = {"code": 10108, 'error': 'Must be give me username!!'}
        return JsonResponse(result)
Example #10
0
def users(request, username=None):
    #查看用户信息
    if request.method == 'GET':
        if username:
            users = UserProfile.objects.filter(username=username)
            user = users[0]
            #拿具体用户数据
            #有查询字符串[]
            if request.GET.keys():  #.keys() 获取字典里面所有的键
                #查询字符串
                data = {}
                for k in request.GET.keys():
                    if hasattr(user, k):  #查询字符串是否为表对象字段
                        #
                        if k == 'password':
                            continue

                        v = getattr(user, k)  #取出表中某个对象的某个字段的值
                        data[k] = v
                res = {'code': 200, 'username': username, 'data': data}

            else:
                #无查询字符串

                res={'code':200,'username':username,'data':{\
                    'nickname':user.nickname,'sign':user.sign,
                'info':user.info,'avatar':str(user.avatar)}}

            return JsonResponse(res)

        else:
            #拿数据
            all_users = UserProfile.objects.all()
            users_data = []
            for user in all_users:
                dic = {}
                dic['nickname'] = user.nickname
                dic['username'] = user.username
                dic['sign'] = user.sign
                dic['info'] = user.info
                users_data.append(dic)
            res = {'code': 200, 'data': users_data}
            return JsonResponse(res)

    # 创建用户
    elif request.method == 'POST':

        json_str = request.body  #从请求中获取json格式的字符串
        if not json_str:
            result = {'code': 10102, 'error': 'Please give me data~'}
            return JsonResponse(result)

        json_obj = json.loads(json_str)  #把json格式的字符串转换成python的数据类型
        username = json_obj.get('username')
        email = json_obj.get('email')
        if not username:
            result = {'code': 10101, 'error': 'Please give me username~'}
            return JsonResponse(result)
        #TODO 检查 json dict 中的key 是否存在
        password_1 = json_obj.get('password_1')
        password_2 = json_obj.get('password_2')
        if password_1 != password_2:
            result = {'code': 10103, 'error': 'The password is error!'}
            return JsonResponse(result)

        old_user = UserProfile.objects.filter(username=username)
        if old_user:
            result = {
                'code': 10104,
                'error': 'The username is already existed !'
            }
            return JsonResponse(result)

        #生成散列密码   散列作用:定长32位,不可逆,雪崩(密码中1位变动,整个散列都变)
        pm = hashlib.md5()  # 生成一个散列对象
        pm.update(password_1.encode())  #想要进行散列计算的值加进去,值必须是二进制

        #创建用户
        try:  #增加数据到UserProfile表中
            UserProfile.objects.create(username=username,
                                       password=pm.hexdigest(),
                                       nickname=username,
                                       email=email)
        except Exception as e:
            print('---create error---')
            print(e)
            result = {
                'code': 10105,
                'error': 'The username is already existed !!'
            }
            return JsonResponse(result)
        login_time = time.time()

        #生成token
        token = make_token(username, 3600 * 24, login_time)
        result = {
            'code': 200,
            'data': {
                'token': token.decode()
            },
            'username': username
        }
        return JsonResponse(result)

    # 更新数据
    elif request.method == 'PUT':
        if not username:
            res = {'code': 10108, 'error': 'Must be give me username!!'}
            return JsonResponse(res)
        json_str = request.body
        json_obj = json.loads(json_str)
        nickname = json_obj.get('nickname')
        sign = json_obj.get('sign')
        info = json_obj.get('info')
        #更新
        users = UserProfile.objects.filter(username=username)
        user = users[0]
        # user=request.user
        #当前请求,token用户 修改自己数据
        # if user.username!=username:
        #     result={'code':10109,'error':'The username is eroor!'}
        #     return JsonResponse(result)

        to_update = False
        if user.nickname != nickname:
            to_update = True
        if user.sign != sign:
            to_update = True
        if user.info != info:
            to_update = True

        if to_update:
            #做更新
            user.nickname = nickname
            user.sign = sign
            user.info = info
            user.save()

        return JsonResponse({'code': 200, 'username': username})