luffy项目的接口开发

Posted huang-yc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了luffy项目的接口开发相关的知识,希望对你有一定的参考价值。

 

处理跨域请求

主要的思路:

设置一个基于CORS的中间件来处理,关于跨域的产生与处理手段

settings.py:

技术分享图片
MIDDLEWARE = [
    django.middleware.security.SecurityMiddleware,
    django.contrib.sessions.middleware.SessionMiddleware,
    django.middleware.common.CommonMiddleware,
    django.middleware.csrf.CsrfViewMiddleware,
    django.contrib.auth.middleware.AuthenticationMiddleware,
    django.contrib.messages.middleware.MessageMiddleware,
    django.middleware.clickjacking.XFrameOptionsMiddleware,
    api.cors.CORSMiddleware,
]
View Code

cors.py:

技术分享图片
class CORSMiddleware(MiddlewareMixin):
?
    def process_response(self,request,response):
        # 添加响应头
?
        # 允许你的域名来获取我的数据
        # response[‘Access-Control-Allow-Origin‘] = "*"
?
        # 允许你携带Content-Type请求头
        # response[‘Access-Control-Allow-Headers‘] = "Content-Type"
?
        # 允许你发送DELETE,PUT
        # response[‘Access-Control-Allow-Methods‘] = "DELETE,PUT"
        response[Access-Control-Allow-Origin] = "*"
?
        if request.method == "OPTIONS":
            response[Access-Control-Allow-Headers] = "Content-Type"
            response[Access-Control-Allow-Methods] = "PUT,DELETE"
?
        return response
View Code

urls.py:

技术分享图片
urlpatterns = [
    url(r^admin/, admin.site.urls),
    url(r^api/(?P<version>w+)/, include(api.urls)),
]
 
View Code

 

1.API汇总

  1. 查询所有的课程

     http://127.0.0.1:8000/api/v1/course/

  1. 查询课程详细

    http://127.0.0.1:8000/api/v1/course/1/

  2. 登陆认证

    http://127.0.0.1:8000/api/v1/auth/

  3. 微学位

    http://127.0.0.1:8000/api/v1/micro/

1.1 课程接口

序列化课程表:

技术分享图片
from api import models
from rest_framework import serializers
?
?
class CourseSerializer(serializers.ModelSerializer):
    """
    课程序列化
    """
    level = serializers.CharField(source=get_level_display)
?
    class Meta:
        model = models.Course
        fields = [id, title, course_img, level]
?
?
class CourseDetailSerializer(serializers.ModelSerializer):
    """
    课程详细序列化
    """
    # one2one/fk/choice
    title = serializers.CharField(source=course.title)
    img = serializers.CharField(source=course.course_img)
    level = serializers.CharField(source=course.get_level_display)
?
    # m2m
    recommends = serializers.SerializerMethodField()
    chapter = serializers.SerializerMethodField()
?
    class Meta:
        model = models.CourseDetail
        fields = [course, title, img, level,
                  slogon, why, recommends, chapter]
?
    def get_recommends(self, obj):
        # 获取推荐的所有课程
        queryset = obj.recommend_courses.all()
?
        return [{id: row.id, title: row.title} for row in queryset]
?
    def get_chapter(self, obj):
        # 获取推荐的所有课程
        queryset = obj.course.chapter_set.all()
?
        return [{id: row.id, name: row.name} for row in queryset]
View Code

course.py:

技术分享图片
from api import models
from rest_framework import serializers
?
?
class CourseSerializer(serializers.ModelSerializer):
    """
    课程序列化
    """
    level = serializers.CharField(source=get_level_display)
?
    class Meta:
        model = models.Course
        fields = [id, title, course_img, level]
?
?
class CourseDetailSerializer(serializers.ModelSerializer):
    """
    课程详细序列化
    """
    # one2one/fk/choice
    title = serializers.CharField(source=course.title)
    img = serializers.CharField(source=course.course_img)
    level = serializers.CharField(source=course.get_level_display)
?
    # m2m
    recommends = serializers.SerializerMethodField()
    chapter = serializers.SerializerMethodField()
?
    class Meta:
        model = models.CourseDetail
        fields = [course, title, img, level,
                  slogon, why, recommends, chapter]
?
    def get_recommends(self, obj):
        # 获取推荐的所有课程
        queryset = obj.recommend_courses.all()
?
        return [{id: row.id, title: row.title} for row in queryset]
?
    def get_chapter(self, obj):
        # 获取推荐的所有课程
        queryset = obj.course.chapter_set.all()
?
        return [{id: row.id, name: row.name} for row in queryset]
?
View Code

urls.py:

技术分享图片
    url(r^course/$, course.CourseView.as_view({get:list})),
    url(r^course/(?P<pk>d+)/$, course.CourseView.as_view({get:retrieve})),
View Code

1.2 登陆认证接口:

要点:

  • 为了保证接口的安全,即使Vue部分已经完成了用户的认证,接口还是需要对Vue的token进行认证。

  • uuid可以用来生成随机字符串,且基于mac地址与时间的组合,安全性较高。此字符串可以用来作为我们的token

account.py

技术分享图片
import uuid
class AuthView(APIView):
?
    def post(self,request,*args,**kwargs):
        """
        用户登录认证
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
?
        ret = {code:1000}
        user = request.data.get(user)
        pwd = request.data.get(pwd)
?
        user = models.UserInfo.objects.filter(user=user,pwd=pwd).first()
        if not user:
            ret[code] = 1001
            ret[error] = 用户名或密码错误
        else:
            # 这里就是利用uuid模块来生成安全性较高的字符串
            uid = str(uuid.uuid4())
            models.UserToken.objects.update_or_create(user=user,defaults={token:uid})
            ret[token] = uid
        return Response(ret)
View Code

 

1.3 微职位接口

views.py:

技术分享图片
class MicroView(APIView):
    authentication_classes = [LuffyAuth,]
?
    def get(self,request,*args,**kwargs):
        ret = {code:1000,title:微职位}
        return Response(ret)
View Code

 

urls.py:

技术分享图片
url(r^micro/$, course.MicroView.as_view())
View Code

 

 

 

 

以上是关于luffy项目的接口开发的主要内容,如果未能解决你的问题,请参考以下文章

luffy--02

luffy-city 基础环境搭建(至轮播图前后台交互实现)-步骤目录

luffy--01

前端Vue框架 01

luffy项目中关于APIView的使用

(失败)配置vue+nginx+uwsgi luffy项目