diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000..d8ed724 --- /dev/null +++ b/.flake8 @@ -0,0 +1,3 @@ +[flake8] +max-line-length = 120 +exclude = .env/ diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..28999f9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,167 @@ + +# Created by https://www.toptal.com/developers/gitignore/api/django +# Edit at https://www.toptal.com/developers/gitignore?templates=django + +### Django ### +*.log +*.pot +*.pyc +__pycache__/ +local_settings.py +db.sqlite3 +db.sqlite3-journal +media + +# If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/ +# in your Git repository. Update and uncomment the following line accordingly. +# /staticfiles/ + +### Django.Python Stack ### +# Byte-compiled / optimized / DLL files +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo + +# Django stuff: + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +# End of https://www.toptal.com/developers/gitignore/api/django \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..33fe63f --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "python.linting.flake8Enabled": true, + "python.linting.enabled": true +} \ No newline at end of file diff --git a/doc/diagram.drawio.png b/doc/diagram.drawio.png new file mode 100644 index 0000000..ea719b7 Binary files /dev/null and b/doc/diagram.drawio.png differ diff --git a/doc/diagram.xml b/doc/diagram.xml new file mode 100644 index 0000000..538167c --- /dev/null +++ b/doc/diagram.xml @@ -0,0 +1 @@ +7Zxdd9o4EIZ/DZfpQZItm8tASHb3tN2eZtuml8IW4I2xOEYEsr9+ZZDwh0QgwR844SbBshH4mZeRZjRWBw1m67uYzKdfmE/DDuz66w666UAIAXTFv6TleduCAd42TOLA3zaBtOE++I/Kxq5sXQY+XeQu5IyFPJjnGz0WRdT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VbviKxPfP9e8ovZDu2K2fTQjPXp7zDiAQ9oFdPfkI55i4yFYX4l0rCBLAAG5/gGa4nDdP/fbb4n3V8ZDf8H \ No newline at end of file diff --git a/doc/readme b/doc/readme new file mode 100644 index 0000000..0c84136 --- /dev/null +++ b/doc/readme @@ -0,0 +1 @@ +open the diagram using draw.io \ No newline at end of file diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..36f3b49 --- /dev/null +++ b/manage.py @@ -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', 'urlshortner.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/requirements.txt b/requirements.txt new file mode 100644 index 0000000..489aa39 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,12 @@ +asgiref==3.5.0 +decorator==5.1.1 +Django==4.0.3 +flake8==4.0.1 +mccabe==0.6.1 +punq==0.6.2 +pycodestyle==2.8.0 +pyflakes==2.4.0 +qrcode==7.3.1 +six==1.16.0 +sqlparse==0.4.2 +validators==0.18.2 diff --git a/shortner/__init__.py b/shortner/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/shortner/admin.py b/shortner/admin.py new file mode 100644 index 0000000..4185d36 --- /dev/null +++ b/shortner/admin.py @@ -0,0 +1,3 @@ +# from django.contrib import admin + +# Register your models here. diff --git a/shortner/apps.py b/shortner/apps.py new file mode 100644 index 0000000..42dc249 --- /dev/null +++ b/shortner/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class ShortnerConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'shortner' diff --git a/shortner/domain/__inti__.py b/shortner/domain/__inti__.py new file mode 100644 index 0000000..e69de29 diff --git a/shortner/domain/boundaries/input/token_broker.py b/shortner/domain/boundaries/input/token_broker.py new file mode 100644 index 0000000..d986a7c --- /dev/null +++ b/shortner/domain/boundaries/input/token_broker.py @@ -0,0 +1,6 @@ +from typing import Protocol + + +class TokenBroker(Protocol): + def get_token(self, url: str) -> str: ... + def get_url(self, token: str) -> str: ... diff --git a/shortner/domain/boundaries/output/random_generator.py b/shortner/domain/boundaries/output/random_generator.py new file mode 100644 index 0000000..35ff2be --- /dev/null +++ b/shortner/domain/boundaries/output/random_generator.py @@ -0,0 +1,5 @@ +from typing import Protocol + + +class RandomGenerator(Protocol): + def get_next_int(self, stop: int) -> int: ... diff --git a/shortner/domain/boundaries/output/token_generator_config.py b/shortner/domain/boundaries/output/token_generator_config.py new file mode 100644 index 0000000..cd44c08 --- /dev/null +++ b/shortner/domain/boundaries/output/token_generator_config.py @@ -0,0 +1,5 @@ +from typing import Protocol + + +class TokenGeneratorConfig(Protocol): + def get_token_length(self) -> int: ... diff --git a/shortner/domain/boundaries/output/url_validator.py b/shortner/domain/boundaries/output/url_validator.py new file mode 100644 index 0000000..ba3cdd7 --- /dev/null +++ b/shortner/domain/boundaries/output/url_validator.py @@ -0,0 +1,5 @@ +from typing import Protocol + + +class UrlValidator(Protocol): + def is_url_valid(self, url: str) -> bool: ... diff --git a/shortner/domain/boundaries/output/urltoken_repository.py b/shortner/domain/boundaries/output/urltoken_repository.py new file mode 100644 index 0000000..d8bae7f --- /dev/null +++ b/shortner/domain/boundaries/output/urltoken_repository.py @@ -0,0 +1,8 @@ +from typing import Protocol + +from shortner.domain.entities.url_token import UrlToken + + +class UrlTokenRepository(Protocol): + def get_by_token(self, token: str) -> UrlToken: ... + def insert(self, data: UrlToken): ... diff --git a/shortner/domain/entities/exceptions.py b/shortner/domain/entities/exceptions.py new file mode 100644 index 0000000..4deea66 --- /dev/null +++ b/shortner/domain/entities/exceptions.py @@ -0,0 +1,6 @@ +class NotFoundException(Exception): + pass + + +class BusinessException(Exception): + pass diff --git a/shortner/domain/entities/url_token.py b/shortner/domain/entities/url_token.py new file mode 100644 index 0000000..ebc1c39 --- /dev/null +++ b/shortner/domain/entities/url_token.py @@ -0,0 +1,7 @@ +from dataclasses import dataclass + + +@dataclass +class UrlToken: + url: str + token: str diff --git a/shortner/domain/services/token_broker_service.py b/shortner/domain/services/token_broker_service.py new file mode 100644 index 0000000..5c25216 --- /dev/null +++ b/shortner/domain/services/token_broker_service.py @@ -0,0 +1,33 @@ +from shortner.domain.boundaries.input.token_broker import TokenBroker +from shortner.domain.boundaries.output.url_validator import UrlValidator +from shortner.domain.boundaries.output.urltoken_repository import UrlTokenRepository +from shortner.domain.services.token_generator import TokenGenerator +from shortner.domain.entities.exceptions import BusinessException, NotFoundException +from shortner.domain.entities.url_token import UrlToken + + +class TokenBrokerService(TokenBroker): + def __init__(self, + repository: UrlTokenRepository, + url_validator: UrlValidator, + token_generator: TokenGenerator): + self.repository = repository + self.url_validator = url_validator + self.token_generator = token_generator + + def get_token(self, url: str) -> str: + if not self.url_validator.is_url_valid(url): + raise BusinessException('url is not valid') + + token = self.token_generator.get_token() + + self.repository.insert(UrlToken(url, token)) + + return token + + def get_url(self, token: str) -> str: + url_token = self.repository.get_by_token(token) + if url_token is None: + raise NotFoundException('token not found') + + return url_token.url diff --git a/shortner/domain/services/token_generation_service.py b/shortner/domain/services/token_generation_service.py new file mode 100644 index 0000000..c738c1d --- /dev/null +++ b/shortner/domain/services/token_generation_service.py @@ -0,0 +1,19 @@ +from shortner.domain.services.token_generator import TokenGenerator +from shortner.domain.boundaries.output.random_generator import RandomGenerator +from shortner.domain.boundaries.output.token_generator_config import TokenGeneratorConfig + + +class TokenGenerationService(TokenGenerator): + def __init__(self, + token_generation_config: TokenGeneratorConfig, + random_generator: RandomGenerator): + self.token_generation_config = token_generation_config + self.random_generator = random_generator + + CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' + + def get_token(self) -> str: + chars = [self.CHARS[self.random_generator.get_next_int(len(self.CHARS))] + for i in range(self.token_generation_config.get_token_length())] + result = ''.join(chars) + return result diff --git a/shortner/domain/services/token_generator.py b/shortner/domain/services/token_generator.py new file mode 100644 index 0000000..83a4554 --- /dev/null +++ b/shortner/domain/services/token_generator.py @@ -0,0 +1,5 @@ +from typing import Protocol + + +class TokenGenerator(Protocol): + def get_token(self) -> str: ... diff --git a/shortner/ioc.py b/shortner/ioc.py new file mode 100644 index 0000000..dc0941c --- /dev/null +++ b/shortner/ioc.py @@ -0,0 +1,40 @@ +import punq + +from shortner.domain.boundaries.input.token_broker import TokenBroker +from shortner.domain.boundaries.output.random_generator import RandomGenerator +from shortner.domain.boundaries.output.token_generator_config import TokenGeneratorConfig +from shortner.domain.boundaries.output.url_validator import UrlValidator +from shortner.domain.boundaries.output.urltoken_repository import UrlTokenRepository +from shortner.domain.services.token_broker_service import TokenBrokerService +from shortner.domain.services.token_generation_service import TokenGenerationService +from shortner.domain.services.token_generator import TokenGenerator +from shortner.services.default_random_generator_service import DefaultRandomGeneratorService +from shortner.services.env_token_generator_config import EnvTokenGeneratorConfig +from shortner.services.validators_url_validator_service import ValidatorsUrlValidatorService +from shortner.services.model_url_token_repository import ModelUrlTokenRepository + +container = punq.Container() + +container.register(TokenBroker, TokenBrokerService) +container.register(RandomGenerator, DefaultRandomGeneratorService) +container.register(UrlValidator, ValidatorsUrlValidatorService) +container.register(UrlTokenRepository, ModelUrlTokenRepository) +container.register(TokenGenerator, TokenGenerationService) +container.register(TokenGeneratorConfig, EnvTokenGeneratorConfig) + + +# based on https://github.com/django/django/blob/main/django/views/generic/base.py +def get_ioc_view(cls, **initkwargs): + def view(request, *args, **kwargs): + self = container.instantiate(cls, **initkwargs) + self.setup(request, *args, **kwargs) + return self.dispatch(request, *args, **kwargs) + + view.view_class = cls + view.view_initkwargs = initkwargs + view.__doc__ = cls.__doc__ + view.__module__ = cls.__module__ + view.__annotations__ = cls.dispatch.__annotations__ + view.__dict__.update(cls.dispatch.__dict__) + + return view diff --git a/shortner/migrations/0001_initial.py b/shortner/migrations/0001_initial.py new file mode 100644 index 0000000..dec5cde --- /dev/null +++ b/shortner/migrations/0001_initial.py @@ -0,0 +1,22 @@ +# Generated by Django 4.0.3 on 2022-03-12 04:50 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='UrlToken', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('url', models.CharField(max_length=1000)), + ('token', models.CharField(db_index=True, max_length=50)), + ], + ), + ] diff --git a/shortner/migrations/__init__.py b/shortner/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/shortner/models.py b/shortner/models.py new file mode 100644 index 0000000..09873c1 --- /dev/null +++ b/shortner/models.py @@ -0,0 +1,17 @@ +from django.db import models +from .domain.entities.url_token import UrlToken as DomainUrlToken + + +class UrlToken(models.Model): + url = models.CharField(max_length=1000) + token = models.CharField(max_length=50, db_index=True) + + @staticmethod + def from_domain(data: DomainUrlToken): + result = UrlToken(url=data.url, token=data.token) + return result + + @staticmethod + def to_domain(model) -> DomainUrlToken: + result = DomainUrlToken(model.url, model.token) + return result diff --git a/shortner/services/default_random_generator_service.py b/shortner/services/default_random_generator_service.py new file mode 100644 index 0000000..16cc014 --- /dev/null +++ b/shortner/services/default_random_generator_service.py @@ -0,0 +1,11 @@ +import random + +from ..domain.boundaries.output.random_generator import RandomGenerator + + +class DefaultRandomGeneratorService(RandomGenerator): + def __init__(self): + self.random = random.Random() + + def get_next_int(self, stop: int) -> int: + return self.random.randrange(stop) diff --git a/shortner/services/env_token_generator_config.py b/shortner/services/env_token_generator_config.py new file mode 100644 index 0000000..8fbe78b --- /dev/null +++ b/shortner/services/env_token_generator_config.py @@ -0,0 +1,7 @@ +import os +from ..domain.boundaries.output.token_generator_config import TokenGeneratorConfig + + +class EnvTokenGeneratorConfig(TokenGeneratorConfig): + def get_token_length(self) -> int: + return int(os.environ.get('TOKEN_LENGTH', 10)) diff --git a/shortner/services/model_url_token_repository.py b/shortner/services/model_url_token_repository.py new file mode 100644 index 0000000..09a4dcf --- /dev/null +++ b/shortner/services/model_url_token_repository.py @@ -0,0 +1,14 @@ +from ..domain.boundaries.output.urltoken_repository import UrlTokenRepository +from ..domain.entities.url_token import UrlToken as DomainUrlToken +from shortner.models import UrlToken + + +class ModelUrlTokenRepository(UrlTokenRepository): + def get_by_token(self, token: str) -> UrlToken: + try: + return UrlToken.to_domain(UrlToken.objects.get(token=token)) + except UrlToken.DoesNotExist: + return None + + def insert(self, data: DomainUrlToken): + UrlToken.objects.create(url=data.url, token=data.token) diff --git a/shortner/services/validators_url_validator_service.py b/shortner/services/validators_url_validator_service.py new file mode 100644 index 0000000..3b8c60a --- /dev/null +++ b/shortner/services/validators_url_validator_service.py @@ -0,0 +1,7 @@ +import validators +from ..domain.boundaries.output.url_validator import UrlValidator + + +class ValidatorsUrlValidatorService(UrlValidator): + def is_url_valid(self, url: str) -> bool: + return validators.url(url) diff --git a/shortner/tests.py b/shortner/tests.py new file mode 100644 index 0000000..a79ca8b --- /dev/null +++ b/shortner/tests.py @@ -0,0 +1,3 @@ +# from django.test import TestCase + +# Create your tests here. diff --git a/shortner/urls.py b/shortner/urls.py new file mode 100644 index 0000000..edd1cbc --- /dev/null +++ b/shortner/urls.py @@ -0,0 +1,9 @@ +from django.urls import path +from shortner.ioc import get_ioc_view + +from shortner.views import UrlAdder, UrlGetter + +urlpatterns = [ + path('urls/', get_ioc_view(UrlAdder), name='add_url'), + path('t/', get_ioc_view(UrlGetter), name='get_url') +] diff --git a/shortner/views.py b/shortner/views.py new file mode 100644 index 0000000..b644fae --- /dev/null +++ b/shortner/views.py @@ -0,0 +1,43 @@ +from dataclasses import asdict, dataclass +import json +from django.http import HttpResponseBadRequest, HttpResponsePermanentRedirect, JsonResponse +from django.views.decorators.csrf import csrf_exempt +from django.utils.decorators import method_decorator +from django.views import View + +from .domain.boundaries.input.token_broker import TokenBroker + + +@dataclass +class UrlDto: + url: str + + +@dataclass +class TokenDto: + token: str + + +@method_decorator(csrf_exempt, name='dispatch') +class UrlAdder(View): + def __init__(self, token_broker: TokenBroker): + self.token_broker = token_broker + + def post(self, request): + try: + j = json.loads(request.body) + in_dto = UrlDto(**j) + except Exception: + return HttpResponseBadRequest('invalid payload') + token = self.token_broker.get_token(in_dto.url) + out_dto = TokenDto(token) + return JsonResponse(asdict(out_dto)) + + +class UrlGetter(View): + def __init__(self, token_broker: TokenBroker): + self.token_broker = token_broker + + def get(self, request, token): + url = self.token_broker.get_url(token) + return HttpResponsePermanentRedirect(url) diff --git a/urlshortner/__init__.py b/urlshortner/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/urlshortner/asgi.py b/urlshortner/asgi.py new file mode 100644 index 0000000..d64187c --- /dev/null +++ b/urlshortner/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for urlshortner 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/4.0/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'urlshortner.settings') + +application = get_asgi_application() diff --git a/urlshortner/settings.py b/urlshortner/settings.py new file mode 100644 index 0000000..3def069 --- /dev/null +++ b/urlshortner/settings.py @@ -0,0 +1,124 @@ +""" +Django settings for urlshortner project. + +Generated by 'django-admin startproject' using Django 4.0.3. + +For more information on this file, see +https://docs.djangoproject.com/en/4.0/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/4.0/ref/settings/ +""" + +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/4.0/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'django-insecure-y92txdx91gb=*_0zz3n6%s#hzi9u!(7!(&k-w0a%*@el7o7i)t' + +# 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', + 'shortner', +] + +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 = 'urlshortner.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 = 'urlshortner.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/4.0/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/4.0/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/4.0/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/4.0/howto/static-files/ + +STATIC_URL = 'static/' + +# Default primary key field type +# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' diff --git a/urlshortner/urls.py b/urlshortner/urls.py new file mode 100644 index 0000000..269dc67 --- /dev/null +++ b/urlshortner/urls.py @@ -0,0 +1,22 @@ +"""urlshortner URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/4.0/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 include, path + +urlpatterns = [ + path('admin/', admin.site.urls), + path('api/', include('shortner.urls')) +] diff --git a/urlshortner/wsgi.py b/urlshortner/wsgi.py new file mode 100644 index 0000000..940503a --- /dev/null +++ b/urlshortner/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for urlshortner 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/4.0/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'urlshortner.settings') + +application = get_wsgi_application()