zoukankan      html  css  js  c++  java
  • 使用Django开发REST 接口

    # views.py
    
    from datetime import datetime
    
    class BooksAPIVIew(View):
        """
        查询所有图书、增加图书
        """
        def get(self, request):
            """
            查询所有图书
            路由:GET /books/
            """
            queryset = BookInfo.objects.all()
            book_list = []
            for book in queryset:
                book_list.append({
                    'id': book.id,
                    'btitle': book.btitle,
                    'bpub_date': book.bpub_date,
                    'bread': book.bread,
                    'bcomment': book.bcomment,
                    'image': book.image.url if book.image else ''
                })
            return JsonResponse(book_list, safe=False)
    
        def post(self, request):
            """
            新增图书
            路由:POST /books/ 
            """
            json_bytes = request.body
            json_str = json_bytes.decode()
            book_dict = json.loads(json_str)
    
            # 此处详细的校验参数省略
    
            book = BookInfo.objects.create(
                btitle=book_dict.get('btitle'),
                bpub_date=datetime.strptime(book_dict.get('bpub_date'), '%Y-%m-%d').date()
            )
    
            return JsonResponse({
                'id': book.id,
                'btitle': book.btitle,
                'bpub_date': book.bpub_date,
                'bread': book.bread,
                'bcomment': book.bcomment,
                'image': book.image.url if book.image else ''
            }, status=201)
    
    
    class BookAPIView(View):
        def get(self, request, pk):
            """
            获取单个图书信息
            路由: GET  /books/<pk>/
            """
            try:
                book = BookInfo.objects.get(pk=pk)
            except BookInfo.DoesNotExist:
                return HttpResponse(status=404)
    
            return JsonResponse({
                'id': book.id,
                'btitle': book.btitle,
                'bpub_date': book.bpub_date,
                'bread': book.bread,
                'bcomment': book.bcomment,
                'image': book.image.url if book.image else ''
            })
    
        def put(self, request, pk):
            """
            修改图书信息
            路由: PUT  /books/<pk>
            """
            try:
                book = BookInfo.objects.get(pk=pk)
            except BookInfo.DoesNotExist:
                return HttpResponse(status=404)
    
            json_bytes = request.body
            json_str = json_bytes.decode()
            book_dict = json.loads(json_str)
    
            # 此处详细的校验参数省略
    
            book.btitle = book_dict.get('btitle')
            book.bpub_date = datetime.strptime(book_dict.get('bpub_date'), '%Y-%m-%d').date()
            book.save()
    
            return JsonResponse({
                'id': book.id,
                'btitle': book.btitle,
                'bpub_date': book.bpub_date,
                'bread': book.bread,
                'bcomment': book.bcomment,
                'image': book.image.url if book.image else ''
            })
    
        def delete(self, request, pk):
            """
            删除图书
            路由: DELETE /books/<pk>/
            """
            try:
                book = BookInfo.objects.get(pk=pk)
            except BookInfo.DoesNotExist:
                return HttpResponse(status=404)
    
            book.delete()
    
            return HttpResponse(status=204)
    # urls.py
    
    urlpatterns = [
        url(r'^books/$', views.BooksAPIVIew.as_view()),
        url(r'^books/(?P<pk>d+)/$', views.BookAPIView.as_view())
    ]
    #model.py
    class BookInfo(models.Model):

    bittle = models.CharField(max_length=20, verbose_name='名称')
    bpub_date = models.DateField(verbose_name='发布日期', null=True)
    bread = models.IntegerField(default=0, verbose_name='阅读量')
    bcomment = models.IntegerField(default=0, verbose_name='评论量')
    image = models.ImageField(upload_to='booktest', verbose_name='图片', null=True)

     
  • 相关阅读:
    gvim e303 无法打开 “[未命名]“的交换文件,恢复将不可能
    AspectJ获取方法注解的信息
    type parameters of <T>T cannot be determined; no unique maximal instance exists for type variable T with upper bounds int,java.lang.Object
    MySQL@淘宝 资料分享
    MySQL的语句执行顺序
    关于HttpClient上传中文乱码的解决办法
    使用IntelliJ IDEA查看类的继承关系图形
    javax.net.ssl.SSLException: Certificate doesn't match any of the subject alternative names
    Failed to process import candidates for configuration class [com.simple.....]
    安装npm及cnpm(Windows)
  • 原文地址:https://www.cnblogs.com/wwr3569/p/14279766.html
Copyright © 2011-2022 走看看