Starting a basic app
authorDavid Kerkeslager <kerkeslager@gmail.com>
Tue, 31 Aug 2021 22:07:01 +0000 (18:07 -0400)
committerDavid Kerkeslager <kerkeslager@gmail.com>
Tue, 31 Aug 2021 22:07:01 +0000 (18:07 -0400)
12 files changed:
.gitignore [new file with mode: 0644]
src/bigly/__init__.py [new file with mode: 0644]
src/bigly/asgi.py [new file with mode: 0644]
src/bigly/serializers.py [new file with mode: 0644]
src/bigly/settings.py [new file with mode: 0644]
src/bigly/static/bigly/styles.css [new file with mode: 0644]
src/bigly/templates/bigly/index.html [new file with mode: 0644]
src/bigly/urls.py [new file with mode: 0644]
src/bigly/views.py [new file with mode: 0644]
src/bigly/wsgi.py [new file with mode: 0644]
src/manage.py [new file with mode: 0755]
src/requirements.txt [new file with mode: 0644]

diff --git a/.gitignore b/.gitignore
new file mode 100644 (file)
index 0000000..36f60d7
--- /dev/null
@@ -0,0 +1,3 @@
+.env/
+db.sqlite3
+__pycache__/
diff --git a/src/bigly/__init__.py b/src/bigly/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/src/bigly/asgi.py b/src/bigly/asgi.py
new file mode 100644 (file)
index 0000000..82e4e45
--- /dev/null
@@ -0,0 +1,16 @@
+"""
+ASGI config for bigly 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/3.2/howto/deployment/asgi/
+"""
+
+import os
+
+from django.core.asgi import get_asgi_application
+
+os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bigly.settings')
+
+application = get_asgi_application()
diff --git a/src/bigly/serializers.py b/src/bigly/serializers.py
new file mode 100644 (file)
index 0000000..bc948fd
--- /dev/null
@@ -0,0 +1,4 @@
+from rest_framework import serializers
+
+class FollowRedirectsSerializer(serializers.Serializer):
+    link = serializers.URLField(required=True)
diff --git a/src/bigly/settings.py b/src/bigly/settings.py
new file mode 100644 (file)
index 0000000..a58aae1
--- /dev/null
@@ -0,0 +1,131 @@
+"""
+Django settings for bigly project.
+
+Generated by 'django-admin startproject' using Django 3.2.6.
+
+For more information on this file, see
+https://docs.djangoproject.com/en/3.2/topics/settings/
+
+For the full list of settings and their values, see
+https://docs.djangoproject.com/en/3.2/ref/settings/
+"""
+
+import os.path
+from pathlib import Path
+
+# 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/3.2/howto/deployment/checklist/
+
+# SECURITY WARNING: keep the secret key used in production secret!
+SECRET_KEY = 'django-insecure-7^29bo%t0#u21-vc!q#1kbkwpuz8vtt3mjc2t%9zt4!1ma5egs'
+
+# SECURITY WARNING: don't run with debug turned on in production!
+DEBUG = True
+
+ALLOWED_HOSTS = []
+
+
+# Application definition
+
+INSTALLED_APPS = [
+    'django.contrib.admin',
+    'django.contrib.auth',
+    'django.contrib.contenttypes',
+    'django.contrib.sessions',
+    'django.contrib.messages',
+    'django.contrib.staticfiles',
+
+    'rest_framework',
+
+    'bigly',
+]
+
+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 = 'bigly.urls'
+
+TEMPLATES = [
+    {
+        'BACKEND': 'django.template.backends.django.DjangoTemplates',
+        'DIRS': [],
+        'APP_DIRS': True,
+        'OPTIONS': {
+            'context_processors': [
+                'django.template.context_processors.debug',
+                'django.template.context_processors.request',
+                'django.contrib.auth.context_processors.auth',
+                'django.contrib.messages.context_processors.messages',
+            ],
+        },
+    },
+]
+
+WSGI_APPLICATION = 'bigly.wsgi.application'
+
+
+# Database
+# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
+
+DATABASES = {
+    'default': {
+        'ENGINE': 'django.db.backends.sqlite3',
+        'NAME': BASE_DIR / 'db.sqlite3',
+    }
+}
+
+
+# Password validation
+# https://docs.djangoproject.com/en/3.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/3.2/topics/i18n/
+
+LANGUAGE_CODE = 'en-us'
+
+TIME_ZONE = 'UTC'
+
+USE_I18N = True
+
+USE_L10N = True
+
+USE_TZ = True
+
+
+# Static files (CSS, JavaScript, Images)
+# https://docs.djangoproject.com/en/3.2/howto/static-files/
+
+STATIC_ROOT = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static')
+STATIC_URL = '/static/'
+
+# Default primary key field type
+# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
+
+DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
diff --git a/src/bigly/static/bigly/styles.css b/src/bigly/static/bigly/styles.css
new file mode 100644 (file)
index 0000000..5eaa9c4
--- /dev/null
@@ -0,0 +1,3 @@
+body {
+  color: magenta;
+}
diff --git a/src/bigly/templates/bigly/index.html b/src/bigly/templates/bigly/index.html
new file mode 100644 (file)
index 0000000..4178319
--- /dev/null
@@ -0,0 +1,29 @@
+{% load static %}
+<!doctype html>
+<html lang='en'>
+  <head>
+    <title>bigly</title>
+
+    <meta charset='utf-8'/>
+    <meta name='viewport' content='width=device-width, initial-scale=1'/>
+    <meta name='description' content='A tool for unshortening links that have been shortened with a link shortener.'/>
+    <meta name='author' content='David Kerkeslager'/>
+
+    <link rel='stylesheet' href='{% static "bigly/styles.css" %}'/>
+  </head>
+
+  <body>
+    <h1>bigly</h1>
+    <h2>make links big again</h2>
+    Hello, world
+
+    <div id='app'>
+      <noscript>
+        Foo
+      </noscript>
+    </div>
+
+    <script src='bigly/scripts.js'></script>
+  </body>
+</html>
+
diff --git a/src/bigly/urls.py b/src/bigly/urls.py
new file mode 100644 (file)
index 0000000..d074512
--- /dev/null
@@ -0,0 +1,25 @@
+"""bigly URL Configuration
+
+The `urlpatterns` list routes URLs to views. For more information please see:
+    https://docs.djangoproject.com/en/3.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
+
+from . import views
+
+urlpatterns = (
+    path('admin/', admin.site.urls),
+    path('api/v1/follow-redirects', views.api_follow_redirects),
+    path('', views.index),
+)
diff --git a/src/bigly/views.py b/src/bigly/views.py
new file mode 100644 (file)
index 0000000..46bccd6
--- /dev/null
@@ -0,0 +1,55 @@
+from django.views.generic.base import TemplateView
+
+from rest_framework import status, viewsets
+from rest_framework.response import Response
+import requests
+
+from . import serializers
+
+class IndexView(TemplateView):
+    template_name = 'bigly/index.html'
+
+index = IndexView.as_view()
+
+class FollowRedirectsViewSet(viewsets.ViewSet):
+    serializer_class = serializers.FollowRedirectsSerializer
+
+    def follow_redirects(self, request):
+        serializer = serializers.FollowRedirectsSerializer(data=request.query_params)
+
+        if not serializer.is_valid():
+            return Response(
+                serializer.errors,
+                status=status.HTTP_400_BAD_REQUEST,
+            )
+
+        link = serializer.data['link']
+
+        while True:
+            response = requests.head(link)
+
+            # TODO Handle timeouts
+
+            if 301 <= response.status_code and response.status_code <= 308:
+                # TODO Handle the different kinds of redirects correctly
+
+                link = response.headers.get('Location')
+
+                if not link:
+                    # TODO Handle this
+                    raise Exception()
+
+            # TODO Handle error responses
+            else:
+                return Response(
+                    {
+                        'link': link,
+                        'status': response.status_code,
+                    },
+                    status=status.HTTP_200_OK,
+                )
+
+
+api_follow_redirects = FollowRedirectsViewSet.as_view({
+    'get': 'follow_redirects',
+})
diff --git a/src/bigly/wsgi.py b/src/bigly/wsgi.py
new file mode 100644 (file)
index 0000000..f6ffa75
--- /dev/null
@@ -0,0 +1,16 @@
+"""
+WSGI config for bigly 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/3.2/howto/deployment/wsgi/
+"""
+
+import os
+
+from django.core.wsgi import get_wsgi_application
+
+os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bigly.settings')
+
+application = get_wsgi_application()
diff --git a/src/manage.py b/src/manage.py
new file mode 100755 (executable)
index 0000000..b043708
--- /dev/null
@@ -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', 'bigly.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()
diff --git a/src/requirements.txt b/src/requirements.txt
new file mode 100644 (file)
index 0000000..ec54341
--- /dev/null
@@ -0,0 +1,3 @@
+Django==3.2.6
+djangorestframework==3.12.4
+requests==2.26.0