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

Commit ad1d04b

Browse files
committed
Added snippets app
1 parent e86f190 commit ad1d04b

File tree

12 files changed

+172
-3
lines changed

12 files changed

+172
-3
lines changed

‎README.md

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
# django_rest_framework_tutorial
22

3-
My practices about [Django 1.9 Project tutorial](https://docs.djangoproject.com/en/1.9/intro/) and [Django Rest Framework 3.6.4 tutorial Quickstart](http://www.django-rest-framework.org/tutorial/quickstart/).
3+
My practices about the following tutorials:
4+
5+
- [Django 1.9 Project tutorial](https://docs.djangoproject.com/en/1.9/intro/).
6+
- [Django Rest Framework 3.6.4 tutorial Quickstart](http://www.django-rest-framework.org/tutorial/quickstart/).
7+
- [Desarrollo de un API REST con Django REST framework, tutorial 1: Serialización](http://jonathanpumares.com/desarrollo-de-un-api-rest-con-django-rest-framework-tutorial-1-serializacion/).
48

59
## Installation
610

@@ -43,6 +47,14 @@ $ python manage.py runserver
4347

4448
**Tip:** PLEASE add two **groups**, two **users** and later add a user into a group.
4549

50+
### Quickstart App
51+
52+
For add data for *Quickstart* App, please access to the following URL: [http://localhost:8000/admin/quickstart/](http://localhost:8000/admin/quickstart/)
53+
54+
### Snippets App
55+
56+
For add data for *Snippets* App, please access to the following URL: [http://localhost:8000/admin/snippets/](http://localhost:8000/admin/snippets/)
57+
4658
### Testing the API
4759

4860
You have many APIs Rest for testing, now access to the APIs, both from the command-line, using tools like **curl**, please execute the following command:
@@ -168,6 +180,24 @@ $ curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0
168180
]
169181
```
170182

183+
#### Snippets list endpoint
184+
185+
For testing the **snippets list** API Rest, please execute the following command:
186+
187+
```bash
188+
$ curl -H 'Accept: application/json; indent=4' -u admin:password123 http://localhost:8000/snippets/list/
189+
[{"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"}]
190+
```
191+
192+
#### Snippets detail endpoint
193+
194+
For testing the **snippets detail** API Rest, please execute the following command:
195+
196+
```bash
197+
$ curl -H 'Accept: application/json; indent=4' -u admin:password123 http://localhost:8000/snippets/detail/1/
198+
{"id":1,"title":"","code":"foo = \"bar\"\n","linenos":false,"language":"python","style":"friendly"}
199+
```
200+
171201
## Django Interactive Console
172202
For make some practices the Django ORM, please execute the following command:
173203

@@ -317,3 +347,4 @@ ValidationError: {'email': [u'Enter a valid email address.'], 'created': [u'This
317347

318348
- [Django 1.9 Project tutorial](https://docs.djangoproject.com/en/1.9/intro/).
319349
- [Django Rest Framework 3.6.4 tutorial Quickstart](http://www.django-rest-framework.org/tutorial/quickstart/).
350+
- [Desarrollo de un API REST con Django REST framework, tutorial 1: Serialización](http://jonathanpumares.com/desarrollo-de-un-api-rest-con-django-rest-framework-tutorial-1-serializacion/).

‎snippets/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# -*- coding: utf-8 -*-

‎snippets/admin.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# -*- coding: utf-8 -*-
2+
3+
from django.contrib import admin
4+
5+
# Register your models here.

‎snippets/apps.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# -*- coding: utf-8 -*-
2+
3+
from __future__ import unicode_literals
4+
5+
from django.apps import AppConfig
6+
7+
8+
class SnippetsConfig(AppConfig):
9+
name = 'snippets'

‎snippets/migrations/__init__.py

Whitespace-only changes.

‎snippets/models.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# -*- coding: utf-8 -*-
2+
3+
from __future__ import unicode_literals
4+
5+
from django.db import models
6+
from pygments.lexers import get_all_lexers
7+
from pygments.styles import get_all_styles
8+
9+
LEXERS = [item for item in get_all_lexers() if item[1]]
10+
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
11+
STYLE_CHOICES = sorted((item, item) for item in get_all_styles())
12+
13+
14+
class Snippet(models.Model):
15+
created = models.DateTimeField(auto_now_add=True)
16+
title = models.CharField(max_length=100, blank=True, default='')
17+
code = models.TextField()
18+
linenos = models.BooleanField(default=False)
19+
language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
20+
style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)
21+
22+
class Meta:
23+
verbose_name = "Snippet"
24+
verbose_name_plural = "Snippets"
25+
ordering = ('created',)
26+
27+
def __unicode__(self):
28+
return "%s" % (self.title)
29+
30+
def __str__(self):
31+
return self.title

‎snippets/serializers.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# -*- coding: utf-8 -*-
2+
3+
from django.forms import widgets
4+
from rest_framework import serializers
5+
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
6+
7+
8+
class SnippetSerializer(serializers.ModelSerializer):
9+
class Meta:
10+
model = Snippet
11+
fields = ('id', 'title', 'code', 'linenos', 'language', 'style')

‎snippets/tests.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# -*- coding: utf-8 -*-
2+
3+
from django.test import TestCase
4+
5+
# Create your tests here.

‎snippets/urls.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# -*- coding: utf-8 -*-
2+
3+
from django.conf.urls import url
4+
from snippets import views
5+
6+
urlpatterns = [
7+
url(r'^list/$', views.snippet_list),
8+
url(r'^detail/(?P<pk>[0-9]+)/$', views.snippet_detail),
9+
]

‎snippets/views.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# -*- coding: utf-8 -*-
2+
3+
from django.http import HttpResponse
4+
from django.views.decorators.csrf import csrf_exempt
5+
from rest_framework.renderers import JSONRenderer
6+
from rest_framework.parsers import JSONParser
7+
from snippets.models import Snippet
8+
from snippets.serializers import SnippetSerializer
9+
10+
11+
class JSONResponse(HttpResponse):
12+
"""
13+
An HttpResponse that renders its content into JSON.
14+
"""
15+
def __init__(self, data, **kwargs):
16+
content = JSONRenderer().render(data)
17+
kwargs['content_type'] = 'application/json'
18+
super(JSONResponse, self).__init__(content, **kwargs)
19+
20+
21+
@csrf_exempt
22+
def snippet_list(request):
23+
"""
24+
List all code snippets, or create a new snippet.
25+
"""
26+
if request.method == 'GET':
27+
snippets = Snippet.objects.all()
28+
serializer = SnippetSerializer(snippets, many=True)
29+
return JSONResponse(serializer.data)
30+
31+
elif request.method == 'POST':
32+
data = JSONParser().parse(request)
33+
serializer = SnippetSerializer(data=data)
34+
if serializer.is_valid():
35+
serializer.save()
36+
return JSONResponse(serializer.data, status=201)
37+
return JSONResponse(serializer.errors, status=400)
38+
39+
40+
@csrf_exempt
41+
def snippet_detail(request, pk):
42+
"""
43+
Retrieve, update or delete a code snippet.
44+
"""
45+
try:
46+
snippet = Snippet.objects.get(pk=pk)
47+
except Snippet.DoesNotExist:
48+
return HttpResponse(status=404)
49+
50+
if request.method == 'GET':
51+
serializer = SnippetSerializer(snippet)
52+
return JSONResponse(serializer.data)
53+
54+
elif request.method == 'PUT':
55+
data = JSONParser().parse(request)
56+
serializer = SnippetSerializer(snippet, data=data)
57+
if serializer.is_valid():
58+
serializer.save()
59+
return JSONResponse(serializer.data)
60+
return JSONResponse(serializer.errors, status=400)
61+
62+
elif request.method == 'DELETE':
63+
snippet.delete()
64+
return HttpResponse(status=204)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /