This commit is contained in:
oleg.vodyanov91@gmail.com 2025-04-08 23:58:22 +04:00
commit 036196e182
15 changed files with 435 additions and 0 deletions

16
.gitignore vendored Normal file
View File

@ -0,0 +1,16 @@
init.sql
.venv/
.env
command
.pytest_cache/
.DS_Store
Thumbs.db
staticfiles/
static/
__pycache__/
*.py[cod]
*$py.class
**/migrations/
!*/migrations/__init__.py # Keep the init file if you ignore migrations

25
Dockerfile.app Normal file
View File

@ -0,0 +1,25 @@
# Dockerfile
FROM python:3.12.9-slim-bookworm
# Create a working directory for the app
WORKDIR /app
# Copy requirements first, to leverage Docker's layer caching
COPY instalinks/requirements.txt /app/
# Install dependencies
RUN pip install --no-cache-dir -r requirements.txt
# Copy the rest of the source code
COPY instalinks/ /app/
# Set environment variables for Django
ENV PYTHONUNBUFFERED 1
ENV DJANGO_SETTINGS_MODULE instagram_links.settings
# Expose the port Django runs on
EXPOSE 8000
# Default command: run the Django dev server
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]

16
Dockerfile.db Normal file
View File

@ -0,0 +1,16 @@
# docker build --secret id=DB_NAME --secret id=DB_USER \
# --secret id=DB_PASSWORD -t instagram_links_db:0.0.1 .
FROM bitnami/postgresql:17.4.0-debian-12-r12
# Set environment variables to override default credentials
ENV POSTGRES_USER=/run/secrets/DB_USER
ENV POSTGRES_PASSWORD=/run/secrets/DB_PASSWORD
ENV POSTGRES_DB=/run/secrets/DB_NAME
# Copy the SQL init script into the entrypoint directory
COPY init.sql /docker-entrypoint-initdb.d/init.sql
# The base image's entrypoint will automatically run
# any scripts in /docker-entrypoint-initdb.d/
# No additional commands needed.

0
docker-compose.yml Normal file
View File

View File

View File

@ -0,0 +1,16 @@
"""
ASGI config for instalinks project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'instalinks.settings')
application = get_asgi_application()

View File

@ -0,0 +1,137 @@
"""
Django settings for instalinks project.
Generated by 'django-admin startproject' using Django 5.2.
For more information on this file, see
https://docs.djangoproject.com/en/5.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.2/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure--6^d01urjvdon#5(lf+-1qm385!$82j^q@6*&=xkm^0f@0s(h-'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'links',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'instalinks.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
SETTINGS_PATH = os.path.normpath(os.path.dirname(__file__))
WSGI_APPLICATION = 'instalinks.wsgi.application'
# Database
# https://docs.djangoproject.com/en/5.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ.get('DB_NAME'),
'USER': os.environ.get('DB_USER'),
'PASSWORD': os.environ.get('DB_PASSWORD'),
'HOST': 'localhost',
'PORT': '5432',
}
}
# Password validation
# https://docs.djangoproject.com/en/5.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/5.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
# Default primary key field type
# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

View File

@ -0,0 +1,23 @@
"""
URL configuration for instalinks project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/5.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('links.urls')), # include our links app routes
]

View File

@ -0,0 +1,16 @@
"""
WSGI config for instalinks project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'instalinks.settings')
application = get_wsgi_application()

View File

@ -0,0 +1,9 @@
from django.db import models
class Link(models.Model):
url = models.URLField()
watched = models.BooleanField(default=False)
def __str__(self):
return f"{self.url} (watched={self.watched})"

12
instalinks/links/urls.py Normal file
View File

@ -0,0 +1,12 @@
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
# API endpoints (basic, no DRF):
path('api/links/', views.links_list, name='links_list'),
path('api/links/add/', views.add_link, name='add_link'),
path('api/links/<int:link_id>/delete/', views.delete_link, name='delete_link'),
path('api/links/<int:link_id>/watched/', views.mark_watched, name='mark_watched'),
]

70
instalinks/links/views.py Normal file
View File

@ -0,0 +1,70 @@
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)

22
instalinks/manage.py Executable file
View File

@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'instalinks.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()

View File

@ -0,0 +1,5 @@
Django==5.2
psycopg2-binary==2.9.10
sqlparse==0.5.3
asgiref==3.8.1
python-decouple==3.8

View File

@ -0,0 +1,68 @@
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Instagram Links</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<!-- Bootstrap or your CSS of choice (optional) -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body class="bg-light">
<div class="container py-4">
<h1 class="mb-4">Instagram Links</h1>
<!-- Input to add new link -->
<div class="mb-4 d-flex">
<input id="newLinkInput" type="text" class="form-control me-2" placeholder="Enter Instagram Link"/>
<button id="addLinkBtn" class="btn btn-primary">Add Link</button>
</div>
<!-- Tabs -->
<ul class="nav nav-tabs" id="myTab" role="tablist">
<li class="nav-item">
<button
class="nav-link active"
id="new-tab"
data-bs-toggle="tab"
data-bs-target="#newLinks"
type="button"
role="tab"
>
New
</button>
</li>
<li class="nav-item">
<button
class="nav-link"
id="watched-tab"
data-bs-toggle="tab"
data-bs-target="#watchedLinks"
type="button"
role="tab"
>
Watched
</button>
</li>
</ul>
<!-- Tab panes -->
<div class="tab-content" id="myTabContent">
<div class="tab-pane fade show active" id="newLinks" role="tabpanel" aria-labelledby="new-tab">
<div id="newLinksContainer" class="mt-3"></div>
</div>
<div class="tab-pane fade" id="watchedLinks" role="tabpanel" aria-labelledby="watched-tab">
<div id="watchedLinksContainer" class="mt-3"></div>
</div>
</div>
</div>
<!-- Instagram embed script -->
<script async src="//www.instagram.com/embed.js"></script>
<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<!-- Custom JS -->
<script src="{% static "links/main.js" %}"></script>
</body>
</html>