Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Django Rest Framework 3.9.1 Quickstart Tutorial

NotificationsYou must be signed in to change notification settings

macagua/example.django.rest_framework.tutorial

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

47 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

My practices about the following tutorials:

Installation

This Django Web app need a lot of Python extras packages, please execute the following command:

$ pip install -r requirements.txt --timeout 120

Build the Django Web app DB

$ python manage.py makemigrations$ python manage.py migrate

Create Django Admin User

This Django Web app need a to create a Django Admin User, for access and manager the Admin interface, please execute the following command:

Tip: for this local installation use the user asadmin and password aspassword123.

$ python manage.py createsuperuser --email admin@mail.com --username adminPassword: Password (again): Superuser created successfully.

Run the Django Web app

You need to run the Django server, please execute the following command:

$ python manage.py runserver
  • Open your web browser with the following URL:http://0.0.0.0:8000/ and see the Django Web app.

  • Open your web browser with the following URL:http://0.0.0.0:8000/admin/ and see the Django Admin Interface, use the useradmin and passwordpassword123.

Tip: PLEASE add twogroups, twousers and later add a user into a group.

Quickstart App

For add data forQuickstart App, please access to the following URL:http://localhost:8000/admin/quickstart/

Snippets App

For add data forSnippets App, please access to the following URL:http://localhost:8000/admin/snippets/

Testing the API

You have many APIs Rest for testing, now access to the APIs, both from the command-line, using tools likecurl, please execute the following command:

Users endpoint

For testing theusers API Rest, please execute the following command:

$ 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":"rociogonzalez@mail.com","groups": ["http://127.0.0.1:8000/groups/3/"        ]    },    {"url":"http://127.0.0.1:8000/users/3/","username":"leonardo","email":"leonardo@mail.com","groups": ["http://127.0.0.1:8000/groups/2/"        ]    },    {"url":"http://127.0.0.1:8000/users/1/","username":"admin","email":"admin@mail.com","groups": []    }]

Groups endpoint

For testing thegroups API Rest, please execute the following command:

$ 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"    }]

Events endpoint

For testing theevents API Rest, please execute the following command:

$ 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"    }]

Blog post endpoint

For testing theblog post API Rest, please execute the following command:

$ 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"    }]

Comments endpoint

For testing thecomments API Rest, please execute the following command:

$ curl -H'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/comments/[    {"email":"leonardo@mail.com","content":"I want to dowload and test it","created":"2018-02-03T19:46:43Z"    },    {"email":"leonardoc@plone.org","content":"#FuckYou Djanguero","created":"2018-02-03T19:22:02Z"    },    {"email":"djangueroguy@djangoproject.com","content":"You are very pathetic you are still using Plone","created":"2018-02-03T19:21:33Z"    }]

Snippets list endpoint

For testing thesnippets list API Rest, please execute the following command:

$ 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"}]

Snippets detail endpoint

For testing thesnippets detail API Rest, please execute the following command:

$ 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"}

Django Interactive Console

For make some practices the Django ORM, please execute the following command:

$ python manage.py shellPython 2.7.13 (default, Nov 24 2017, 17:33:09) [GCC 6.3.0 20170516] on linux2Type"help","copyright","credits" or"license"for more information.(InteractiveConsole)>>>

At Python Interactive Console, please execute the following command:

>>>>>># Serializers tutorial section>>>>>># Declaring Serializers section>>>>>>fromdatetimeimportdatetime>>>>>>classComment(object):...def__init__(self,email,content,created=None):...self.email=email...self.content=content...self.created=createdordatetime.now()...>>>comment=Comment(email='leonardo@mail.com',content='THIS IS A TESTING COMMENT')>>>comment<Commentobjectat0x7f110aa91510>>>>fromrest_frameworkimportserializers>>>classCommentSerializer(serializers.Serializer):...email=serializers.EmailField()...content=serializers.CharField(max_length=200)...created=serializers.DateTimeField()...>>>>>># Serializing objects section>>>>>>serializer=CommentSerializer(comment)>>>serializerCommentSerializer(<Commentobject>):email=EmailField()content=CharField(max_length=200)created=DateTimeField()>>>serializer.data{'email':u'leonardo@mail.com','content':u'THIS IS A TESTING COMMENT','created':'2018-02-03T14:51:39.574410'}>>>fromrest_framework.renderersimportJSONRenderer>>>json=JSONRenderer().render(serializer.data)>>>json'{"email":"leonardo@mail.com","content":"THIS IS A TESTING COMMENT","created":"2018-02-03T14:51:39.574410"}'>>>>>># Deserializing objects section>>>>>>fromdjango.utils.siximportBytesIO>>>fromrest_framework.parsersimportJSONParser>>>>>>stream=BytesIO(json)>>>data=JSONParser().parse(stream)>>>data{u'content':u'THIS IS A TESTING COMMENT',u'email':u'leonardo@mail.com',u'created':u'2018-02-03T15:16:41.744807'}>>>>>>serializer=CommentSerializer(data=data)>>>serializer.is_valid()True>>>serializer.validated_dataOrderedDict([(u'email',u'leonardo@mail.com'), (u'content',u'THIS IS A TESTING COMMENT'), (u'created',datetime.datetime(2018,2,3,14,51,39,574410,tzinfo=<django.utils.timezone.LocalTimezoneobjectat0x7f1109752c90>))])>>>>>># Saving instances section>>>>>>classCommentSerializer(serializers.Serializer):... ...email=serializers.EmailField()...content=serializers.CharField(max_length=200)...created=serializers.DateTimeField()...defcreate(self,validated_data):...returnComment(**validated_data)...defupdate(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)...returninstance...>>>>>>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 (mostrecentcalllast):File"<console>",line1,in<module>File"/home/leonardo/virtualenv/django27/local/lib/python2.7/site-packages/rest_framework/serializers.py",line245,inis_validraiseValidationError(self.errors)ValidationError: {'email': [u'Enter a valid email address.'],'created': [u'This field is required.']}>>>>>># Field-level validation section>>>>>>fromrest_frameworkimportserializers>>>classBlogPostSerializer(serializers.Serializer):...title=serializers.CharField(max_length=100)...content=serializers.CharField()...defvalidate_title(self,value):..."""...         Check that the blog post is about Django....         """...if'django'notinvalue.lower():...raiseserializers.ValidationError("Blog post is not about Django")...returnvalue...>>>>>># Object-level validation section>>>>>>classEventSerializer(serializers.Serializer):...description=serializers.CharField(max_length=100)...start=serializers.DateTimeField()...finish=serializers.DateTimeField()...defvalidate(self,data):..."""...         Check that the start is before the stop....         """...ifdata['start']>data['finish']:...raiseserializers.ValidationError("finish must occur after start")...returndata...>>>>>># Validators section>>>>>>defmultiple_of_ten(value):...ifvalue%10!=0:...raiseserializers.ValidationError('Not a multiple of ten')...>>>classGameRecord(serializers.Serializer):...score=serializers.IntegerField(validators=[multiple_of_ten])...>>>

Reference

Releases

No releases published

Packages

No packages published

Contributors2

  •  
  •  

Languages


[8]ページ先頭

©2009-2025 Movatter.jp