example.django.rest_framework.tutorial
1.0.0
我對以下教程的實踐:
此Django Web應用程序需要大量python附加軟件包,請執行以下命令:
$ pip install -r requirements.txt --timeout 120$ python manage.py makemigrations
$ python manage.py migrate此Django Web應用需要a來創建Django Admin用戶,訪問和管理Admin界面,請執行以下命令:
提示:對於此本地安裝,將用戶用作管理員和密碼作為密碼123 。
$ python manage.py createsuperuser --email [email protected] --username admin
Password:
Password (again):
Superuser created successfully.您需要運行Django服務器,請執行以下命令:
$ python manage.py runserver使用以下URL打開您的Web瀏覽器:http://0.0.0.0:8000/,然後查看Django Web應用程序。
使用以下URL打開您的Web瀏覽器:http://0.0.0.0:8000/admin/並查看Django Admin界面,使用用戶管理員和密碼password123 。
提示:請添加兩個組,兩個用戶,然後將用戶添加到一個組中。
有關QuickStart應用的添加數據,請訪問以下URL:http:// localhost:8000/admin/quickstart/
有關摘要應用的添加數據,請訪問以下URL:http:// localhost:8000/admin/smippets/
您有許多API休息進行測試,現在使用curl等工具,請執行以下命令:
要測試用戶API REST,請執行以下命令:
$ curl -H ' Accept: application/json; indent=4 ' -u admin:password123 http://127.0.0.1:8000/users/
[
{
" url " : " http://127.0.0.1:8000/users/4/ " ,
" username " : " rocio " ,
" email " : " [email protected] " ,
" groups " : [
" http://127.0.0.1:8000/groups/3/ "
]
},
{
" url " : " http://127.0.0.1:8000/users/3/ " ,
" username " : " leonardo " ,
" email " : " [email protected] " ,
" groups " : [
" http://127.0.0.1:8000/groups/2/ "
]
},
{
" url " : " http://127.0.0.1:8000/users/1/ " ,
" username " : " admin " ,
" email " : " [email protected] " ,
" groups " : []
}
]為了測試組API休息,請執行以下命令:
$ curl -H ' Accept: application/json; indent=4 ' -u admin:password123 http://127.0.0.1:8000/groups/
[
{
" url " : " http://127.0.0.1:8000/groups/1/ " ,
" name " : " Administrators "
},
{
" url " : " http://127.0.0.1:8000/groups/2/ " ,
" name " : " Plone "
},
{
" url " : " http://127.0.0.1:8000/groups/3/ " ,
" name " : " Botana "
}
]要測試事件API休息,請執行以下命令:
$ curl -H ' Accept: application/json; indent=4 ' -u admin:password123 http://127.0.0.1:8000/events/
[
{
" name " : " New Plone release for 2018 " ,
" description " : " Plone will be release a new version at PloneConf 2018 " ,
" room_number " : 201,
" start_date " : " 2018-02-13T19:42:31Z " ,
" finish_date " : " 2018-02-14T19:42:37Z "
},
{
" name " : " New Django release " ,
" description " : " Django will be release a new version at DjangoConf 2018 " ,
" room_number " : 101,
" start_date " : " 2018-02-12T19:40:59Z " ,
" finish_date " : " 2018-02-12T20:41:04Z "
}
]要測試博客文章API休息,請執行以下命令:
$ curl -H ' Accept: application/json; indent=4 ' -u admin:password123 http://127.0.0.1:8000/blog-post/
[
{
" title " : " Django project will be release a new version soon " ,
" content " : " Django will be release a new version at DjangoConf 2018 "
},
{
" title " : " Plone is Cool " ,
" content " : " Plone is still in fashion with the latest Web technologies "
}
]要測試評論API休息,請執行以下命令:
$ curl -H ' Accept: application/json; indent=4 ' -u admin:password123 http://127.0.0.1:8000/comments/
[
{
" email " : " [email protected] " ,
" content " : " I want to dowload and test it " ,
" created " : " 2018-02-03T19:46:43Z "
},
{
" email " : " [email protected] " ,
" content " : " #FuckYou Djanguero " ,
" created " : " 2018-02-03T19:22:02Z "
},
{
" email " : " [email protected] " ,
" content " : " You are very pathetic you are still using Plone " ,
" created " : " 2018-02-03T19:21:33Z "
}
]對於測試摘要列表API休息,請執行以下命令:
$ curl -H ' Accept: application/json; indent=4 ' -u admin:password123 http://localhost:8000/snippets/list/
[{ " id " :1, " title " : " " , " code " : " foo = " bar " n " , " linenos " :false, " language " : " python " , " style " : " friendly " },{ " id " :2, " title " : " " , " code " : " print " hello, world " n " , " linenos " :false, " language " : " python " , " style " : " friendly " },{ " id " :3, " title " : " " , " code " : " print " hello, world " " , " linenos " :false, " language " : " python " , " style " : " friendly " }]要測試片段詳細信息API休息,請執行以下命令:
$ curl -H ' Accept: application/json; indent=4 ' -u admin:password123 http://localhost:8000/snippets/detail/1/
{ " id " :1, " title " : " " , " code " : " foo = " bar " n " , " linenos " :false, " language " : " python " , " style " : " friendly " }為了進行一些練習,請執行以下命令:
$ python manage.py shell
Python 2.7.13 (default, Nov 24 2017, 17:33:09)
[GCC 6.3.0 20170516] on linux2
Type " help " , " copyright " , " credits " or " license " for more information.
(InteractiveConsole)
>>> 在Python Interactive Console,請執行以下命令:
> >>
>> > # Serializers tutorial section
>> >
>> > # Declaring Serializers section
>> >
>> > from datetime import datetime
> >>
>> > class Comment ( object ):
... def __init__ ( self , email , content , created = None ):
... self . email = email
... self . content = content
... self . created = created or datetime . now ()
...
> >> comment = Comment ( email = '[email protected]' , content = 'THIS IS A TESTING COMMENT' )
> >> comment
< Comment object at 0x7f110aa91510 >
> >> from rest_framework import serializers
> >> class CommentSerializer ( serializers . Serializer ):
... email = serializers . EmailField ()
... content = serializers . CharField ( max_length = 200 )
... created = serializers . DateTimeField ()
...
> >>
>> > # Serializing objects section
>> >
>> > serializer = CommentSerializer ( comment )
> >> serializer
CommentSerializer ( < Comment object > ):
email = EmailField ()
content = CharField ( max_length = 200 )
created = DateTimeField ()
>> > serializer . data
{ 'email' : u'[email protected]' , 'content' : u'THIS IS A TESTING COMMENT' , 'created' : '2018-02-03T14:51:39.574410' }
> >> from rest_framework . renderers import JSONRenderer
> >> json = JSONRenderer (). render ( serializer . data )
> >> json
'{"email":"[email protected]","content":"THIS IS A TESTING COMMENT","created":"2018-02-03T14:51:39.574410"}'
> >>
>> > # Deserializing objects section
>> >
>> > from django . utils . six import BytesIO
> >> from rest_framework . parsers import JSONParser
> >>
>> > stream = BytesIO ( json )
> >> data = JSONParser (). parse ( stream )
> >> data
{ u'content' : u'THIS IS A TESTING COMMENT' , u'email' : u'[email protected]' , u'created' : u'2018-02-03T15:16:41.744807' }
> >>
>> > serializer = CommentSerializer ( data = data )
> >> serializer . is_valid ()
True
> >> serializer . validated_data
OrderedDict ([( u'email' , u'[email protected]' ), ( u'content' , u'THIS IS A TESTING COMMENT' ), ( u'created' , datetime . datetime ( 2018 , 2 , 3 , 14 , 51 , 39 , 574410 , tzinfo = < django . utils . timezone . LocalTimezone object at 0x7f1109752c90 > ))])
> >>
>> > # Saving instances section
>> >
>> > class CommentSerializer ( serializers . Serializer ):
...
... email = serializers . EmailField ()
... content = serializers . CharField ( max_length = 200 )
... created = serializers . DateTimeField ()
... def create ( self , validated_data ):
... return Comment ( ** validated_data )
... def update ( self , instance , validated_data ):
... instance . email = validated_data . get ( 'email' , instance . email )
... instance . content = validated_data . get ( 'content' , instance . content )
... instance . created = validated_data . get ( 'created' , instance . created )
... return instance
...
> >>
>> > serializer = CommentSerializer ( data = data )
> >> serializer = CommentSerializer ( comment , data = data )
> >>
>> > # Validation section
>> >
>> > serializer = CommentSerializer ( data = { 'email' : 'foobar' , 'content' : 'baz' })
> >> serializer . is_valid ()
False
> >> serializer . errors
{ 'email' : [ u'Enter a valid email address.' ], 'created' : [ u'This field is required.' ]}
> >>
>> > serializer . is_valid ( raise_exception = True )
Traceback ( most recent call last ):
File "<console>" , line 1 , in < module >
File "/home/leonardo/virtualenv/django27/local/lib/python2.7/site-packages/rest_framework/serializers.py" , line 245 , in is_valid
raise ValidationError ( self . errors )
ValidationError : { 'email' : [ u'Enter a valid email address.' ], 'created' : [ u'This field is required.' ]}
> >>
>> > # Field-level validation section
>> >
>> > from rest_framework import serializers
> >> class BlogPostSerializer ( serializers . Serializer ):
... title = serializers . CharField ( max_length = 100 )
... content = serializers . CharField ()
... def validate_title ( self , value ):
... """
... Check that the blog post is about Django.
... """
... if 'django' not in value . lower ():
... raise serializers . ValidationError ( "Blog post is not about Django" )
... return value
...
>> >
>> > # Object-level validation section
>> >
>> > class EventSerializer ( serializers . Serializer ):
... description = serializers . CharField ( max_length = 100 )
... start = serializers . DateTimeField ()
... finish = serializers . DateTimeField ()
... def validate ( self , data ):
... """
... Check that the start is before the stop.
... """
... if data [ 'start' ] > data [ 'finish' ]:
... raise serializers . ValidationError ( "finish must occur after start" )
... return data
...
>> >
>> > # Validators section
>> >
>> > def multiple_of_ten ( value ):
... if value % 10 != 0 :
... raise serializers . ValidationError ( 'Not a multiple of ten' )
...
>> > class GameRecord ( serializers . Serializer ):
... score = serializers . IntegerField ( validators = [ multiple_of_ten ])
...
>> >