Commit 666d57fd authored by Давид Ли's avatar Давид Ли

lesson 68

parent db6fb61e
from django.contrib import admin
# Register your models here.
from django.apps import AppConfig
class ApiConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'api'
from django.db import models
# Create your models here.
from django.test import TestCase
# Create your tests here.
from django.urls import path
from api import views
urlpatterns = [
path('echo', views.echo_view),
path('articles', views.articles_view),
]
import json
from django import http
from django.core.serializers import serialize, deserialize
from django.http import JsonResponse, HttpResponse
from datetime import datetime
from django.views.decorators.csrf import ensure_csrf_cookie
from web.models import Article
@ensure_csrf_cookie
def echo_view(request, *args, **kwargs):
answer = {
'time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'method': request.method,
}
print(request.body)
if request.method == 'POST':
if request.body:
answer['content'] = json.loads(request.body)
return JsonResponse(answer)
def articles_view(request, *args, **kwargs):
if request.method == 'GET':
qs = Article.objects.values()
return JsonResponse(list(qs), safe=False)
elif request.method == 'POST':
if request.body:
try:
article = Article.objects.create(**json.loads(request.body))
except TypeError:
return http.HttpResponseBadRequest('invalid request body')
return JsonResponse({'id': article.id, 'title': article.title, 'text': article.text})
else:
return JsonResponse(status=400, data={'error': 'No data provided!'})
......@@ -42,7 +42,8 @@ INSTALLED_APPS = [
'django_extensions',
'web',
'accounts'
'accounts',
'api',
]
MIDDLEWARE = [
......
......@@ -24,6 +24,7 @@ urlpatterns = [
path('admin/', admin.site.urls),
path('', views.MainPageRedirectView.as_view()),
path('', include('web.urls')),
path('auth/', include('accounts.urls'))
path('auth/', include('accounts.urls')),
path('api/', include('api.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment