mirror of
https://github.com/olegvodyanov/instalinks.git
synced 2025-12-20 04:37:04 +03:00
70 lines
2.0 KiB
Python
70 lines
2.0 KiB
Python
import json
|
|
from django.http import JsonResponse, HttpResponseNotFound
|
|
from django.shortcuts import render
|
|
from .models import Link
|
|
from django.views.decorators.csrf import csrf_exempt
|
|
|
|
|
|
def index(request):
|
|
"""
|
|
Renders a page that will load the data via JavaScript (AJAX fetch).
|
|
"""
|
|
return render(request, 'links/index.html')
|
|
|
|
|
|
def links_list(request):
|
|
"""
|
|
Return JSON list of all links.
|
|
"""
|
|
if request.method == 'GET':
|
|
all_links = Link.objects.all().values('id', 'url', 'watched')
|
|
return JsonResponse(list(all_links), safe=False)
|
|
else:
|
|
return JsonResponse({'error': 'Method not allowed'}, status=405)
|
|
|
|
|
|
@csrf_exempt
|
|
def add_link(request):
|
|
"""
|
|
POST endpoint to add a new link.
|
|
"""
|
|
if request.method == 'POST':
|
|
body = json.loads(request.body)
|
|
url = body.get('url')
|
|
if url:
|
|
link = Link.objects.create(url=url, watched=False)
|
|
return JsonResponse({'id': link.id, 'url': link.url, 'watched': link.watched}, status=201)
|
|
else:
|
|
return JsonResponse({'error': 'URL is required'}, status=400)
|
|
else:
|
|
return JsonResponse({'error': 'Method not allowed'}, status=405)
|
|
|
|
|
|
@csrf_exempt
|
|
def delete_link(request, link_id):
|
|
if request.method == 'DELETE':
|
|
try:
|
|
link = Link.objects.get(pk=link_id)
|
|
link.delete()
|
|
return JsonResponse({'status': 'deleted'})
|
|
except Link.DoesNotExist:
|
|
return HttpResponseNotFound()
|
|
return JsonResponse({'error': 'Method not allowed'}, status=405)
|
|
|
|
|
|
@csrf_exempt
|
|
def mark_watched(request, link_id):
|
|
"""
|
|
PATCH endpoint to mark a link as watched.
|
|
"""
|
|
if request.method == 'PATCH':
|
|
try:
|
|
link = Link.objects.get(pk=link_id)
|
|
except Link.DoesNotExist:
|
|
return HttpResponseNotFound()
|
|
|
|
link.watched = True
|
|
link.save()
|
|
return JsonResponse({'id': link.id, 'url': link.url, 'watched': link.watched})
|
|
else:
|
|
return JsonResponse({'error': 'Method not allowed'}, status=405) |