广告小程序后端开发(5.安装配置django-rest-framework,编写后台登录逻辑)

1.安装djangorestframework

1.安装djangorestframework及其依赖包markdown、django-filter。

pip install djangorestframework markdown django-filter

2.在settings中注册,如下:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'users.apps.UsersConfig',
    'ad.apps.AdConfig',
    'trade.apps.TradeConfig',
    'user_operation.apps.UserOperationConfig',
    'crispy_forms',
    'xadmin','rest_framework'  
]

2.编写登录逻辑

1.在apps/users目录下新建序列化文件:serializers.py

from rest_framework import serializers
from .models import UserProfile,Area


class UserProfileModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields="__all__"


class AreaModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Area
        fields="__all__"

2.在settings.py中写入APPID和SECRET(从微信开发者公众平台后台内获得):

APPID="……"
SECRET="……"

 3.在settings.py中配置对接百度地图api的AK:

AK="......"

百度地图开发者文档地址:

http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding

百度地图的开发者AK查看页面:

http://lbsyun.baidu.com/apiconsole/key

4.在apps/users/views.py中编写登录视图:

from django.shortcuts import render,HttpResponse
from gg.settings import APPID,SECRET,AK
import urllib.request
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.renderers import JSONRenderer,BrowsableAPIRenderer
from .serializers import UserProfileModelSerializer
from .models import UserProfile,Area,AddJiFen
import hashlib,time,json
from datetime import datetime

# Create your views here.


class LoginView(APIView):
    """登录"""
    renderer_classes = [JSONRenderer]  # 渲染器
    def get(self, request):
        code = request.GET.get('code')
        aurl=request.GET.get('avatarUrl')
        nickname=request.GET.get('nickname')
        gender=request.GET.get('gender')
        longitude=request.GET.get('longitude')
        latitude=request.GET.get('latitude')
        # print(code, nickname, gender, latitude, longitude)
        if code and nickname and longitude and latitude:
            # print(code, nickname,aurl, gender, latitude, longitude)
            # 用前端发过来的code把openid和session_key兑换过来
            url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APPID + "&secret=" + SECRET + "&js_code=" + code + "&grant_type=authorization_code"
            res = urllib.request.urlopen(url)
            content = res.read().decode()
            obj = json.loads(content)
            openid = obj["openid"]
            # print(openid)
            if openid:
                # 生成token,加密
                i = int(time.time())
                s = str(i)
                sha = hashlib.sha1()
                sha.update((openid + s).encode('utf-8'))
                token = sha.hexdigest()
                # print(token)
                # 查看以前此用户是否登陆过
                wxuser = UserProfile.objects.filter(open_id=openid).first()
                if wxuser:
                    # 如果登录过,就将token值更新
                    wxuser.token = token
                    wxuser.nickName=nickname
                    wxuser.avatarUrl=aurl
                    wxuser.gender=gender
                    wxuser.longitude=longitude
                    wxuser.latitude=latitude
                    # 更新最后登录时间
                    wxuser.last_login = datetime.now()
                    wxuser.save()
                else:
                    # 如果没登录过,就生成用户,并且赋值token
                    wxuser = UserProfile()
                    wxuser.open_id = openid
                    wxuser.token = token
                    wxuser.nickName = nickname
                    wxuser.avatarUrl = aurl
                    wxuser.gender = gender
                    wxuser.longitude = longitude
                    wxuser.latitude = latitude
                    wxuser.save()
            else:
                return HttpResponse(404)
            # 根据经纬度,获取用户地理位置,并将省、市、区并且返回
            try:
                areaurl='http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=' + latitude + ',' + longitude + '&output=json&pois=1&ak=' + AK
                ree = urllib.request.urlopen(areaurl)
                # print(ree.read().decode('utf-8'))
                ree=ree.read().decode('utf-8')
                adcode=ree[ree.find("adcode")+9:ree.find("adcode")+15]
                # print(adcode)
                adcode=int(adcode)
                xian=Area.objects.filter(num=adcode).first()
                shi=Area.objects.filter(id=xian.parent_category.id).first()
                sheng=Area.objects.filter(id=shi.parent_category.id).first()
                # print(xian.name,shi.name,sheng.name)
                result = {"status": "200", "data": {'token': token,'nickname':nickname, 'xian': xian.name, 'shi': shi.name,'sheng':sheng.name}}
                # print(result)
                return HttpResponse(json.dumps(result, ensure_ascii=False),
                                    content_type="application/json,charset=utf-8")
            except Exception as e:
                print('获取地区时错误,请检查代码或百度开发者平台相关配置。')
                return HttpResponse(403)
        else:
            return HttpResponse(404)

 

5.配置路由urls.py:

1.在gg/urls.py中:

from django.contrib import admin
from django.urls import path,include
from django.views.static import serve
from gg.settings import MEDIA_ROOT

import xadmin

urlpatterns = [
    #path('admin/', admin.site.urls),
    path('media/',serve,{'document_root':MEDIA_ROOT}),
    path('xadmin/', xadmin.site.urls),
    path('users/',include('users.urls'))
]

2.在apps/users/目录下新建urls.py:

from django.urls import path
from .views import LoginView

urlpatterns = [
    path('login/',LoginView.as_view())
]

 

转载于:https://www.cnblogs.com/xuepangzi/p/10842283.html

你可能感兴趣的:(广告小程序后端开发(5.安装配置django-rest-framework,编写后台登录逻辑))