欢迎来访我的博客。

Django Rest Framework学习总结:快速入门

Django 小张哥哥 1031浏览 48评论

前面的几篇关于REST framework的内容,从刚开始的序列化到框架的几个重要的模块,再到基于类的视图,再到认证和权限,后面还有给我们的API添加链接,以及最后关于ViewSet和Router的内容。这算是一个比较系统的,比较完善的学习过程。如果只是简单使用REST framework,不想花费很多精力的化,可以直接通过本文内容快速入门Django REST framework。

下面我们创建一个简单的API允许管理员用户去编辑系统的用户和组。


项目设置

创建一个Django项目,命名为quick_start, 然后新建一个app,命名为myapp:

# 创建项目文件夹
mkdir quickstartcd quick_start
# 创建一个虚拟环境
python3 -m venv env
source env/bin/activate 

# 在虚拟环境中安装django, djangorestframework
pip install django
pip install djangorestframework

# 新建一个项目,并在项目下新建一个app
django-admin startproject quickstart .  
cd quickstart
django-admin startapp myapp
cd ..

当创建完成后,我们的文件夹结构如下:

$ pwd<some path>/quickstart
$ find .../manage.py
./quickstart
./quickstart/__init__.py
./quickstart/myapp
./quickstart/myapp/__init__.py
./quickstart/myapp/admin.py
./quickstart/myapp/apps.py
./quickstart/myapp/migrations
./quickstart/myapp/migrations/__init__.py
./quickstart/myapp/models.py
./quickstart/myapp/tests.py
./quickstart/myapp/views.py
./quickstart/settings.py
./quickstart/urls.py
./quickstart/wsgi.py

然后,同步一下数据库:

python manage.py makemigrations
python manage.py migrate

我们现在先创建一个超级用户,后面会需要用到:

python manage.py createsuperuser --email zhangsan@123.com --username zhangsan

下面,我们就可以进入到我们的app目录下进行编码了。


序列化器

首先,我们需要定义几个序列化器,我们直接在myapp目录下新建一个文件quick_start/myapps/serializers.py,我们用序列化器来进行数据库中的数据进行展示和操作。

from django.contrib.auth.models import User, Group
from rest_framework import serializers


class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'groups')

     
     
class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ('url', 'name')

在上面的代码中,我们使用了HyperlinkedModelSerializer。当然有可以使用主键(primary key)或者其它的关系。不过使用超链接更符合REST的设计。


视图

现在,我们可以写一下视图函数了。打开quick_start/myapp/views.py文件,编辑:

from django.contrib.auth.models import User, Group
from rest_framework import viewsets

from .serializers import UserSerializer, GroupSerializer


class UserViewSet(viewsets.ModelViewSet):
    """
    允许查看或者编辑user对象的API
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer
    
    
class GroupSerializer(viewsets.ModelViewSet):
    """
    允许查看或者编辑group对象的API
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer

我们这边并不是针对User和Group写多个视图veiws,而是使用了ViewSet类,这个类整合了我们常见的多种操作行为,比如我们在view视图中常写的get, post, put,delete等操作。
如果有需要的话,我们也可以把它们分别写成单独的视图。不过还是最好使用ViewSet,ViewSet能让我们的代码更加简洁。


URLs

然后,我们可以设置我们的API的URL了。在quick_start/urls.py文件中:

from django.urls import path, include
from rest_framework.routers import DefaultRouter

from myapp import views

router = DefaultRouter()router.register('users', views.UserViewSet)
router.register('groups', views.GroupViewSet)

urlpatterns = [
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework', namespace='rest_framework'))
]

分页

如果返回的结果很多的话,为了有良好的显示效果,我们最好对我们的API进行分页显示。分页显示的功能也很容易实现,只需要在我们项目下的quick_start/setttings.py文件中添加如下内容:

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10}

其中上面的这个名字为REDT_FRAMEWORK的字典是用于存储我们的REST framework的所有全局配置项。


Settings.py设置

我们还需要在我们的quick_start/setttings.py文件中的INSTALLED_APPS字典中添加rest_framework。

INSTALLED_APPS = [
    ...
    'rest_framework',]

现在,我们所有的工作就已经完成了。


测试API

现在我们可以来测试一下我们写的API了。
首先运行一下我们的服务器:

python manage.py runserver

我们可以直接在命令行中通过一些工具来访问我们的API,比如curl或者httpie
如下是通过httpie:

>>> http -a zhangsan:123456 GET http://127.0.0.1:8000/users/
HTTP/1.1 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Length: 247
Content-Type: application/json
Date: Wed, 17 Jul 2019 04:39:40 GMT
Server: WSGIServer/0.2 CPython/3.6.0
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN

{
    "count": 2,
    "next": null,
    "previous": null,
    "results": [
        {
            "email": "zhangsan@123.com",
            "groups": [],
            "url": "http://127.0.0.1:8000/users/1/",
            "username": "zhangsan"
        },
        {
            "email": "lisi@123.com",
            "groups": [],
            "url": "http://127.0.0.1:8000/users/2/",
            "username": "lisi"
        }
    ]
}

我们还可以直接通过浏览器访问我们的URL,http://127.0.0.1/users/。
访问如下图:

django_rest_framework_qs_1.png

在使用浏览器访问时候,我们还需要注意页面右上角的Login选项。

此时由于我们还没有设置查看和修改的权限,在未授权的情况下就可以编辑或者新增内容,这样是不安全的。

如果需要设置权限,可以查看下面这篇文章:

查看REST framework关于认证和权限的内容



本文中的源码可以在Github上查看。点我查看本文源码







转载请注明:禅思 » Django Rest Framework学习总结:快速入门?

喜欢 (2) or 分享 (0)

我的个人微信公众号,欢迎关注

扫码或搜索:Python后端开发Django

Python后端开发Django

微信公众号 扫一扫关注

结交朋友、一起学习,一起进步。

科波之主

QQ号 386046154 立即加入

添加微信,进行技术交流

专注技术交流, 一同成长进步

我的微信号

如果您喜欢我的文章,感觉我的文章对您有帮助,请狠狠点击下面

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
(48)个小伙伴在吐槽
    1. https://getcreditscorefast.com/ experian credit report chase credit score experian credit free credit report online credit score
      FressyArraday 2020-12-16 23:26:13 回复
      • САмое эффективное для продаж - Pinterest. Сотни Продаж на Etsy, amazon, ebay, shopify за 2 месяца при ср.цене чека 300 usd https://youtu.be/GNOZtXGGM-I
        JamesCet 2020-12-22 12:28:25 回复
        • generic viagra overnight delivery gneeric viagra online sildenafil citrate tablets viagra http://llviabest.com/ - viagra sold in plipeans ’
          Jdbxamomi 2021-01-29 02:03:17 回复
          • viagra gel sachets in australia buy wholesale viagra how to take viagra http://genqpviag.com/ - viagra 100 mg generic ’
            Lbgamomi 2021-01-29 11:36:32 回复
            • natural source of viagra buy viagra online discover card viagra 50mg http://llviabest.com/ - viagra without prescription yahoo answers ’
              Jdbxamomi 2021-02-02 19:00:26 回复
              • singapore viagra viagra low cost viagra in without persription
                Nncsaddew 2021-02-08 19:23:13 回复
                • online medicine to buy 92126 viagra online medicine tablets shopping
                  Lbsxamomi 2021-02-08 20:31:27 回复
                  • canadian prescriptions online canadian drug canadian pharma companies
                    Kbcxchit 2021-02-08 21:40:13 回复
                    • best seller cialis cialis generic uk buy cialis
                      Aqcfsilkdisee 2021-02-09 13:12:43 回复
                      • aarp recommended canadian pharmacies Brand Levitra best online pharmacies no prescription
                        Jbbvamomi 2021-02-09 22:33:01 回复
                        • canadian pharmacy viagra generic overseas pharmacy forum canadian pharmacy drugs online
                          Jbnbelelm 2021-02-10 00:02:43 回复
                          • payday cash advance nj money loan baguio navy federal cash advance limit
                            Ahbzamomi 2021-02-11 02:05:51 回复
                            • viagra usa viagra 200mg viagra for sale in melbourne
                              Fvfcaddew 2021-02-11 10:23:05 回复
                              • payday loans venice ca money loans in san francisco cash n go title loans piedmont sc
                                Fqbbamomi 2021-02-12 18:42:41 回复
                                • payday loan in 15 minutes direct lenders best payday loan in georgia assurance money loan
                                  Kvaxchit 2021-02-16 05:59:21 回复
                                  • http://bio-catalyst.com/ - cefadroxil tablets order clindamycin buy flagyl online order chloromycetin
                                    Jamesfer 2021-02-16 10:24:44 回复
                                    • kann man mit cialis lГ¤nger cialis pharmaceutical name venta de cialis en ecuador
                                      Labxamomi 2021-02-16 14:13:42 回复
                                      • order cheap viagra sildenafil nz pharmacy female viagra tablet in india online purchase
                                        Nbnhaddew 2021-02-16 22:45:42 回复
                                        • cash advance zales card advance america cash advance hours of operation payday advance fort myers fl
                                          Jbnvelelm 2021-02-17 12:48:55 回复
                                          • play slots online https://casinorealmoneybigbet.com/ - slot games online casinos best online casino play slots online
                                            FressyArraday 2021-02-17 15:00:34 回复
                                            • online slot games https://casinorealmoneybigbet.com/ - real casino slots vegas slots online slot games slots games
                                              FressyArraday 2021-02-17 20:05:17 回复
                                              • 20 mg cialis canada cialis bydgoszcz cialis for women how does it work
                                                Jbbnamomi 2021-02-17 21:13:31 回复
                                                • switching from tamsulosin to cialis cialis patent expiration cialis without a doctor's prescription https://edplsgeneric.com/ cialis online cialis dosage cialis coupons printable
                                                  Kennethamigh 2021-02-17 22:11:20 回复
                                                  • Very high quality article free robux
                                                    Donalderype 2021-02-18 06:12:37 回复
                                                    • viagra online no prescription viagra without prescription australia where can i buy viagra in canada
                                                      Abcfsilkdisee 2021-02-18 07:44:53 回复
                                                      • when is the best time to take cialis cialis online tiujana cialis https://edplsgeneric.com/ safe alternatives to viagra and cialis coupons for cialis side effects for cialis
                                                        Kennethamigh 2021-02-18 14:02:00 回复
                                                        • generic cialis coming out when will cialis go generic cialis at a discount price https://edplsgeneric.com/ cialis online daily use of cialis cialis 20 image
                                                          Kennethamigh 2021-02-19 06:04:52 回复
                                                          • cialis delivered in 24 hours http://llecialisjaw.com/ cialis indien bezahlung mit paypal
                                                            Fbsgaddew 2021-02-19 10:35:47 回复
                                                            • cialis coupons printable real cialis online with paypal cialis 20 image https://edplsgeneric.com/ which is better - cialis or viagra how long does 20mg cialis keep in system cialis dosage 40 mg dangerous
                                                              Kennethamigh 2021-02-20 12:13:01 回复
                                                              • lowest cialis prices taking l-citrulline and cialis together cialis lowest price http://cialisirt.com/ liquid cialis source reviews cialis dosages buy cialis online
                                                                Kennethamigh 2021-02-21 04:56:56 回复
                                                                • does cialis lower your blood pressure best liquid cialis is generic cialis safe https://edplsgeneric.com/ generic cialis at walgreens pharmacy cost of cialis price of cialis
                                                                  Kennethamigh 2021-02-23 07:28:28 回复
                                                                  • expired cialis 3 years cialis erection penis interactions for cialis http://cialisirt.com/ daily use of cialis cialis 5mg coupon generic names for cialis and viagra
                                                                    Kennethamigh 2021-02-24 00:56:38 回复
                                                                    • п»їcialis cialis 20 mg how to get cialis samples
                                                                      Buddyevera 2021-02-24 06:52:18 回复
                                                                      • cialis money order cialis patent expiration cialis lowest price 20mg http://cialisirt.com/ canadien cialis hard erections cialis cialis vs levitra
                                                                        Kennethamigh 2021-02-24 18:18:58 回复
                                                                        • cialis canada free cialis medication for providers viagra vs cialis http://cialisirt.com/ buy cialis fastest delivery of cialis buying online cialis side effects
                                                                          Kennethamigh 2021-02-25 10:28:09 回复
                                                                          • warnings for cialis cialis coupons buy cialis https://edplsgeneric.com/ side effects for cialis $200 cialis coupon cialis coupons
                                                                            Kennethamigh 2021-02-26 04:34:20 回复
                                                                            • cheapest cialis web prices daily use cialis cost canada cialis https://edplsgeneric.com/ generic cialis bitcoin safe alternatives to viagra and cialis price of cialis
                                                                              Kennethamigh 2021-02-26 18:52:55 回复
                                                                              • cialis vs viagra buy cialis best liquid cialis http://cialisirt.com/ coupon for cialis by manufacturer how long does 20mg cialis keep in system when is the best time to take cialis
                                                                                Kennethamigh 2021-02-27 06:50:39 回复
                                                                                • coupons for cialis cialis coupon code cialis without a doctor prescription https://edplsgeneric.com/ coupon for cialis by manufacturer warnings for cialis cialis vs levitra
                                                                                  Kennethamigh 2021-02-27 18:38:07 回复
                                                                                  • cialis before and after taking l-citrulline and cialis together free cialis medication for providers https://edplsgeneric.com/ does cialis make you bigger cialis maximum dosage buy cialis online canadian
                                                                                    Kennethamigh 2021-02-28 06:29:18 回复
                                                                                    • generic cialis bitcoin cialis going generic in 2019 in us cialis pills http://cialisirt.com/ cialis for daily use cialis tadalafil 20 mg cialis coupons printable
                                                                                      Kennethamigh 2021-02-28 17:49:53 回复
                                                                                      • which is better - cialis or viagra samples of cialis cialis before and after https://edplsgeneric.com/ п»їcialis walgreens price for cialis 20mg cialis prices
                                                                                        Kennethamigh 2021-03-01 05:07:11 回复
                                                                                        • generic cialis no doctor's prescription take cialis with or without food generic cialis coming out https://edplsgeneric.com/ buy cialis free cialis medication for providers 30ml liquid cialis
                                                                                          Kennethamigh 2021-03-01 16:41:59 回复
                                                                                          • fda warning list cialis generic cialis tadalafil cost of cialis 20mg tablets http://cialisirt.com/ cheap cialis does cialis lower your blood pressure otc cialis
                                                                                            Kennethamigh 2021-03-02 04:45:29 回复
                                                                                            • walgreens viagra substitute does viagra make you harder viagra on steroids
                                                                                              Kndnchit 2021-03-02 09:43:44 回复
                                                                                              • cheap cialis generic cialis - generic cialis 10mg
                                                                                                Nbmoaddew 2021-03-03 12:18:05 回复
                                                                                                • tadalafil 40: http://tadalafilonline20.com/ tadalafil 40
                                                                                                  MarcosKix 2021-03-04 23:10:27 回复
                                                                                                  • tadalafil online 20 tadalafil online 40 mg tadalafil
                                                                                                    Wesleyviord 2021-03-05 21:33:24 回复