├── config
├── __init__.py
├── settings
│ ├── __init__.py
│ ├── test.py
│ ├── local.py
│ ├── production.py
│ └── base.py
├── urls.py
└── wsgi.py
├── .gitattributes
├── CONTRIBUTORS.txt
├── todobackend
├── static
│ ├── fonts
│ │ └── .gitkeep
│ ├── sass
│ │ ├── custom_bootstrap_vars.scss
│ │ └── project.scss
│ ├── images
│ │ └── favicon.ico
│ ├── css
│ │ └── project.css
│ └── js
│ │ ├── project.js
│ │ └── vuex.js
├── todos
│ ├── __init__.py
│ ├── migrations
│ │ ├── __init__.py
│ │ ├── 0002_todoitem_uuid.py
│ │ ├── 0004_auto_20180226_2352.py
│ │ ├── 0005_auto_20180227_0045.py
│ │ ├── 0003_auto_20180226_2351.py
│ │ └── 0001_initial.py
│ ├── tests.py
│ ├── views.py
│ ├── apps.py
│ ├── api
│ │ ├── __init__.py
│ │ ├── urls.py
│ │ ├── serializers.py
│ │ └── views.py
│ ├── urls.py
│ ├── admin.py
│ ├── templates
│ │ └── todo.html
│ └── models.py
├── users
│ ├── __init__.py
│ ├── tests
│ │ ├── __init__.py
│ │ ├── factories.py
│ │ ├── test_models.py
│ │ ├── test_admin.py
│ │ ├── test_urls.py
│ │ └── test_views.py
│ ├── migrations
│ │ ├── __init__.py
│ │ └── 0001_initial.py
│ ├── apps.py
│ ├── adapters.py
│ ├── urls.py
│ ├── models.py
│ ├── admin.py
│ └── views.py
├── templates
│ ├── pages
│ │ ├── about.html
│ │ └── home.html
│ ├── 404.html
│ ├── 403_csrf.html
│ ├── account
│ │ ├── base.html
│ │ ├── account_inactive.html
│ │ ├── password_reset_from_key_done.html
│ │ ├── signup_closed.html
│ │ ├── verification_sent.html
│ │ ├── password_set.html
│ │ ├── password_reset_done.html
│ │ ├── password_change.html
│ │ ├── logout.html
│ │ ├── signup.html
│ │ ├── verified_email_required.html
│ │ ├── password_reset.html
│ │ ├── password_reset_from_key.html
│ │ ├── email_confirm.html
│ │ ├── login.html
│ │ └── email.html
│ ├── 500.html
│ ├── users
│ │ ├── user_list.html
│ │ ├── user_form.html
│ │ └── user_detail.html
│ └── base.html
├── __init__.py
├── contrib
│ ├── __init__.py
│ └── sites
│ │ ├── __init__.py
│ │ └── migrations
│ │ ├── __init__.py
│ │ ├── 0002_alter_domain_unique.py
│ │ ├── 0001_initial.py
│ │ └── 0003_set_site_domain_and_name.py
└── static_src
│ └── js
│ └── todo
│ └── todo.js
├── pytest.ini
├── docs
├── __init__.py
├── pycharm
│ ├── images
│ │ ├── 1.png
│ │ ├── 2.png
│ │ ├── 3.png
│ │ ├── 4.png
│ │ ├── 7.png
│ │ ├── 8.png
│ │ ├── f1.png
│ │ ├── f2.png
│ │ ├── f3.png
│ │ ├── f4.png
│ │ ├── issue1.png
│ │ └── issue2.png
│ └── configuration.rst
├── deploy.rst
├── install.rst
├── index.rst
├── make.bat
├── Makefile
├── docker_ec2.rst
└── conf.py
├── .coveragerc
├── locale
└── README.rst
├── .idea
├── vcs.xml
├── modules.xml
├── misc.xml
├── webResources.xml
├── todobackend.iml
└── runConfigurations
│ ├── Docker__tests___all.xml
│ ├── Docker__tests___module__users.xml
│ ├── Docker__migrate.xml
│ ├── Docker__tests___file__test_models.xml
│ ├── Docker__tests___class__TestUser.xml
│ ├── Docker__runserver.xml
│ ├── Docker__runserver_plus.xml
│ └── Docker__tests___specific__test_get_absolute_url.xml
├── setup.cfg
├── requirements
├── test.txt
├── local.txt
├── production.txt
└── base.txt
├── .pylintrc
├── Makefile
├── Makefile.settings
├── Dockerfile
├── webpack.config.js
├── utility
├── requirements-trusty.apt
├── requirements-xenial.apt
├── requirements-jessie.apt
├── requirements-stretch.apt
├── install_python_dependencies.sh
└── install_os_dependencies.sh
├── .travis.yml
├── .editorconfig
├── README.rst
├── package.json
├── LICENSE
├── manage.py
├── docker-compose.yml
└── .gitignore
/config/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/config/settings/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | * text=auto
2 |
--------------------------------------------------------------------------------
/CONTRIBUTORS.txt:
--------------------------------------------------------------------------------
1 | James Lin
2 |
--------------------------------------------------------------------------------
/todobackend/static/fonts/.gitkeep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/todobackend/todos/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/todobackend/users/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/todobackend/users/tests/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/todobackend/todos/migrations/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/todobackend/users/migrations/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/todobackend/static/sass/custom_bootstrap_vars.scss:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/todobackend/templates/pages/about.html:
--------------------------------------------------------------------------------
1 | {% extends "base.html" %}
--------------------------------------------------------------------------------
/pytest.ini:
--------------------------------------------------------------------------------
1 | [pytest]
2 | DJANGO_SETTINGS_MODULE=config.settings.test
3 |
4 |
--------------------------------------------------------------------------------
/todobackend/todos/tests.py:
--------------------------------------------------------------------------------
1 | from django.test import TestCase
2 |
3 | # Create your tests here.
4 |
--------------------------------------------------------------------------------
/docs/__init__.py:
--------------------------------------------------------------------------------
1 | # Included so that Django's startproject comment runs against the docs directory
2 |
--------------------------------------------------------------------------------
/todobackend/todos/views.py:
--------------------------------------------------------------------------------
1 | from django.shortcuts import render
2 |
3 | # Create your views here.
4 |
--------------------------------------------------------------------------------
/docs/pycharm/images/1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/variable/todobackend/master/docs/pycharm/images/1.png
--------------------------------------------------------------------------------
/docs/pycharm/images/2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/variable/todobackend/master/docs/pycharm/images/2.png
--------------------------------------------------------------------------------
/docs/pycharm/images/3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/variable/todobackend/master/docs/pycharm/images/3.png
--------------------------------------------------------------------------------
/docs/pycharm/images/4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/variable/todobackend/master/docs/pycharm/images/4.png
--------------------------------------------------------------------------------
/docs/pycharm/images/7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/variable/todobackend/master/docs/pycharm/images/7.png
--------------------------------------------------------------------------------
/docs/pycharm/images/8.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/variable/todobackend/master/docs/pycharm/images/8.png
--------------------------------------------------------------------------------
/docs/pycharm/images/f1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/variable/todobackend/master/docs/pycharm/images/f1.png
--------------------------------------------------------------------------------
/docs/pycharm/images/f2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/variable/todobackend/master/docs/pycharm/images/f2.png
--------------------------------------------------------------------------------
/docs/pycharm/images/f3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/variable/todobackend/master/docs/pycharm/images/f3.png
--------------------------------------------------------------------------------
/docs/pycharm/images/f4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/variable/todobackend/master/docs/pycharm/images/f4.png
--------------------------------------------------------------------------------
/docs/deploy.rst:
--------------------------------------------------------------------------------
1 | Deploy
2 | ========
3 |
4 | This is where you describe how the project is deployed in production.
5 |
--------------------------------------------------------------------------------
/docs/pycharm/images/issue1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/variable/todobackend/master/docs/pycharm/images/issue1.png
--------------------------------------------------------------------------------
/docs/pycharm/images/issue2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/variable/todobackend/master/docs/pycharm/images/issue2.png
--------------------------------------------------------------------------------
/docs/install.rst:
--------------------------------------------------------------------------------
1 | Install
2 | =========
3 |
4 | This is where you write how to get a new laptop to run this project.
5 |
--------------------------------------------------------------------------------
/.coveragerc:
--------------------------------------------------------------------------------
1 | [run]
2 | include = todobackend/*
3 | omit = *migrations*, *tests*
4 | plugins =
5 | django_coverage_plugin
6 |
--------------------------------------------------------------------------------
/todobackend/static/images/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/variable/todobackend/master/todobackend/static/images/favicon.ico
--------------------------------------------------------------------------------
/todobackend/todos/apps.py:
--------------------------------------------------------------------------------
1 | from django.apps import AppConfig
2 |
3 |
4 | class TodolistConfig(AppConfig):
5 | name = 'todos'
6 |
--------------------------------------------------------------------------------
/locale/README.rst:
--------------------------------------------------------------------------------
1 | Translations
2 | ============
3 |
4 | Translations will be placed in this folder when running::
5 |
6 | python manage.py makemessages
7 |
--------------------------------------------------------------------------------
/todobackend/__init__.py:
--------------------------------------------------------------------------------
1 | __version__ = '0.1.0'
2 | __version_info__ = tuple([int(num) if num.isdigit() else num for num in __version__.replace('-', '.', 1).split('.')])
3 |
--------------------------------------------------------------------------------
/todobackend/todos/api/__init__.py:
--------------------------------------------------------------------------------
1 | # encoding: utf-8
2 | from __future__ import unicode_literals
3 | from __future__ import absolute_import
4 | from __future__ import division
5 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/todobackend/todos/urls.py:
--------------------------------------------------------------------------------
1 | # encoding: utf-8
2 | from django.urls import path, include
3 | from django.views.generic import TemplateView
4 |
5 | urlpatterns = [
6 | path('api/', include('todobackend.todos.api.urls')),
7 | ]
8 |
9 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [flake8]
2 | max-line-length = 120
3 | exclude = .tox,.git,*/migrations/*,*/static/CACHE/*,docs,node_modules
4 |
5 | [pycodestyle]
6 | max-line-length = 120
7 | exclude=.tox,.git,*/migrations/*,*/static/CACHE/*,docs,node_modules
8 |
--------------------------------------------------------------------------------
/todobackend/contrib/__init__.py:
--------------------------------------------------------------------------------
1 | """
2 | To understand why this file is here, please read:
3 |
4 | http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django
5 | """
6 |
--------------------------------------------------------------------------------
/todobackend/contrib/sites/__init__.py:
--------------------------------------------------------------------------------
1 | """
2 | To understand why this file is here, please read:
3 |
4 | http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django
5 | """
6 |
--------------------------------------------------------------------------------
/todobackend/contrib/sites/migrations/__init__.py:
--------------------------------------------------------------------------------
1 | """
2 | To understand why this file is here, please read:
3 |
4 | http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django
5 | """
6 |
--------------------------------------------------------------------------------
/todobackend/templates/404.html:
--------------------------------------------------------------------------------
1 | {% extends "base.html" %}
2 |
3 | {% block title %}Page not found{% endblock %}
4 |
5 | {% block content %}
6 |
Page not found
7 |
8 | This is not the page you were looking for.
9 | {% endblock content %}
10 |
--------------------------------------------------------------------------------
/todobackend/templates/403_csrf.html:
--------------------------------------------------------------------------------
1 | {% extends "base.html" %}
2 |
3 | {% block title %}Forbidden (403){% endblock %}
4 |
5 | {% block content %}
6 | Forbidden (403)
7 |
8 | CSRF verification failed. Request aborted.
9 | {% endblock content %}
10 |
--------------------------------------------------------------------------------
/todobackend/todos/admin.py:
--------------------------------------------------------------------------------
1 | from django.contrib import admin
2 | from .models import TODOItem
3 |
4 | class TODOItemAmin(admin.ModelAdmin):
5 | list_display = ['uuid', 'session_id', 'description', 'priority', 'created_at', 'completed_at']
6 |
7 | admin.site.register(TODOItem, TODOItemAmin)
8 |
--------------------------------------------------------------------------------
/todobackend/todos/api/urls.py:
--------------------------------------------------------------------------------
1 | # encoding: utf-8
2 | from rest_framework import routers
3 | from todobackend.todos.api.views import TodoItemViewSet
4 |
5 |
6 | router = routers.SimpleRouter()
7 | router.register(r'todos', TodoItemViewSet, base_name='todo')
8 |
9 | urlpatterns = router.urls
10 |
--------------------------------------------------------------------------------
/requirements/test.txt:
--------------------------------------------------------------------------------
1 | # Test dependencies go here.
2 | -r base.txt
3 |
4 |
5 |
6 | coverage==4.5.1
7 | flake8==3.5.0 # pyup: != 2.6.0
8 | django-test-plus==1.0.22
9 | factory-boy==2.10.0
10 | django-coverage-plugin==1.5.0
11 |
12 | # pytest
13 | pytest-django==3.1.2
14 | pytest-sugar==0.9.1
15 |
--------------------------------------------------------------------------------
/todobackend/todos/api/serializers.py:
--------------------------------------------------------------------------------
1 | # encoding: utf-8
2 | from rest_framework import serializers
3 | from todobackend.todos.models import TODOItem
4 |
5 |
6 | class TODOItemSerializer(serializers.ModelSerializer):
7 | class Meta:
8 | fields = '__all__'
9 | model = TODOItem
10 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/todobackend/static/css/project.css:
--------------------------------------------------------------------------------
1 | /* These styles are generated from project.scss. */
2 |
3 | .alert-debug {
4 | color: black;
5 | background-color: white;
6 | border-color: #d6e9c6;
7 | }
8 |
9 | .alert-error {
10 | color: #b94a48;
11 | background-color: #f2dede;
12 | border-color: #eed3d7;
13 | }
14 |
--------------------------------------------------------------------------------
/.pylintrc:
--------------------------------------------------------------------------------
1 | [MASTER]
2 | load-plugins=pylint_common, pylint_django
3 |
4 | [FORMAT]
5 | max-line-length=120
6 |
7 | [MESSAGES CONTROL]
8 | disable=missing-docstring,invalid-name
9 |
10 | [DESIGN]
11 | max-parents=13
12 |
13 | [TYPECHECK]
14 | generated-members=REQUEST,acl_users,aq_parent,"[a-zA-Z]+_set{1,2}",save,delete
15 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/todobackend/templates/account/base.html:
--------------------------------------------------------------------------------
1 | {% extends "base.html" %}
2 | {% block title %}{% block head_title %}{% endblock head_title %}{% endblock title %}
3 |
4 | {% block content %}
5 |
6 |
7 | {% block inner %}{% endblock %}
8 |
9 |
10 | {% endblock %}
11 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | include Makefile.settings
2 | init:
3 | ${INFO} "Starting database container ..."
4 | @ docker-compose up -d db
5 | @ sleep 5
6 | ${INFO} "Creating todobackend database ..."
7 | @ docker exec todobackend_db mysql -uroot -e "create database todobackend"
8 | ${INFO} "Initial migration ..."
9 | @ docker-compose run migrate
10 |
--------------------------------------------------------------------------------
/Makefile.settings:
--------------------------------------------------------------------------------
1 | # Cosmetics
2 | RED := "\e[1;31m"
3 | YELLOW := "\e[1;33m"
4 | NC := "\e[0m"
5 |
6 | # Shell Functions
7 | INFO := @bash -c '\
8 | printf $(YELLOW); \
9 | echo "=> $$1"; \
10 | printf $(NC)' SOME_VALUE
11 | WARNING := @bash -c '\
12 | printf $(RED); \
13 | echo "WARNING: $$1"; \
14 | printf $(NC)' SOME_VALUE
15 |
--------------------------------------------------------------------------------
/todobackend/templates/account/account_inactive.html:
--------------------------------------------------------------------------------
1 | {% extends "account/base.html" %}
2 |
3 | {% load i18n %}
4 |
5 | {% block head_title %}{% trans "Account Inactive" %}{% endblock %}
6 |
7 | {% block inner %}
8 | {% trans "Account Inactive" %}
9 |
10 | {% trans "This account is inactive." %}
11 | {% endblock %}
12 |
13 |
--------------------------------------------------------------------------------
/todobackend/templates/account/password_reset_from_key_done.html:
--------------------------------------------------------------------------------
1 | {% extends "account/base.html" %}
2 |
3 | {% load i18n %}
4 | {% block head_title %}{% trans "Change Password" %}{% endblock %}
5 |
6 | {% block inner %}
7 | {% trans "Change Password" %}
8 | {% trans 'Your password is now changed.' %}
9 | {% endblock %}
10 |
11 |
--------------------------------------------------------------------------------
/todobackend/users/apps.py:
--------------------------------------------------------------------------------
1 | from django.apps import AppConfig
2 |
3 |
4 | class UsersConfig(AppConfig):
5 | name = 'todobackend.users'
6 | verbose_name = "Users"
7 |
8 | def ready(self):
9 | """Override this to put in:
10 | Users system checks
11 | Users signal registration
12 | """
13 | pass
14 |
--------------------------------------------------------------------------------
/todobackend/templates/account/signup_closed.html:
--------------------------------------------------------------------------------
1 | {% extends "account/base.html" %}
2 |
3 | {% load i18n %}
4 |
5 | {% block head_title %}{% trans "Sign Up Closed" %}{% endblock %}
6 |
7 | {% block inner %}
8 | {% trans "Sign Up Closed" %}
9 |
10 | {% trans "We are sorry, but the sign up is currently closed." %}
11 | {% endblock %}
12 |
13 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM alang/django:2.0-python3
2 |
3 | ARG DEBIAN_FRONTEND=noninteractive
4 | RUN apt-get update
5 | RUN apt-get -y install python-mysqldb
6 |
7 | ENV DJANGO_MIGRATE=true
8 | RUN mkdir /tmp/requirements
9 | COPY ./requirements /tmp/requirements
10 |
11 | RUN pip install -r /tmp/requirements/local.txt
12 |
13 | WORKDIR /usr/django/app
14 | ENTRYPOINT ["/bin/bash", "-c"]
15 |
--------------------------------------------------------------------------------
/todobackend/templates/500.html:
--------------------------------------------------------------------------------
1 | {% extends "base.html" %}
2 |
3 | {% block title %}Server Error{% endblock %}
4 |
5 | {% block content %}
6 | Ooops!!! 500
7 |
8 | Looks like something went wrong!
9 |
10 | We track these errors automatically, but if the problem persists feel free to contact us. In the meantime, try refreshing.
11 | {% endblock content %}
12 |
13 |
14 |
--------------------------------------------------------------------------------
/requirements/local.txt:
--------------------------------------------------------------------------------
1 | # Local development dependencies go here
2 | -r base.txt
3 |
4 | coverage==4.5.1
5 | django-coverage-plugin==1.5.0
6 |
7 | Sphinx==1.7.0
8 | django-extensions==2.0.0
9 | Werkzeug==0.14.1
10 | django-test-plus==1.0.22
11 | factory-boy==2.10.0
12 |
13 | django-debug-toolbar==1.9.1
14 |
15 | # improved REPL
16 | ipdb==0.11
17 |
18 | pytest-django==3.1.2
19 | pytest-sugar==0.9.1
20 |
--------------------------------------------------------------------------------
/webpack.config.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 |
3 | module.exports = {
4 | entry: './todobackend/static_src/js/todo/todo.js',
5 | output: {
6 | filename: 'todo.js',
7 | path: path.resolve(__dirname, 'todobackend', 'static', 'js', 'todo')
8 | },
9 | resolve: {
10 | alias: {
11 | 'vue$': 'vue/dist/vue.esm.js' // 'vue/dist/vue.common.js' for webpack 1
12 | }
13 | },
14 | devtool: "source-map"
15 | };
16 |
--------------------------------------------------------------------------------
/todobackend/users/tests/factories.py:
--------------------------------------------------------------------------------
1 | import factory
2 |
3 |
4 | class UserFactory(factory.django.DjangoModelFactory):
5 | username = factory.Sequence(lambda n: 'user-{0}'.format(n))
6 | email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n))
7 | password = factory.PostGenerationMethodCall('set_password', 'password')
8 |
9 | class Meta:
10 | model = 'users.User'
11 | django_get_or_create = ('username', )
12 |
--------------------------------------------------------------------------------
/.idea/webResources.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/todobackend/todos/migrations/0002_todoitem_uuid.py:
--------------------------------------------------------------------------------
1 | # Generated by Django 2.0.2 on 2018-02-26 23:50
2 |
3 | from django.db import migrations, models
4 | import uuid
5 |
6 |
7 | class Migration(migrations.Migration):
8 |
9 | dependencies = [
10 | ('todos', '0001_initial'),
11 | ]
12 |
13 | operations = [
14 | migrations.AddField(
15 | model_name='todoitem',
16 | name='uuid',
17 | field=models.UUIDField(default=uuid.uuid4, editable=False),
18 | ),
19 | ]
20 |
--------------------------------------------------------------------------------
/todobackend/templates/account/verification_sent.html:
--------------------------------------------------------------------------------
1 | {% extends "account/base.html" %}
2 |
3 | {% load i18n %}
4 |
5 | {% block head_title %}{% trans "Verify Your E-mail Address" %}{% endblock %}
6 |
7 | {% block inner %}
8 | {% trans "Verify Your E-mail Address" %}
9 |
10 | {% blocktrans %}We have sent an e-mail to you for verification. Follow the link provided to finalize the signup process. Please contact us if you do not receive it within a few minutes.{% endblocktrans %}
11 |
12 | {% endblock %}
13 |
14 |
--------------------------------------------------------------------------------
/todobackend/templates/users/user_list.html:
--------------------------------------------------------------------------------
1 | {% extends "base.html" %}
2 | {% load static i18n %}
3 | {% block title %}Members{% endblock %}
4 |
5 | {% block content %}
6 |
17 | {% endblock content %}
18 |
--------------------------------------------------------------------------------
/utility/requirements-trusty.apt:
--------------------------------------------------------------------------------
1 | ##basic build dependencies of various Django apps for Ubuntu Trusty 14.04
2 | #build-essential metapackage install: make, gcc, g++,
3 | build-essential
4 | #required to translate
5 | gettext
6 | python3-dev
7 |
8 | ##shared dependencies of:
9 | ##Pillow, pylibmc
10 | zlib1g-dev
11 |
12 | ##Postgresql and psycopg2 dependencies
13 | libpq-dev
14 |
15 | ##Pillow dependencies
16 | libtiff4-dev
17 | libjpeg8-dev
18 | libfreetype6-dev
19 | liblcms1-dev
20 | libwebp-dev
21 |
22 | ##django-extensions
23 | graphviz-dev
24 |
--------------------------------------------------------------------------------
/utility/requirements-xenial.apt:
--------------------------------------------------------------------------------
1 | ##basic build dependencies of various Django apps for Ubuntu Xenial 16.04
2 | #build-essential metapackage install: make, gcc, g++,
3 | build-essential
4 | #required to translate
5 | gettext
6 | python3-dev
7 |
8 | ##shared dependencies of:
9 | ##Pillow, pylibmc
10 | zlib1g-dev
11 |
12 | ##Postgresql and psycopg2 dependencies
13 | libpq-dev
14 |
15 | ##Pillow dependencies
16 | libtiff5-dev
17 | libjpeg8-dev
18 | libfreetype6-dev
19 | liblcms2-dev
20 | libwebp-dev
21 |
22 | ##django-extensions
23 | graphviz-dev
24 |
--------------------------------------------------------------------------------
/utility/requirements-jessie.apt:
--------------------------------------------------------------------------------
1 | ##basic build dependencies of various Django apps for Debian Jessie 8.x
2 | #build-essential metapackage install: make, gcc, g++,
3 | build-essential
4 | #required to translate
5 | gettext
6 | python3-dev
7 |
8 | ##shared dependencies of:
9 | ##Pillow, pylibmc
10 | zlib1g-dev
11 |
12 | ##Postgresql and psycopg2 dependencies
13 | libpq-dev
14 |
15 | ##Pillow dependencies
16 | libtiff5-dev
17 | libjpeg62-turbo-dev
18 | libfreetype6-dev
19 | liblcms2-dev
20 | libwebp-dev
21 |
22 | ##django-extensions
23 | graphviz-dev
24 |
--------------------------------------------------------------------------------
/utility/requirements-stretch.apt:
--------------------------------------------------------------------------------
1 | ##basic build dependencies of various Django apps for Debian Jessie 9.x
2 | #build-essential metapackage install: make, gcc, g++,
3 | build-essential
4 | #required to translate
5 | gettext
6 | python3-dev
7 |
8 | ##shared dependencies of:
9 | ##Pillow, pylibmc
10 | zlib1g-dev
11 |
12 | ##Postgresql and psycopg2 dependencies
13 | libpq-dev
14 |
15 | ##Pillow dependencies
16 | libtiff5-dev
17 | libjpeg62-turbo-dev
18 | libfreetype6-dev
19 | liblcms2-dev
20 | libwebp-dev
21 |
22 | ##django-extensions
23 | graphviz-dev
24 |
--------------------------------------------------------------------------------
/todobackend/users/tests/test_models.py:
--------------------------------------------------------------------------------
1 | from test_plus.test import TestCase
2 |
3 |
4 | class TestUser(TestCase):
5 |
6 | def setUp(self):
7 | self.user = self.make_user()
8 |
9 | def test__str__(self):
10 | self.assertEqual(
11 | self.user.__str__(),
12 | 'testuser' # This is the default username for self.make_user()
13 | )
14 |
15 | def test_get_absolute_url(self):
16 | self.assertEqual(
17 | self.user.get_absolute_url(),
18 | '/users/testuser/'
19 | )
20 |
--------------------------------------------------------------------------------
/todobackend/templates/users/user_form.html:
--------------------------------------------------------------------------------
1 | {% extends "base.html" %}
2 | {% load crispy_forms_tags %}
3 |
4 | {% block title %}{{ user.username }}{% endblock %}
5 |
6 | {% block content %}
7 | {{ user.username }}
8 |
17 | {% endblock %}
18 |
--------------------------------------------------------------------------------
/todobackend/todos/migrations/0004_auto_20180226_2352.py:
--------------------------------------------------------------------------------
1 | # Generated by Django 2.0.2 on 2018-02-26 23:52
2 |
3 | from django.db import migrations, models
4 |
5 |
6 | class Migration(migrations.Migration):
7 |
8 | dependencies = [
9 | ('todos', '0003_auto_20180226_2351'),
10 | ]
11 |
12 | operations = [
13 | migrations.AlterField(
14 | model_name='todoitem',
15 | name='session_id',
16 | field=models.CharField(blank=True, db_index=True, editable=False, max_length=255),
17 | ),
18 | ]
19 |
--------------------------------------------------------------------------------
/todobackend/templates/account/password_set.html:
--------------------------------------------------------------------------------
1 | {% extends "account/base.html" %}
2 |
3 | {% load i18n %}
4 | {% load crispy_forms_tags %}
5 |
6 | {% block head_title %}{% trans "Set Password" %}{% endblock %}
7 |
8 | {% block inner %}
9 | {% trans "Set Password" %}
10 |
11 |
16 | {% endblock %}
17 |
18 |
--------------------------------------------------------------------------------
/todobackend/users/adapters.py:
--------------------------------------------------------------------------------
1 | from django.conf import settings
2 | from allauth.account.adapter import DefaultAccountAdapter
3 | from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
4 |
5 |
6 | class AccountAdapter(DefaultAccountAdapter):
7 | def is_open_for_signup(self, request):
8 | return getattr(settings, 'ACCOUNT_ALLOW_REGISTRATION', True)
9 |
10 |
11 | class SocialAccountAdapter(DefaultSocialAccountAdapter):
12 | def is_open_for_signup(self, request, sociallogin):
13 | return getattr(settings, 'ACCOUNT_ALLOW_REGISTRATION', True)
14 |
--------------------------------------------------------------------------------
/todobackend/templates/account/password_reset_done.html:
--------------------------------------------------------------------------------
1 | {% extends "account/base.html" %}
2 |
3 | {% load i18n %}
4 | {% load account %}
5 |
6 | {% block head_title %}{% trans "Password Reset" %}{% endblock %}
7 |
8 | {% block inner %}
9 | {% trans "Password Reset" %}
10 |
11 | {% if user.is_authenticated %}
12 | {% include "account/snippets/already_logged_in.html" %}
13 | {% endif %}
14 |
15 | {% blocktrans %}We have sent you an e-mail. Please contact us if you do not receive it within a few minutes.{% endblocktrans %}
16 | {% endblock %}
17 |
18 |
--------------------------------------------------------------------------------
/docs/index.rst:
--------------------------------------------------------------------------------
1 | .. todobackend documentation master file, created by
2 | sphinx-quickstart.
3 | You can adapt this file completely to your liking, but it should at least
4 | contain the root `toctree` directive.
5 |
6 | Welcome to todobackend's documentation!
7 | ====================================================================
8 |
9 | Contents:
10 |
11 | .. toctree::
12 | :maxdepth: 2
13 |
14 | install
15 | deploy
16 | docker_ec2
17 | tests
18 |
19 |
20 |
21 | Indices and tables
22 | ==================
23 |
24 | * :ref:`genindex`
25 | * :ref:`modindex`
26 | * :ref:`search`
27 |
--------------------------------------------------------------------------------
/todobackend/templates/account/password_change.html:
--------------------------------------------------------------------------------
1 | {% extends "account/base.html" %}
2 |
3 | {% load i18n %}
4 | {% load crispy_forms_tags %}
5 |
6 | {% block head_title %}{% trans "Change Password" %}{% endblock %}
7 |
8 | {% block inner %}
9 | {% trans "Change Password" %}
10 |
11 |
16 | {% endblock %}
17 |
18 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | sudo: true
2 | before_install:
3 | - sudo apt-get update -qq
4 | - sudo apt-get install -qq build-essential gettext python-dev zlib1g-dev libpq-dev xvfb
5 | - sudo apt-get install -qq libtiff4-dev libjpeg8-dev libfreetype6-dev liblcms1-dev libwebp-dev
6 | - sudo apt-get install -qq graphviz-dev python-setuptools python3-dev python-virtualenv python-pip
7 | - sudo apt-get install -qq firefox automake libtool libreadline6 libreadline6-dev libreadline-dev
8 | - sudo apt-get install -qq libsqlite3-dev libxml2 libxml2-dev libssl-dev libbz2-dev wget curl llvm
9 | language: python
10 | python:
11 | - "3.6"
12 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # http://editorconfig.org
2 |
3 | root = true
4 |
5 | [*]
6 | charset = utf-8
7 | end_of_line = lf
8 | insert_final_newline = true
9 | trim_trailing_whitespace = true
10 |
11 | [*.{py,rst,ini}]
12 | indent_style = space
13 | indent_size = 4
14 |
15 | [*.py]
16 | line_length=120
17 | known_first_party=todobackend
18 | multi_line_output=3
19 | default_section=THIRDPARTY
20 |
21 | [*.{html,css,scss,json,yml}]
22 | indent_style = space
23 | indent_size = 2
24 |
25 | [*.md]
26 | trim_trailing_whitespace = false
27 |
28 | [Makefile]
29 | indent_style = tab
30 |
31 | [nginx.conf]
32 | indent_style = space
33 | indent_size = 2
34 |
--------------------------------------------------------------------------------
/README.rst:
--------------------------------------------------------------------------------
1 | todobackend
2 | ===========
3 |
4 | A playable todo list backend
5 |
6 | .. image:: https://img.shields.io/badge/built%20with-Cookiecutter%20Django-ff69b4.svg
7 | :target: https://github.com/pydanny/cookiecutter-django/
8 | :alt: Built with Cookiecutter Django
9 |
10 |
11 | :License: MIT
12 |
13 | Installation
14 | --------------
15 |
16 | Setting Up Dev Environment
17 | ^^^^^^^^^^^^^^^^^^^^^^^^^^
18 |
19 | 1. install docker
20 | 2. git clone the repo
21 | 3. `make init` to create the initial database
22 |
23 | Running the development server
24 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
25 | ::
26 |
27 | docker-compose up -d runserver
28 |
--------------------------------------------------------------------------------
/todobackend/contrib/sites/migrations/0002_alter_domain_unique.py:
--------------------------------------------------------------------------------
1 | import django.contrib.sites.models
2 | from django.db import migrations, models
3 |
4 |
5 | class Migration(migrations.Migration):
6 |
7 | dependencies = [
8 | ('sites', '0001_initial'),
9 | ]
10 |
11 | operations = [
12 | migrations.AlterField(
13 | model_name='site',
14 | name='domain',
15 | field=models.CharField(
16 | max_length=100, unique=True, validators=[django.contrib.sites.models._simple_domain_name_validator],
17 | verbose_name='domain name'
18 | ),
19 | ),
20 | ]
21 |
--------------------------------------------------------------------------------
/todobackend/templates/account/logout.html:
--------------------------------------------------------------------------------
1 | {% extends "account/base.html" %}
2 |
3 | {% load i18n %}
4 |
5 | {% block head_title %}{% trans "Sign Out" %}{% endblock %}
6 |
7 | {% block inner %}
8 | {% trans "Sign Out" %}
9 |
10 | {% trans 'Are you sure you want to sign out?' %}
11 |
12 |
19 |
20 |
21 | {% endblock %}
22 |
23 |
--------------------------------------------------------------------------------
/requirements/production.txt:
--------------------------------------------------------------------------------
1 | # Pro-tip: Try not to put anything here. Avoid dependencies in
2 | # production that aren't in development.
3 | -r base.txt
4 |
5 |
6 |
7 | # WSGI Handler
8 | # ------------------------------------------------
9 | gevent==1.2.2
10 | gunicorn==19.7.1
11 |
12 | # Static and Media Storage
13 | # ------------------------------------------------
14 | boto3==1.5.33
15 | django-storages==1.6.5
16 |
17 |
18 | # Email backends for Mailgun, Postmark, SendGrid and more
19 | # -------------------------------------------------------
20 | django-anymail==1.4
21 |
22 | # Raven is the Sentry client
23 | # --------------------------
24 | raven==6.5.0
25 |
26 |
27 |
--------------------------------------------------------------------------------
/todobackend/todos/migrations/0005_auto_20180227_0045.py:
--------------------------------------------------------------------------------
1 | # Generated by Django 2.0.2 on 2018-02-27 00:45
2 |
3 | from django.db import migrations
4 |
5 |
6 | class Migration(migrations.Migration):
7 |
8 | dependencies = [
9 | ('todos', '0004_auto_20180226_2352'),
10 | ]
11 |
12 | operations = [
13 | migrations.AlterModelOptions(
14 | name='todoitem',
15 | options={'ordering': ['-completed_at', 'priority', '-created_at']},
16 | ),
17 | migrations.RenameField(
18 | model_name='todoitem',
19 | old_name='completed_date',
20 | new_name='completed_at',
21 | ),
22 | ]
23 |
--------------------------------------------------------------------------------
/todobackend/users/urls.py:
--------------------------------------------------------------------------------
1 | from django.conf.urls import url
2 |
3 | from . import views
4 |
5 | app_name = 'users'
6 | urlpatterns = [
7 | url(
8 | regex=r'^$',
9 | view=views.UserListView.as_view(),
10 | name='list'
11 | ),
12 | url(
13 | regex=r'^~redirect/$',
14 | view=views.UserRedirectView.as_view(),
15 | name='redirect'
16 | ),
17 | url(
18 | regex=r'^(?P[\w.@+-]+)/$',
19 | view=views.UserDetailView.as_view(),
20 | name='detail'
21 | ),
22 | url(
23 | regex=r'^~update/$',
24 | view=views.UserUpdateView.as_view(),
25 | name='update'
26 | ),
27 | ]
28 |
--------------------------------------------------------------------------------
/todobackend/todos/migrations/0003_auto_20180226_2351.py:
--------------------------------------------------------------------------------
1 | # Generated by Django 2.0.2 on 2018-02-26 23:51
2 |
3 | from django.db import migrations, models
4 | import uuid
5 |
6 |
7 | class Migration(migrations.Migration):
8 |
9 | dependencies = [
10 | ('todos', '0002_todoitem_uuid'),
11 | ]
12 |
13 | operations = [
14 | migrations.RemoveField(
15 | model_name='todoitem',
16 | name='id',
17 | ),
18 | migrations.AlterField(
19 | model_name='todoitem',
20 | name='uuid',
21 | field=models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False),
22 | ),
23 | ]
24 |
--------------------------------------------------------------------------------
/todobackend/todos/templates/todo.html:
--------------------------------------------------------------------------------
1 |
19 |
--------------------------------------------------------------------------------
/todobackend/users/models.py:
--------------------------------------------------------------------------------
1 | from django.contrib.auth.models import AbstractUser
2 | from django.db import models
3 | from django.urls import reverse
4 | from django.utils.encoding import python_2_unicode_compatible
5 | from django.utils.translation import ugettext_lazy as _
6 |
7 |
8 | @python_2_unicode_compatible
9 | class User(AbstractUser):
10 |
11 | # First Name and Last Name do not cover name patterns
12 | # around the globe.
13 | name = models.CharField(_('Name of User'), blank=True, max_length=255)
14 |
15 | def __str__(self):
16 | return self.username
17 |
18 | def get_absolute_url(self):
19 | return reverse('users:detail', kwargs={'username': self.username})
20 |
--------------------------------------------------------------------------------
/todobackend/static/sass/project.scss:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | // project specific CSS goes here
6 |
7 | ////////////////////////////////
8 | //Variables//
9 | ////////////////////////////////
10 |
11 | // Alert colors
12 |
13 | $white: #fff;
14 | $mint-green: #d6e9c6;
15 | $black: #000;
16 | $pink: #f2dede;
17 | $dark-pink: #eed3d7;
18 | $red: #b94a48;
19 |
20 | ////////////////////////////////
21 | //Alerts//
22 | ////////////////////////////////
23 |
24 | // bootstrap alert CSS, translated to the django-standard levels of
25 | // debug, info, success, warning, error
26 |
27 | .alert-debug {
28 | background-color: $white;
29 | border-color: $mint-green;
30 | color: $black;
31 | }
32 |
33 | .alert-error {
34 | background-color: $pink;
35 | border-color: $dark-pink;
36 | color: $red;
37 | }
38 |
--------------------------------------------------------------------------------
/todobackend/todos/api/views.py:
--------------------------------------------------------------------------------
1 | # encoding: utf-8
2 | from rest_framework import viewsets
3 | from todobackend.todos.api.serializers import TODOItemSerializer
4 | from todobackend.todos.models import TODOItem
5 |
6 | class TodoItemViewSet(viewsets.ModelViewSet):
7 | serializer_class = TODOItemSerializer
8 |
9 | @property
10 | def session_id(self):
11 | if not self.request.session.session_key:
12 | self.request.session.save()
13 | return self.request.META.get('HTTP_SESSION_ID') or self.request.session.session_key
14 |
15 | def get_queryset(self):
16 | return TODOItem.objects.filter(session_id=self.session_id)
17 |
18 | def perform_create(self, serializer):
19 | serializer.save(session_id=self.session_id)
20 | TODOItem.objects.trim_rows()
21 |
--------------------------------------------------------------------------------
/todobackend/templates/account/signup.html:
--------------------------------------------------------------------------------
1 | {% extends "account/base.html" %}
2 |
3 | {% load i18n %}
4 | {% load crispy_forms_tags %}
5 |
6 | {% block head_title %}{% trans "Signup" %}{% endblock %}
7 |
8 | {% block inner %}
9 | {% trans "Sign Up" %}
10 |
11 | {% blocktrans %}Already have an account? Then please sign in .{% endblocktrans %}
12 |
13 |
21 |
22 | {% endblock %}
23 |
24 |
--------------------------------------------------------------------------------
/todobackend/static/js/project.js:
--------------------------------------------------------------------------------
1 | /* Project specific Javascript goes here. */
2 |
3 | /*
4 | Formatting hack to get around crispy-forms unfortunate hardcoding
5 | in helpers.FormHelper:
6 |
7 | if template_pack == 'bootstrap4':
8 | grid_colum_matcher = re.compile('\w*col-(xs|sm|md|lg|xl)-\d+\w*')
9 | using_grid_layout = (grid_colum_matcher.match(self.label_class) or
10 | grid_colum_matcher.match(self.field_class))
11 | if using_grid_layout:
12 | items['using_grid_layout'] = True
13 |
14 | Issues with the above approach:
15 |
16 | 1. Fragile: Assumes Bootstrap 4's API doesn't change (it does)
17 | 2. Unforgiving: Doesn't allow for any variation in template design
18 | 3. Really Unforgiving: No way to override this behavior
19 | 4. Undocumented: No mention in the documentation, or it's too hard for me to find
20 | */
21 | $('.form-group').removeClass('row');
22 |
--------------------------------------------------------------------------------
/todobackend/templates/account/verified_email_required.html:
--------------------------------------------------------------------------------
1 | {% extends "account/base.html" %}
2 |
3 | {% load i18n %}
4 |
5 | {% block head_title %}{% trans "Verify Your E-mail Address" %}{% endblock %}
6 |
7 | {% block inner %}
8 | {% trans "Verify Your E-mail Address" %}
9 |
10 | {% url 'account_email' as email_url %}
11 |
12 | {% blocktrans %}This part of the site requires us to verify that
13 | you are who you claim to be. For this purpose, we require that you
14 | verify ownership of your e-mail address. {% endblocktrans %}
15 |
16 | {% blocktrans %}We have sent an e-mail to you for
17 | verification. Please click on the link inside this e-mail. Please
18 | contact us if you do not receive it within a few minutes.{% endblocktrans %}
19 |
20 | {% blocktrans %}Note: you can still change your e-mail address .{% endblocktrans %}
21 |
22 |
23 | {% endblock %}
24 |
25 |
--------------------------------------------------------------------------------
/todobackend/templates/users/user_detail.html:
--------------------------------------------------------------------------------
1 | {% extends "base.html" %}
2 | {% load static %}
3 |
4 | {% block title %}User: {{ object.username }}{% endblock %}
5 |
6 | {% block content %}
7 |
8 |
9 |
10 |
11 |
12 |
{{ object.username }}
13 | {% if object.name %}
14 |
{{ object.name }}
15 | {% endif %}
16 |
17 |
18 |
19 | {% if object == request.user %}
20 |
21 |
30 |
31 | {% endif %}
32 |
33 |
34 |
35 | {% endblock content %}
36 |
37 |
--------------------------------------------------------------------------------
/todobackend/templates/account/password_reset.html:
--------------------------------------------------------------------------------
1 | {% extends "account/base.html" %}
2 |
3 | {% load i18n %}
4 | {% load account %}
5 | {% load crispy_forms_tags %}
6 |
7 | {% block head_title %}{% trans "Password Reset" %}{% endblock %}
8 |
9 | {% block inner %}
10 |
11 | {% trans "Password Reset" %}
12 | {% if user.is_authenticated %}
13 | {% include "account/snippets/already_logged_in.html" %}
14 | {% endif %}
15 |
16 | {% trans "Forgotten your password? Enter your e-mail address below, and we'll send you an e-mail allowing you to reset it." %}
17 |
18 |
23 |
24 | {% blocktrans %}Please contact us if you have any trouble resetting your password.{% endblocktrans %}
25 | {% endblock %}
26 |
27 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "todobackend",
3 | "version": "1.0.0",
4 | "description": "todobackend ===========",
5 | "main": "app.js",
6 | "directories": {
7 | "doc": "docs"
8 | },
9 | "scripts": {
10 | "test": "echo \"Error: no test specified\" && exit 1",
11 | "build_todo_raw": "npx webpack todobackend/static_src/js/todo/todo.js --output todobackend/static/js/app.js",
12 | "build_todo": "npx webpack --config webpack.config.js"
13 | },
14 | "repository": {
15 | "type": "git",
16 | "url": "git+https://github.com/variable/todobackend.git"
17 | },
18 | "author": "",
19 | "license": "ISC",
20 | "bugs": {
21 | "url": "https://github.com/variable/todobackend/issues"
22 | },
23 | "homepage": "https://github.com/variable/todobackend#readme",
24 | "devDependencies": {
25 | "webpack": "^4.1.0",
26 | "webpack-cli": "^2.0.10"
27 | },
28 | "dependencies": {
29 | "vue": "^2.5.13",
30 | "vue-resource": "^1.5.0",
31 | "vuex": "^3.0.1"
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/todobackend/todos/migrations/0001_initial.py:
--------------------------------------------------------------------------------
1 | # Generated by Django 2.0.2 on 2018-02-26 19:11
2 |
3 | from django.db import migrations, models
4 |
5 |
6 | class Migration(migrations.Migration):
7 |
8 | initial = True
9 |
10 | dependencies = [
11 | ]
12 |
13 | operations = [
14 | migrations.CreateModel(
15 | name='TODOItem',
16 | fields=[
17 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
18 | ('session_id', models.CharField(blank=True, db_index=True, max_length=255)),
19 | ('description', models.CharField(max_length=255)),
20 | ('priority', models.IntegerField(default=10)),
21 | ('created_at', models.DateTimeField(auto_now_add=True)),
22 | ('completed_date', models.DateTimeField(null=True)),
23 | ],
24 | options={
25 | 'ordering': ['-completed_date', 'priority', '-created_at'],
26 | },
27 | ),
28 | ]
29 |
--------------------------------------------------------------------------------
/todobackend/todos/models.py:
--------------------------------------------------------------------------------
1 | import uuid
2 | from django.db import models
3 | from django.db.models import Max, QuerySet
4 |
5 |
6 | class TODOItemQuerySet(QuerySet):
7 | def trim_rows(self):
8 | # TODO move to manager
9 | MAX = 1000000
10 | BUFFER = 5000
11 | total = self.count()
12 | if total > MAX:
13 | pk_pointer = self.order_by('pk')[:total-MAX+BUFFER].aggregate(Max('pk'))['pk__max']
14 | self.filter(pk__lt=pk_pointer).delete()
15 |
16 |
17 | class TODOItem(models.Model):
18 | uuid = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True)
19 | session_id = models.CharField(max_length=255, db_index=True, blank=True, editable=False)
20 | description = models.CharField(max_length=255)
21 | priority = models.IntegerField(default=10)
22 | created_at = models.DateTimeField(auto_now_add=True)
23 | completed_at = models.DateTimeField(null=True)
24 | objects = TODOItemQuerySet.as_manager()
25 |
26 |
27 | class Meta:
28 | ordering = ['priority', '-created_at']
29 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | The MIT License (MIT)
3 | Copyright (c) 2018, James Lin
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6 |
7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8 |
9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
10 |
11 |
--------------------------------------------------------------------------------
/todobackend/templates/account/password_reset_from_key.html:
--------------------------------------------------------------------------------
1 | {% extends "account/base.html" %}
2 |
3 | {% load i18n %}
4 | {% load crispy_forms_tags %}
5 | {% block head_title %}{% trans "Change Password" %}{% endblock %}
6 |
7 | {% block inner %}
8 | {% if token_fail %}{% trans "Bad Token" %}{% else %}{% trans "Change Password" %}{% endif %}
9 |
10 | {% if token_fail %}
11 | {% url 'account_reset_password' as passwd_reset_url %}
12 | {% blocktrans %}The password reset link was invalid, possibly because it has already been used. Please request a new password reset .{% endblocktrans %}
13 | {% else %}
14 | {% if form %}
15 |
20 | {% else %}
21 | {% trans 'Your password is now changed.' %}
22 | {% endif %}
23 | {% endif %}
24 | {% endblock %}
25 |
26 |
--------------------------------------------------------------------------------
/todobackend/templates/account/email_confirm.html:
--------------------------------------------------------------------------------
1 | {% extends "account/base.html" %}
2 |
3 | {% load i18n %}
4 | {% load account %}
5 |
6 | {% block head_title %}{% trans "Confirm E-mail Address" %}{% endblock %}
7 |
8 |
9 | {% block inner %}
10 | {% trans "Confirm E-mail Address" %}
11 |
12 | {% if confirmation %}
13 |
14 | {% user_display confirmation.email_address.user as user_display %}
15 |
16 | {% blocktrans with confirmation.email_address.email as email %}Please confirm that {{ email }} is an e-mail address for user {{ user_display }}.{% endblocktrans %}
17 |
18 |
22 |
23 | {% else %}
24 |
25 | {% url 'account_email' as email_url %}
26 |
27 | {% blocktrans %}This e-mail confirmation link expired or is invalid. Please issue a new e-mail confirmation request .{% endblocktrans %}
28 |
29 | {% endif %}
30 |
31 | {% endblock %}
32 |
33 |
--------------------------------------------------------------------------------
/requirements/base.txt:
--------------------------------------------------------------------------------
1 | # Wheel 0.25+ needed to install certain packages on CPython 3.5+
2 | # like Pillow and psycopg2
3 | # See http://bitly.com/wheel-building-fails-CPython-35
4 | # Verified bug on Python 3.5.1
5 | wheel==0.30.0
6 |
7 |
8 | # Conservative Django
9 | django==2.0.2 # pyup: < 2.1
10 |
11 | # Configuration
12 | django-environ==0.4.4
13 | whitenoise==3.3.1
14 |
15 |
16 | # Forms
17 | django-crispy-forms==1.7.0
18 |
19 | # Models
20 | django-model-utils==3.1.1
21 |
22 | # Images
23 | Pillow==5.0.0
24 |
25 | # Password storage
26 | argon2-cffi==18.1.0
27 |
28 | # For user registration, either via email or social
29 | # Well-built with regular release cycles!
30 | django-allauth==0.35.0
31 |
32 |
33 | # Python-PostgreSQL Database Adapter
34 | # psycopg2==2.7.4 --no-binary psycopg2
35 |
36 | # Unicode slugification
37 | awesome-slugify==1.6.5
38 |
39 | # Time zones support
40 | pytz==2018.3
41 |
42 | # Redis support
43 | django-redis==4.8.0
44 | redis>=2.10.5
45 |
46 |
47 |
48 |
49 |
50 | # Your custom requirements go here
51 | djangorestframework~=3.7.7
52 | mysqlclient==1.3.12
53 | django-cors-headers~=2.1.0
54 |
--------------------------------------------------------------------------------
/manage.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | import os
3 | import sys
4 |
5 | if __name__ == '__main__':
6 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local')
7 |
8 | try:
9 | from django.core.management import execute_from_command_line
10 | except ImportError:
11 | # The above import may fail for some other reason. Ensure that the
12 | # issue is really that Django is missing to avoid masking other
13 | # exceptions on Python 2.
14 | try:
15 | import django # noqa
16 | except ImportError:
17 | raise ImportError(
18 | "Couldn't import Django. Are you sure it's installed and "
19 | "available on your PYTHONPATH environment variable? Did you "
20 | "forget to activate a virtual environment?"
21 | )
22 | raise
23 |
24 | # This allows easy placement of apps within the interior
25 | # todobackend directory.
26 | current_path = os.path.dirname(os.path.abspath(__file__))
27 | sys.path.append(os.path.join(current_path, 'todobackend'))
28 |
29 | execute_from_command_line(sys.argv)
30 |
--------------------------------------------------------------------------------
/todobackend/contrib/sites/migrations/0001_initial.py:
--------------------------------------------------------------------------------
1 | import django.contrib.sites.models
2 | from django.contrib.sites.models import _simple_domain_name_validator
3 | from django.db import migrations, models
4 |
5 |
6 | class Migration(migrations.Migration):
7 |
8 | dependencies = []
9 |
10 | operations = [
11 | migrations.CreateModel(
12 | name='Site',
13 | fields=[
14 | ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
15 | ('domain', models.CharField(
16 | max_length=100, verbose_name='domain name', validators=[_simple_domain_name_validator]
17 | )),
18 | ('name', models.CharField(max_length=50, verbose_name='display name')),
19 | ],
20 | options={
21 | 'ordering': ('domain',),
22 | 'db_table': 'django_site',
23 | 'verbose_name': 'site',
24 | 'verbose_name_plural': 'sites',
25 | },
26 | bases=(models.Model,),
27 | managers=[
28 | ('objects', django.contrib.sites.models.SiteManager()),
29 | ],
30 | ),
31 | ]
32 |
--------------------------------------------------------------------------------
/todobackend/contrib/sites/migrations/0003_set_site_domain_and_name.py:
--------------------------------------------------------------------------------
1 | """
2 | To understand why this file is here, please read:
3 |
4 | http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django
5 | """
6 | from django.conf import settings
7 | from django.db import migrations
8 |
9 |
10 | def update_site_forward(apps, schema_editor):
11 | """Set site domain and name."""
12 | Site = apps.get_model('sites', 'Site')
13 | Site.objects.update_or_create(
14 | id=settings.SITE_ID,
15 | defaults={
16 | 'domain': 'todobackend.lin.nz',
17 | 'name': 'todobackend'
18 | }
19 | )
20 |
21 |
22 | def update_site_backward(apps, schema_editor):
23 | """Revert site domain and name to default."""
24 | Site = apps.get_model('sites', 'Site')
25 | Site.objects.update_or_create(
26 | id=settings.SITE_ID,
27 | defaults={
28 | 'domain': 'example.com',
29 | 'name': 'example.com'
30 | }
31 | )
32 |
33 |
34 | class Migration(migrations.Migration):
35 |
36 | dependencies = [
37 | ('sites', '0002_alter_domain_unique'),
38 | ]
39 |
40 | operations = [
41 | migrations.RunPython(update_site_forward, update_site_backward),
42 | ]
43 |
--------------------------------------------------------------------------------
/todobackend/users/admin.py:
--------------------------------------------------------------------------------
1 | from django import forms
2 | from django.contrib import admin
3 | from django.contrib.auth.admin import UserAdmin as AuthUserAdmin
4 | from django.contrib.auth.forms import UserChangeForm, UserCreationForm
5 | from .models import User
6 |
7 |
8 | class MyUserChangeForm(UserChangeForm):
9 | class Meta(UserChangeForm.Meta):
10 | model = User
11 |
12 |
13 | class MyUserCreationForm(UserCreationForm):
14 |
15 | error_message = UserCreationForm.error_messages.update({
16 | 'duplicate_username': 'This username has already been taken.'
17 | })
18 |
19 | class Meta(UserCreationForm.Meta):
20 | model = User
21 |
22 | def clean_username(self):
23 | username = self.cleaned_data["username"]
24 | try:
25 | User.objects.get(username=username)
26 | except User.DoesNotExist:
27 | return username
28 | raise forms.ValidationError(self.error_messages['duplicate_username'])
29 |
30 |
31 | @admin.register(User)
32 | class MyUserAdmin(AuthUserAdmin):
33 | form = MyUserChangeForm
34 | add_form = MyUserCreationForm
35 | fieldsets = (
36 | ('User Profile', {'fields': ('name',)}),
37 | ) + AuthUserAdmin.fieldsets
38 | list_display = ('username', 'name', 'is_superuser')
39 | search_fields = ['name']
40 |
--------------------------------------------------------------------------------
/docker-compose.yml:
--------------------------------------------------------------------------------
1 | # flatten compose structure due to 'extends' not available in version 3 yet
2 | # https://github.com/moby/moby/issues/31101
3 | version: '3'
4 |
5 | volumes:
6 | todobackend-db:
7 |
8 |
9 | services:
10 | db:
11 | image: mysql:5.6
12 | volumes:
13 | - todobackend-db:/var/lib/mysql
14 | ports:
15 | - 3306:3306
16 | environment:
17 | - MYSQL_ALLOW_EMPTY_PASSWORD=true
18 | container_name: todobackend_db
19 | runserver:
20 | build: .
21 | command:
22 | - python manage.py runserver 0.0.0.0:8000
23 | volumes:
24 | - ./:/usr/django/app
25 | environment:
26 | - DATABASE_URL=mysql://root:@db/todobackend
27 | ports:
28 | - 8000:8000
29 | depends_on:
30 | - db
31 | migrate:
32 | build: .
33 | command:
34 | - python manage.py migrate
35 | volumes:
36 | - ./:/usr/django/app
37 | environment:
38 | - DATABASE_URL=mysql://root:@db/todobackend
39 | ports:
40 | - 8000:8000
41 | depends_on:
42 | - db
43 | makemigrations:
44 | build: .
45 | command:
46 | - python manage.py makemigrations
47 | volumes:
48 | - ./:/usr/django/app
49 | environment:
50 | - DATABASE_URL=mysql://root:@db/todobackend
51 | ports:
52 | - 8000:8000
53 | depends_on:
54 | - db
55 |
--------------------------------------------------------------------------------
/.idea/todobackend.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/.idea/runConfigurations/Docker__tests___all.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/.idea/runConfigurations/Docker__tests___module__users.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/todobackend/users/views.py:
--------------------------------------------------------------------------------
1 | from django.contrib.auth.mixins import LoginRequiredMixin
2 | from django.urls import reverse
3 | from django.views.generic import DetailView, ListView, RedirectView, UpdateView
4 |
5 | from .models import User
6 |
7 |
8 | class UserDetailView(LoginRequiredMixin, DetailView):
9 | model = User
10 | # These next two lines tell the view to index lookups by username
11 | slug_field = 'username'
12 | slug_url_kwarg = 'username'
13 |
14 |
15 | class UserRedirectView(LoginRequiredMixin, RedirectView):
16 | permanent = False
17 |
18 | def get_redirect_url(self):
19 | return reverse('users:detail',
20 | kwargs={'username': self.request.user.username})
21 |
22 |
23 | class UserUpdateView(LoginRequiredMixin, UpdateView):
24 |
25 | fields = ['name', ]
26 |
27 | # we already imported User in the view code above, remember?
28 | model = User
29 |
30 | # send the user back to their own page after a successful update
31 | def get_success_url(self):
32 | return reverse('users:detail',
33 | kwargs={'username': self.request.user.username})
34 |
35 | def get_object(self):
36 | # Only get the User record for the user making the request
37 | return User.objects.get(username=self.request.user.username)
38 |
39 |
40 | class UserListView(LoginRequiredMixin, ListView):
41 | model = User
42 | # These next two lines tell the view to index lookups by username
43 | slug_field = 'username'
44 | slug_url_kwarg = 'username'
45 |
--------------------------------------------------------------------------------
/.idea/runConfigurations/Docker__migrate.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/todobackend/users/tests/test_admin.py:
--------------------------------------------------------------------------------
1 | from test_plus.test import TestCase
2 |
3 | from ..admin import MyUserCreationForm
4 |
5 |
6 | class TestMyUserCreationForm(TestCase):
7 |
8 | def setUp(self):
9 | self.user = self.make_user('notalamode', 'notalamodespassword')
10 |
11 | def test_clean_username_success(self):
12 | # Instantiate the form with a new username
13 | form = MyUserCreationForm({
14 | 'username': 'alamode',
15 | 'password1': '7jefB#f@Cc7YJB]2v',
16 | 'password2': '7jefB#f@Cc7YJB]2v',
17 | })
18 | # Run is_valid() to trigger the validation
19 | valid = form.is_valid()
20 | self.assertTrue(valid)
21 |
22 | # Run the actual clean_username method
23 | username = form.clean_username()
24 | self.assertEqual('alamode', username)
25 |
26 | def test_clean_username_false(self):
27 | # Instantiate the form with the same username as self.user
28 | form = MyUserCreationForm({
29 | 'username': self.user.username,
30 | 'password1': 'notalamodespassword',
31 | 'password2': 'notalamodespassword',
32 | })
33 | # Run is_valid() to trigger the validation, which is going to fail
34 | # because the username is already taken
35 | valid = form.is_valid()
36 | self.assertFalse(valid)
37 |
38 | # The form.errors dict should contain a single error called 'username'
39 | self.assertTrue(len(form.errors) == 1)
40 | self.assertTrue('username' in form.errors)
41 |
--------------------------------------------------------------------------------
/.idea/runConfigurations/Docker__tests___file__test_models.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/.idea/runConfigurations/Docker__tests___class__TestUser.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/.idea/runConfigurations/Docker__runserver.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/.idea/runConfigurations/Docker__runserver_plus.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/.idea/runConfigurations/Docker__tests___specific__test_get_absolute_url.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/todobackend/templates/account/login.html:
--------------------------------------------------------------------------------
1 | {% extends "account/base.html" %}
2 |
3 | {% load i18n %}
4 | {% load account socialaccount %}
5 | {% load crispy_forms_tags %}
6 |
7 | {% block head_title %}{% trans "Sign In" %}{% endblock %}
8 |
9 | {% block inner %}
10 |
11 | {% trans "Sign In" %}
12 |
13 | {% get_providers as socialaccount_providers %}
14 |
15 | {% if socialaccount_providers %}
16 | {% blocktrans with site.name as site_name %}Please sign in with one
17 | of your existing third party accounts. Or, sign up
18 | for a {{ site_name }} account and sign in below:{% endblocktrans %}
19 |
20 |
21 |
22 |
23 | {% include "socialaccount/snippets/provider_list.html" with process="login" %}
24 |
25 |
26 |
{% trans 'or' %}
27 |
28 |
29 |
30 | {% include "socialaccount/snippets/login_extra.html" %}
31 |
32 | {% else %}
33 | {% blocktrans %}If you have not created an account yet, then please
34 | sign up first.{% endblocktrans %}
35 | {% endif %}
36 |
37 |
46 |
47 | {% endblock %}
48 |
49 |
--------------------------------------------------------------------------------
/config/urls.py:
--------------------------------------------------------------------------------
1 | from django.conf import settings
2 | from django.conf.urls import include, url
3 | from django.conf.urls.static import static
4 | from django.contrib import admin
5 | from django.views.generic import TemplateView
6 | from django.views import defaults as default_views
7 | from django.urls import path
8 |
9 | urlpatterns = [
10 | url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name='home'),
11 | url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name='about'),
12 |
13 | # Django Admin, use {% url 'admin:index' %}
14 | url(settings.ADMIN_URL, admin.site.urls),
15 |
16 | path('', include('todobackend.todos.urls')),
17 | # User management
18 | url(r'^users/', include('todobackend.users.urls', namespace='users')),
19 | url(r'^accounts/', include('allauth.urls')),
20 |
21 | # Your stuff: custom urls includes go here
22 |
23 |
24 | ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
25 |
26 | if settings.DEBUG:
27 | # This allows the error pages to be debugged during development, just visit
28 | # these url in browser to see how these error pages look like.
29 | urlpatterns += [
30 | url(r'^400/$', default_views.bad_request, kwargs={'exception': Exception('Bad Request!')}),
31 | url(r'^403/$', default_views.permission_denied, kwargs={'exception': Exception('Permission Denied')}),
32 | url(r'^404/$', default_views.page_not_found, kwargs={'exception': Exception('Page not Found')}),
33 | url(r'^500/$', default_views.server_error),
34 | ]
35 | if 'debug_toolbar' in settings.INSTALLED_APPS:
36 | import debug_toolbar
37 | urlpatterns = [
38 | url(r'^__debug__/', include(debug_toolbar.urls)),
39 | ] + urlpatterns
40 |
--------------------------------------------------------------------------------
/utility/install_python_dependencies.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | WORK_DIR="$(dirname "$0")"
4 | PROJECT_DIR="$(dirname "$WORK_DIR")"
5 |
6 | pip --version >/dev/null 2>&1 || {
7 | echo >&2 -e "\npip is required but it's not installed."
8 | echo >&2 -e "You can install it by running the following command:\n"
9 | echo >&2 "wget https://bootstrap.pypa.io/get-pip.py --output-document=get-pip.py; chmod +x get-pip.py; sudo -H python3 get-pip.py"
10 | echo >&2 -e "\n"
11 | echo >&2 -e "\nFor more information, see pip documentation: https://pip.pypa.io/en/latest/"
12 | exit 1;
13 | }
14 |
15 | virtualenv --version >/dev/null 2>&1 || {
16 | echo >&2 -e "\nvirtualenv is required but it's not installed."
17 | echo >&2 -e "You can install it by running the following command:\n"
18 | echo >&2 "sudo -H pip3 install virtualenv"
19 | echo >&2 -e "\n"
20 | echo >&2 -e "\nFor more information, see virtualenv documentation: https://virtualenv.pypa.io/en/latest/"
21 | exit 1;
22 | }
23 |
24 | if [ -z "$VIRTUAL_ENV" ]; then
25 | echo >&2 -e "\nYou need activate a virtualenv first"
26 | echo >&2 -e 'If you do not have a virtualenv created, run the following command to create and automatically activate a new virtualenv named "venv" on current folder:\n'
27 | echo >&2 -e "virtualenv venv --python=\`which python3\`"
28 | echo >&2 -e "\nTo leave/disable the currently active virtualenv, run the following command:\n"
29 | echo >&2 "deactivate"
30 | echo >&2 -e "\nTo activate the virtualenv again, run the following command:\n"
31 | echo >&2 "source venv/bin/activate"
32 | echo >&2 -e "\nFor more information, see virtualenv documentation: https://virtualenv.pypa.io/en/latest/"
33 | echo >&2 -e "\n"
34 | exit 1;
35 | else
36 |
37 | pip install -r $PROJECT_DIR/requirements/local.txt
38 | pip install -r $PROJECT_DIR/requirements/test.txt
39 |
40 | fi
41 |
--------------------------------------------------------------------------------
/todobackend/users/tests/test_urls.py:
--------------------------------------------------------------------------------
1 | from django.urls import reverse, resolve
2 |
3 | from test_plus.test import TestCase
4 |
5 |
6 | class TestUserURLs(TestCase):
7 | """Test URL patterns for users app."""
8 |
9 | def setUp(self):
10 | self.user = self.make_user()
11 |
12 | def test_list_reverse(self):
13 | """users:list should reverse to /users/."""
14 | self.assertEqual(reverse('users:list'), '/users/')
15 |
16 | def test_list_resolve(self):
17 | """/users/ should resolve to users:list."""
18 | self.assertEqual(resolve('/users/').view_name, 'users:list')
19 |
20 | def test_redirect_reverse(self):
21 | """users:redirect should reverse to /users/~redirect/."""
22 | self.assertEqual(reverse('users:redirect'), '/users/~redirect/')
23 |
24 | def test_redirect_resolve(self):
25 | """/users/~redirect/ should resolve to users:redirect."""
26 | self.assertEqual(
27 | resolve('/users/~redirect/').view_name,
28 | 'users:redirect'
29 | )
30 |
31 | def test_detail_reverse(self):
32 | """users:detail should reverse to /users/testuser/."""
33 | self.assertEqual(
34 | reverse('users:detail', kwargs={'username': 'testuser'}),
35 | '/users/testuser/'
36 | )
37 |
38 | def test_detail_resolve(self):
39 | """/users/testuser/ should resolve to users:detail."""
40 | self.assertEqual(resolve('/users/testuser/').view_name, 'users:detail')
41 |
42 | def test_update_reverse(self):
43 | """users:update should reverse to /users/~update/."""
44 | self.assertEqual(reverse('users:update'), '/users/~update/')
45 |
46 | def test_update_resolve(self):
47 | """/users/~update/ should resolve to users:update."""
48 | self.assertEqual(
49 | resolve('/users/~update/').view_name,
50 | 'users:update'
51 | )
52 |
--------------------------------------------------------------------------------
/todobackend/templates/pages/home.html:
--------------------------------------------------------------------------------
1 | {% extends "base.html" %}
2 | {% load staticfiles %}
3 |
4 | {% block content %}
5 |
6 |
7 |
8 |
ToDo API Playground
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | {% csrf_token %}
17 | {% include 'todo.html' %}
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 | There is only one API here, which provides full RESTful service on ToDo Items. Purposed to
27 | help everyone to test their code to integrate with a RESTful API.
28 | ToDo items are grouped by sessions, you can override the session id by specifying SESSION-ID
29 | value in your request header.
30 | There is a maximum rows limit in ToDo table globally to protect the service from being
31 | overrun, once maximum rows has reached, it will start evicting oldest items.
32 | Any problems, email james@lin.net.nz
33 |
34 |
35 |
36 |
37 |
45 | {% endblock %}
46 |
47 | {% block javascript %}
48 | {{ block.super }}
49 |
50 | {% endblock %}
51 |
--------------------------------------------------------------------------------
/config/wsgi.py:
--------------------------------------------------------------------------------
1 | """
2 | WSGI config for todobackend project.
3 |
4 | This module contains the WSGI application used by Django's development server
5 | and any production WSGI deployments. It should expose a module-level variable
6 | named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
7 | this application via the ``WSGI_APPLICATION`` setting.
8 |
9 | Usually you will have the standard Django WSGI application here, but it also
10 | might make sense to replace the whole Django WSGI application with a custom one
11 | that later delegates to the Django one. For example, you could introduce WSGI
12 | middleware here, or combine a Django application with an application of another
13 | framework.
14 |
15 | """
16 | import os
17 | import sys
18 |
19 | from django.core.wsgi import get_wsgi_application
20 |
21 | # This allows easy placement of apps within the interior
22 | # todobackend directory.
23 | app_path = os.path.abspath(os.path.join(
24 | os.path.dirname(os.path.abspath(__file__)), os.pardir))
25 | sys.path.append(os.path.join(app_path, 'todobackend'))
26 |
27 | if os.environ.get('DJANGO_SETTINGS_MODULE') == 'config.settings.production':
28 | from raven.contrib.django.raven_compat.middleware.wsgi import Sentry
29 |
30 | # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
31 | # if running multiple sites in the same mod_wsgi process. To fix this, use
32 | # mod_wsgi daemon mode with each site in its own daemon process, or use
33 | # os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.production"
34 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production")
35 |
36 | # This application object is used by any WSGI server configured to use this
37 | # file. This includes Django's development server, if the WSGI_APPLICATION
38 | # setting points here.
39 | application = get_wsgi_application()
40 | if os.environ.get('DJANGO_SETTINGS_MODULE') == 'config.settings.production':
41 | application = Sentry(application)
42 | # Apply WSGI middleware here.
43 | # from helloworld.wsgi import HelloWorldApplication
44 | # application = HelloWorldApplication(application)
45 |
--------------------------------------------------------------------------------
/todobackend/users/tests/test_views.py:
--------------------------------------------------------------------------------
1 | from django.test import RequestFactory
2 |
3 | from test_plus.test import TestCase
4 |
5 | from ..views import (
6 | UserRedirectView,
7 | UserUpdateView
8 | )
9 |
10 |
11 | class BaseUserTestCase(TestCase):
12 |
13 | def setUp(self):
14 | self.user = self.make_user()
15 | self.factory = RequestFactory()
16 |
17 |
18 | class TestUserRedirectView(BaseUserTestCase):
19 |
20 | def test_get_redirect_url(self):
21 | # Instantiate the view directly. Never do this outside a test!
22 | view = UserRedirectView()
23 | # Generate a fake request
24 | request = self.factory.get('/fake-url')
25 | # Attach the user to the request
26 | request.user = self.user
27 | # Attach the request to the view
28 | view.request = request
29 | # Expect: '/users/testuser/', as that is the default username for
30 | # self.make_user()
31 | self.assertEqual(
32 | view.get_redirect_url(),
33 | '/users/testuser/'
34 | )
35 |
36 |
37 | class TestUserUpdateView(BaseUserTestCase):
38 |
39 | def setUp(self):
40 | # call BaseUserTestCase.setUp()
41 | super(TestUserUpdateView, self).setUp()
42 | # Instantiate the view directly. Never do this outside a test!
43 | self.view = UserUpdateView()
44 | # Generate a fake request
45 | request = self.factory.get('/fake-url')
46 | # Attach the user to the request
47 | request.user = self.user
48 | # Attach the request to the view
49 | self.view.request = request
50 |
51 | def test_get_success_url(self):
52 | # Expect: '/users/testuser/', as that is the default username for
53 | # self.make_user()
54 | self.assertEqual(
55 | self.view.get_success_url(),
56 | '/users/testuser/'
57 | )
58 |
59 | def test_get_object(self):
60 | # Expect: self.user, as that is the request's user object
61 | self.assertEqual(
62 | self.view.get_object(),
63 | self.user
64 | )
65 |
--------------------------------------------------------------------------------
/config/settings/test.py:
--------------------------------------------------------------------------------
1 | """
2 | Test settings for todobackend project.
3 |
4 | - Used to run tests fast on the continuous integration server and locally
5 | """
6 |
7 | from .base import * # noqa
8 |
9 |
10 | # DEBUG
11 | # ------------------------------------------------------------------------------
12 | # Turn debug off so tests run faster
13 | DEBUG = False
14 | TEMPLATES[0]['OPTIONS']['debug'] = False
15 |
16 | # SECRET CONFIGURATION
17 | # ------------------------------------------------------------------------------
18 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
19 | # Note: This key only used for development and testing.
20 | SECRET_KEY = env('DJANGO_SECRET_KEY', default='QxdrHeJaQ0xReDgpqjrCZoRPDPZQQKV8LPs15DGRaraeF8WgX5')
21 |
22 | # Mail settings
23 | # ------------------------------------------------------------------------------
24 | EMAIL_HOST = 'localhost'
25 | EMAIL_PORT = 1025
26 |
27 | # In-memory email backend stores messages in django.core.mail.outbox
28 | # for unit testing purposes
29 | EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'
30 |
31 | # CACHING
32 | # ------------------------------------------------------------------------------
33 | # Speed advantages of in-memory caching without having to run Memcached
34 | CACHES = {
35 | 'default': {
36 | 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
37 | 'LOCATION': ''
38 | }
39 | }
40 |
41 | # TESTING
42 | # ------------------------------------------------------------------------------
43 | TEST_RUNNER = 'django.test.runner.DiscoverRunner'
44 |
45 |
46 | # PASSWORD HASHING
47 | # ------------------------------------------------------------------------------
48 | # Use fast password hasher so tests run faster
49 | PASSWORD_HASHERS = [
50 | 'django.contrib.auth.hashers.MD5PasswordHasher',
51 | ]
52 |
53 | # TEMPLATE LOADERS
54 | # ------------------------------------------------------------------------------
55 | # Keep templates in memory so tests run faster
56 | TEMPLATES[0]['OPTIONS']['loaders'] = [
57 | ['django.template.loaders.cached.Loader', [
58 | 'django.template.loaders.filesystem.Loader',
59 | 'django.template.loaders.app_directories.Loader',
60 | ], ],
61 | ]
62 |
--------------------------------------------------------------------------------
/config/settings/local.py:
--------------------------------------------------------------------------------
1 | """
2 | Local settings for todobackend project.
3 |
4 | - Run in Debug mode
5 |
6 | - Use console backend for emails
7 |
8 | - Add Django Debug Toolbar
9 | - Add django-extensions as app
10 | """
11 |
12 | from .base import * # noqa
13 |
14 | # DEBUG
15 | # ------------------------------------------------------------------------------
16 | DEBUG = env.bool('DJANGO_DEBUG', default=True)
17 | TEMPLATES[0]['OPTIONS']['debug'] = DEBUG
18 |
19 | # SECRET CONFIGURATION
20 | # ------------------------------------------------------------------------------
21 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
22 | # Note: This key only used for development and testing.
23 | SECRET_KEY = env('DJANGO_SECRET_KEY', default='SfXZw00S9vroAnsh9FnVcneRvACcLo4TLeld2eGWOezWvGH3GZ')
24 |
25 | # Mail settings
26 | # ------------------------------------------------------------------------------
27 |
28 | EMAIL_PORT = 1025
29 |
30 | EMAIL_HOST = 'localhost'
31 | EMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND',
32 | default='django.core.mail.backends.console.EmailBackend')
33 |
34 |
35 | # CACHING
36 | # ------------------------------------------------------------------------------
37 | CACHES = {
38 | 'default': {
39 | 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
40 | 'LOCATION': ''
41 | }
42 | }
43 |
44 | # django-debug-toolbar
45 | # ------------------------------------------------------------------------------
46 | MIDDLEWARE += ['debug_toolbar.middleware.DebugToolbarMiddleware', ]
47 | INSTALLED_APPS += ['debug_toolbar', ]
48 |
49 | INTERNAL_IPS = ['127.0.0.1', '10.0.2.2', ]
50 |
51 | DEBUG_TOOLBAR_CONFIG = {
52 | 'DISABLE_PANELS': [
53 | 'debug_toolbar.panels.redirects.RedirectsPanel',
54 | ],
55 | 'SHOW_TEMPLATE_CONTEXT': True,
56 | }
57 |
58 | # django-extensions
59 | # ------------------------------------------------------------------------------
60 | INSTALLED_APPS += ['django_extensions', ]
61 |
62 | # TESTING
63 | # ------------------------------------------------------------------------------
64 | TEST_RUNNER = 'django.test.runner.DiscoverRunner'
65 |
66 | # Your local stuff: Below this line define 3rd party library settings
67 | # ------------------------------------------------------------------------------
68 |
--------------------------------------------------------------------------------
/docs/pycharm/configuration.rst:
--------------------------------------------------------------------------------
1 | Docker Remote Debugging
2 | =======================
3 |
4 | To connect to python remote interpreter inside docker, you have to make sure first, that Pycharm is aware of your docker.
5 |
6 | Go to *Settings > Build, Execution, Deployment > Docker*. If you are on linux, you can use docker directly using its socket `unix:///var/run/docker.sock`, if you are on Windows or Mac, make sure that you have docker-machine installed, then you can simply *Import credentials from Docker Machine*.
7 |
8 | .. image:: images/1.png
9 |
10 | Configure Remote Python Interpreter
11 | -----------------------------------
12 |
13 | This repository comes with already prepared "Run/Debug Configurations" for docker.
14 |
15 | .. image:: images/2.png
16 |
17 | But as you can see, at the beggining there is something wrong with them. They have red X on django icon, and they cannot be used, without configuring remote python interpteter. To do that, you have to go to *Settings > Build, Execution, Deployment* first.
18 |
19 |
20 | Next, you have to add new remote python interpreter, based on already tested deployment settings. Go to *Settings > Project > Project Interpreter*. Click on the cog icon, and click *Add Remote*.
21 |
22 | .. image:: images/3.png
23 |
24 | Switch to *Docker Compose* and select `local.yml` file from directory of your project, next set *Service name* to `django`
25 |
26 | .. image:: images/4.png
27 |
28 | Having that, click *OK*. Close *Settings* panel, and wait few seconds...
29 |
30 | .. image:: images/7.png
31 |
32 | After few seconds, all *Run/Debug Configurations* should be ready to use.
33 |
34 | .. image:: images/8.png
35 |
36 | **Things you can do with provided configuration**:
37 |
38 | * run and debug python code
39 | .. image:: images/f1.png
40 | * run and debug tests
41 | .. image:: images/f2.png
42 | .. image:: images/f3.png
43 | * run and debug migrations or different django management commands
44 | .. image:: images/f4.png
45 | * and many others..
46 |
47 | Known issues
48 | ------------
49 |
50 | * Pycharm hangs on "Connecting to Debugger"
51 |
52 | .. image:: images/issue1.png
53 |
54 | This might be fault of your firewall. Take a look on this ticket - https://youtrack.jetbrains.com/issue/PY-18913
55 |
56 | * Modified files in `.idea` directory
57 |
58 | Most of the files from `.idea/` were added to `.gitignore` with a few exceptions, which were made, to provide "ready to go" configuration. After adding remote interpreter some of these files are altered by PyCharm:
59 |
60 | .. image:: images/issue2.png
61 |
62 | In theory you can remove them from repository, but then, other people will lose a ability to initialize a project from provided configurations as you did. To get rid of this annoying state, you can run command::
63 |
64 | $ git update-index --assume-unchanged todobackend.iml
65 |
--------------------------------------------------------------------------------
/utility/install_os_dependencies.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | WORK_DIR="$(dirname "$0")"
4 | DISTRO_NAME=$(lsb_release -sc)
5 | OS_REQUIREMENTS_FILENAME="requirements-$DISTRO_NAME.apt"
6 |
7 | cd $WORK_DIR
8 |
9 | # Check if a requirements file exist for the current distribution.
10 | if [ ! -r "$OS_REQUIREMENTS_FILENAME" ]; then
11 | cat <<-EOF >&2
12 | There is no requirements file for your distribution.
13 | You can see one of the files listed below to help search the equivalent package in your system:
14 | $(find ./ -name "requirements-*.apt" -printf " - %f\n")
15 | EOF
16 | exit 1;
17 | fi
18 |
19 | # Handle call with wrong command
20 | function wrong_command()
21 | {
22 | echo "${0##*/} - unknown command: '${1}'" >&2
23 | usage_message
24 | }
25 |
26 | # Print help / script usage
27 | function usage_message()
28 | {
29 | cat <<-EOF
30 | Usage: $WORK_DIR/${0##*/}
31 | Available commands are:
32 | list Print a list of all packages defined on ${OS_REQUIREMENTS_FILENAME} file
33 | help Print this help
34 |
35 | Commands that require superuser permission:
36 | install Install packages defined on ${OS_REQUIREMENTS_FILENAME} file. Note: This
37 | does not upgrade the packages already installed for new versions, even if
38 | new version is available in the repository.
39 | upgrade Same that install, but upgrade the already installed packages, if new
40 | version is available.
41 | EOF
42 | }
43 |
44 | # Read the requirements.apt file, and remove comments and blank lines
45 | function list_packages(){
46 | grep -v "#" "${OS_REQUIREMENTS_FILENAME}" | grep -v "^$";
47 | }
48 |
49 | function install_packages()
50 | {
51 | list_packages | xargs apt-get --no-upgrade install -y;
52 | }
53 |
54 | function upgrade_packages()
55 | {
56 | list_packages | xargs apt-get install -y;
57 | }
58 |
59 | function install_or_upgrade()
60 | {
61 | P=${1}
62 | PARAN=${P:-"install"}
63 |
64 | if [[ $EUID -ne 0 ]]; then
65 | cat <<-EOF >&2
66 | You must run this script with root privilege
67 | Please do:
68 | sudo $WORK_DIR/${0##*/} $PARAN
69 | EOF
70 | exit 1
71 | else
72 |
73 | apt-get update
74 |
75 | # Install the basic compilation dependencies and other required libraries of this project
76 | if [ "$PARAN" == "install" ]; then
77 | install_packages;
78 | else
79 | upgrade_packages;
80 | fi
81 |
82 | # cleaning downloaded packages from apt-get cache
83 | apt-get clean
84 |
85 | exit 0
86 | fi
87 | }
88 |
89 | # Handle command argument
90 | case "$1" in
91 | install) install_or_upgrade;;
92 | upgrade) install_or_upgrade "upgrade";;
93 | list) list_packages;;
94 | help|"") usage_message;;
95 | *) wrong_command "$1";;
96 | esac
97 |
--------------------------------------------------------------------------------
/todobackend/templates/account/email.html:
--------------------------------------------------------------------------------
1 |
2 | {% extends "account/base.html" %}
3 |
4 | {% load i18n %}
5 | {% load crispy_forms_tags %}
6 |
7 | {% block head_title %}{% trans "Account" %}{% endblock %}
8 |
9 | {% block inner %}
10 | {% trans "E-mail Addresses" %}
11 |
12 | {% if user.emailaddress_set.all %}
13 | {% trans 'The following e-mail addresses are associated with your account:' %}
14 |
15 |
44 |
45 | {% else %}
46 | {% trans 'Warning:'%} {% trans "You currently do not have any e-mail address set up. You should really add an e-mail address so you can receive notifications, reset your password, etc." %}
47 |
48 | {% endif %}
49 |
50 |
51 | {% trans "Add E-mail Address" %}
52 |
53 |
58 |
59 | {% endblock %}
60 |
61 |
62 | {% block javascript %}
63 | {{ block.super }}
64 |
79 | {% endblock %}
80 |
81 |
--------------------------------------------------------------------------------
/todobackend/users/migrations/0001_initial.py:
--------------------------------------------------------------------------------
1 | import django.contrib.auth.models
2 | import django.contrib.auth.validators
3 | from django.db import migrations, models
4 | import django.utils.timezone
5 |
6 |
7 | class Migration(migrations.Migration):
8 |
9 | initial = True
10 |
11 | dependencies = [
12 | ('auth', '0008_alter_user_username_max_length'),
13 | ]
14 |
15 | operations = [
16 | migrations.CreateModel(
17 | name='User',
18 | fields=[
19 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
20 | ('password', models.CharField(max_length=128, verbose_name='password')),
21 | ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
22 | ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
23 | ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
24 | ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')),
25 | ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
26 | ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
27 | ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
28 | ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
29 | ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
30 | ('name', models.CharField(blank=True, max_length=255, verbose_name='Name of User')),
31 | ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
32 | ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
33 | ],
34 | options={
35 | 'verbose_name_plural': 'users',
36 | 'verbose_name': 'user',
37 | 'abstract': False,
38 | },
39 | managers=[
40 | ('objects', django.contrib.auth.models.UserManager()),
41 | ],
42 | ),
43 | ]
44 |
--------------------------------------------------------------------------------
/todobackend/static_src/js/todo/todo.js:
--------------------------------------------------------------------------------
1 | import Vue from 'vue';
2 | import VueResource from 'vue-resource';
3 | import Vuex from 'vuex';
4 |
5 | Vue.use(VueResource);
6 | Vue.use(Vuex);
7 |
8 | // CSRF TOKEN
9 | var csrf_token = document.querySelector('input[name="csrfmiddlewaretoken"]').value;
10 | Vue.http.headers.common['X-CSRFToken'] = csrf_token;
11 |
12 | const store = new Vuex.Store({
13 | state: {
14 | title: 'ToDo Items',
15 | items: [],
16 | },
17 | mutations: {
18 | set_data(state, items) {
19 | state.items = items
20 | },
21 | },
22 | actions: {
23 | load_data(context) {
24 | Vue.http.get('/api/todos/', {responseType: 'json'}).then(resp => {
25 | context.commit('set_data', resp.body)
26 | });
27 | },
28 | add_todo(context, todo) {
29 | Vue.http.post('/api/todos/', {description: todo.description}).then(response => {
30 | context.dispatch('load_data')
31 | });
32 | },
33 | update_todo(context, todo) {
34 | Vue.http.patch('/api/todos/'+todo.uuid+'/', {completed_at: todo.completed_at}).then(response => {
35 | context.dispatch('load_data')
36 | });
37 | },
38 | delete_todo(context, uuid){
39 | Vue.http.delete('/api/todos/'+uuid+'/').then(response => {
40 | context.dispatch('load_data')
41 | });
42 | }
43 | }
44 | })
45 |
46 | Vue.component('todo_item_component', {
47 | template: `
48 |
49 |
50 |
{{ item.description }}
51 |
52 |
53 | `,
54 | props: ['item'],
55 | methods: {
56 | complete_todo() {
57 | var completed_at = new Date().toISOString();
58 | if (this.item.completed_at){
59 | completed_at = null;
60 | }
61 | store.dispatch('update_todo', {uuid: this.item.uuid, completed_at: completed_at});
62 | },
63 | delete_todo() {
64 | store.dispatch('delete_todo', this.item.uuid);
65 | }
66 | }
67 | });
68 |
69 |
70 | var todo_app = new Vue({
71 | el: "#todo-app",
72 | delimiters: ['${', '}'],
73 | store,
74 | mounted() {
75 | store.dispatch('load_data')
76 | },
77 | computed: Vuex.mapState({
78 | title: state => state.title,
79 | items: state => state.items
80 | }),
81 | methods: {
82 | create() {
83 | var description = this.$refs.new_text.value;
84 | if (!description) {
85 | alert('Please enter description');
86 | return;
87 | }
88 | store.dispatch('add_todo', {'description': description})
89 | this.$refs.new_text.value = '';
90 | }
91 | }
92 | });
93 |
--------------------------------------------------------------------------------
/todobackend/templates/base.html:
--------------------------------------------------------------------------------
1 | {% load static i18n %}
2 |
3 |
4 |
5 |
6 | {% block title %}todobackend{% endblock title %}
7 |
8 |
9 |
10 |
11 |
16 |
17 |
18 |
19 |
22 |
23 | {% block css %}
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 | {% endblock %}
37 |
38 |
39 |
40 |
41 |
42 |
44 |
45 |
46 |
47 |
48 |
49 |
50 | todobackend
51 |
52 |
53 |
54 | {% comment %}
55 |
56 | Home (current)
57 |
58 |
59 | About
60 |
61 | {% if request.user.is_authenticated %}
62 |
63 | {# URL provided by django-allauth/account/urls.py #}
64 | {% trans "My Profile" %}
65 |
66 |
67 | {# URL provided by django-allauth/account/urls.py #}
68 | {% trans "Sign Out" %}
69 |
70 | {% else %}
71 |
72 | {# URL provided by django-allauth/account/urls.py #}
73 | {% trans "Sign Up" %}
74 |
75 |
76 | {# URL provided by django-allauth/account/urls.py #}
77 | {% trans "Sign In" %}
78 |
79 | {% endif %}
80 | {% endcomment %}
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 | {% if messages %}
90 | {% for message in messages %}
91 |
{{ message }}
92 | {% endfor %}
93 | {% endif %}
94 |
95 | {% block content %}
96 |
Use this document as a way to quick start any new project.
97 | {% endblock content %}
98 |
99 |
100 |
101 | {% block modal %}{% endblock modal %}
102 |
103 |
105 |
106 | {% block javascript %}
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 | {% endblock javascript %}
120 |
121 |
122 |
123 |
--------------------------------------------------------------------------------
/docs/make.bat:
--------------------------------------------------------------------------------
1 | @ECHO OFF
2 |
3 | REM Command file for Sphinx documentation
4 |
5 | if "%SPHINXBUILD%" == "" (
6 | set SPHINXBUILD=sphinx-build
7 | )
8 | set BUILDDIR=_build
9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
10 | set I18NSPHINXOPTS=%SPHINXOPTS% .
11 | if NOT "%PAPER%" == "" (
12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
14 | )
15 |
16 | if "%1" == "" goto help
17 |
18 | if "%1" == "help" (
19 | :help
20 | echo.Please use `make ^` where ^ is one of
21 | echo. html to make standalone HTML files
22 | echo. dirhtml to make HTML files named index.html in directories
23 | echo. singlehtml to make a single large HTML file
24 | echo. pickle to make pickle files
25 | echo. json to make JSON files
26 | echo. htmlhelp to make HTML files and a HTML help project
27 | echo. qthelp to make HTML files and a qthelp project
28 | echo. devhelp to make HTML files and a Devhelp project
29 | echo. epub to make an epub
30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
31 | echo. text to make text files
32 | echo. man to make manual pages
33 | echo. texinfo to make Texinfo files
34 | echo. gettext to make PO message catalogs
35 | echo. changes to make an overview over all changed/added/deprecated items
36 | echo. linkcheck to check all external links for integrity
37 | echo. doctest to run all doctests embedded in the documentation if enabled
38 | goto end
39 | )
40 |
41 | if "%1" == "clean" (
42 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
43 | del /q /s %BUILDDIR%\*
44 | goto end
45 | )
46 |
47 | if "%1" == "html" (
48 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
49 | if errorlevel 1 exit /b 1
50 | echo.
51 | echo.Build finished. The HTML pages are in %BUILDDIR%/html.
52 | goto end
53 | )
54 |
55 | if "%1" == "dirhtml" (
56 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
57 | if errorlevel 1 exit /b 1
58 | echo.
59 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
60 | goto end
61 | )
62 |
63 | if "%1" == "singlehtml" (
64 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
65 | if errorlevel 1 exit /b 1
66 | echo.
67 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
68 | goto end
69 | )
70 |
71 | if "%1" == "pickle" (
72 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
73 | if errorlevel 1 exit /b 1
74 | echo.
75 | echo.Build finished; now you can process the pickle files.
76 | goto end
77 | )
78 |
79 | if "%1" == "json" (
80 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
81 | if errorlevel 1 exit /b 1
82 | echo.
83 | echo.Build finished; now you can process the JSON files.
84 | goto end
85 | )
86 |
87 | if "%1" == "htmlhelp" (
88 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
89 | if errorlevel 1 exit /b 1
90 | echo.
91 | echo.Build finished; now you can run HTML Help Workshop with the ^
92 | .hhp project file in %BUILDDIR%/htmlhelp.
93 | goto end
94 | )
95 |
96 | if "%1" == "qthelp" (
97 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
98 | if errorlevel 1 exit /b 1
99 | echo.
100 | echo.Build finished; now you can run "qcollectiongenerator" with the ^
101 | .qhcp project file in %BUILDDIR%/qthelp, like this:
102 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\todobackend.qhcp
103 | echo.To view the help file:
104 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\todobackend.ghc
105 | goto end
106 | )
107 |
108 | if "%1" == "devhelp" (
109 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
110 | if errorlevel 1 exit /b 1
111 | echo.
112 | echo.Build finished.
113 | goto end
114 | )
115 |
116 | if "%1" == "epub" (
117 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
118 | if errorlevel 1 exit /b 1
119 | echo.
120 | echo.Build finished. The epub file is in %BUILDDIR%/epub.
121 | goto end
122 | )
123 |
124 | if "%1" == "latex" (
125 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
126 | if errorlevel 1 exit /b 1
127 | echo.
128 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
129 | goto end
130 | )
131 |
132 | if "%1" == "text" (
133 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
134 | if errorlevel 1 exit /b 1
135 | echo.
136 | echo.Build finished. The text files are in %BUILDDIR%/text.
137 | goto end
138 | )
139 |
140 | if "%1" == "man" (
141 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
142 | if errorlevel 1 exit /b 1
143 | echo.
144 | echo.Build finished. The manual pages are in %BUILDDIR%/man.
145 | goto end
146 | )
147 |
148 | if "%1" == "texinfo" (
149 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
150 | if errorlevel 1 exit /b 1
151 | echo.
152 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
153 | goto end
154 | )
155 |
156 | if "%1" == "gettext" (
157 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
158 | if errorlevel 1 exit /b 1
159 | echo.
160 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
161 | goto end
162 | )
163 |
164 | if "%1" == "changes" (
165 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
166 | if errorlevel 1 exit /b 1
167 | echo.
168 | echo.The overview file is in %BUILDDIR%/changes.
169 | goto end
170 | )
171 |
172 | if "%1" == "linkcheck" (
173 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
174 | if errorlevel 1 exit /b 1
175 | echo.
176 | echo.Link check complete; look for any errors in the above output ^
177 | or in %BUILDDIR%/linkcheck/output.txt.
178 | goto end
179 | )
180 |
181 | if "%1" == "doctest" (
182 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
183 | if errorlevel 1 exit /b 1
184 | echo.
185 | echo.Testing of doctests in the sources finished, look at the ^
186 | results in %BUILDDIR%/doctest/output.txt.
187 | goto end
188 | )
189 |
190 | :end
191 |
--------------------------------------------------------------------------------
/docs/Makefile:
--------------------------------------------------------------------------------
1 | # Makefile for Sphinx documentation
2 | #
3 |
4 | # You can set these variables from the command line.
5 | SPHINXOPTS =
6 | SPHINXBUILD = sphinx-build
7 | PAPER =
8 | BUILDDIR = _build
9 |
10 | # Internal variables.
11 | PAPEROPT_a4 = -D latex_paper_size=a4
12 | PAPEROPT_letter = -D latex_paper_size=letter
13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
14 | # the i18n builder cannot share the environment and doctrees with the others
15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
16 |
17 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
18 |
19 | help:
20 | @echo "Please use \`make ' where is one of"
21 | @echo " html to make standalone HTML files"
22 | @echo " dirhtml to make HTML files named index.html in directories"
23 | @echo " singlehtml to make a single large HTML file"
24 | @echo " pickle to make pickle files"
25 | @echo " json to make JSON files"
26 | @echo " htmlhelp to make HTML files and a HTML help project"
27 | @echo " qthelp to make HTML files and a qthelp project"
28 | @echo " devhelp to make HTML files and a Devhelp project"
29 | @echo " epub to make an epub"
30 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
31 | @echo " latexpdf to make LaTeX files and run them through pdflatex"
32 | @echo " text to make text files"
33 | @echo " man to make manual pages"
34 | @echo " texinfo to make Texinfo files"
35 | @echo " info to make Texinfo files and run them through makeinfo"
36 | @echo " gettext to make PO message catalogs"
37 | @echo " changes to make an overview of all changed/added/deprecated items"
38 | @echo " linkcheck to check all external links for integrity"
39 | @echo " doctest to run all doctests embedded in the documentation (if enabled)"
40 |
41 | clean:
42 | -rm -rf $(BUILDDIR)/*
43 |
44 | html:
45 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
46 | @echo
47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
48 |
49 | dirhtml:
50 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
51 | @echo
52 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
53 |
54 | singlehtml:
55 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
56 | @echo
57 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
58 |
59 | pickle:
60 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
61 | @echo
62 | @echo "Build finished; now you can process the pickle files."
63 |
64 | json:
65 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
66 | @echo
67 | @echo "Build finished; now you can process the JSON files."
68 |
69 | htmlhelp:
70 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
71 | @echo
72 | @echo "Build finished; now you can run HTML Help Workshop with the" \
73 | ".hhp project file in $(BUILDDIR)/htmlhelp."
74 |
75 | qthelp:
76 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
77 | @echo
78 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \
79 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
80 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/todobackend.qhcp"
81 | @echo "To view the help file:"
82 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/todobackend.qhc"
83 |
84 | devhelp:
85 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
86 | @echo
87 | @echo "Build finished."
88 | @echo "To view the help file:"
89 | @echo "# mkdir -p $$HOME/.local/share/devhelp/todobackend"
90 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/todobackend"
91 | @echo "# devhelp"
92 |
93 | epub:
94 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
95 | @echo
96 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
97 |
98 | latex:
99 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
100 | @echo
101 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
102 | @echo "Run \`make' in that directory to run these through (pdf)latex" \
103 | "(use \`make latexpdf' here to do that automatically)."
104 |
105 | latexpdf:
106 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
107 | @echo "Running LaTeX files through pdflatex..."
108 | $(MAKE) -C $(BUILDDIR)/latex all-pdf
109 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
110 |
111 | text:
112 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
113 | @echo
114 | @echo "Build finished. The text files are in $(BUILDDIR)/text."
115 |
116 | man:
117 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
118 | @echo
119 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
120 |
121 | texinfo:
122 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
123 | @echo
124 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
125 | @echo "Run \`make' in that directory to run these through makeinfo" \
126 | "(use \`make info' here to do that automatically)."
127 |
128 | info:
129 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
130 | @echo "Running Texinfo files through makeinfo..."
131 | make -C $(BUILDDIR)/texinfo info
132 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
133 |
134 | gettext:
135 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
136 | @echo
137 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
138 |
139 | changes:
140 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
141 | @echo
142 | @echo "The overview file is in $(BUILDDIR)/changes."
143 |
144 | linkcheck:
145 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
146 | @echo
147 | @echo "Link check complete; look for any errors in the above output " \
148 | "or in $(BUILDDIR)/linkcheck/output.txt."
149 |
150 | doctest:
151 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
152 | @echo "Testing of doctests in the sources finished, look at the " \
153 | "results in $(BUILDDIR)/doctest/output.txt."
154 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ### Python template
2 | # Byte-compiled / optimized / DLL files
3 | __pycache__/
4 | *.py[cod]
5 | *$py.class
6 |
7 | # C extensions
8 | *.so
9 |
10 | # Distribution / packaging
11 | .Python
12 | build/
13 | develop-eggs/
14 | dist/
15 | downloads/
16 | eggs/
17 | .eggs/
18 | lib/
19 | lib64/
20 | parts/
21 | sdist/
22 | var/
23 | wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 |
28 | # PyInstaller
29 | # Usually these files are written by a python script from a template
30 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
31 | *.manifest
32 | *.spec
33 |
34 | # Installer logs
35 | pip-log.txt
36 | pip-delete-this-directory.txt
37 |
38 | # Unit test / coverage reports
39 | htmlcov/
40 | .tox/
41 | .coverage
42 | .coverage.*
43 | .cache
44 | nosetests.xml
45 | coverage.xml
46 | *.cover
47 | .hypothesis/
48 |
49 | # Translations
50 | *.mo
51 | *.pot
52 |
53 | # Django stuff:
54 | staticfiles/
55 |
56 | # Flask stuff:
57 | instance/
58 | .webassets-cache
59 |
60 | # Scrapy stuff:
61 | .scrapy
62 |
63 | # Sphinx documentation
64 | docs/_build/
65 |
66 | # PyBuilder
67 | target/
68 |
69 | # Jupyter Notebook
70 | .ipynb_checkpoints
71 |
72 | # pyenv
73 | .python-version
74 |
75 | # celery beat schedule file
76 | celerybeat-schedule
77 |
78 | # SageMath parsed files
79 | *.sage.py
80 |
81 | # Environments
82 | .env
83 | .venv
84 | env/
85 | venv/
86 | ENV/
87 |
88 | # Spyder project settings
89 | .spyderproject
90 | .spyproject
91 |
92 | # Rope project settings
93 | .ropeproject
94 |
95 | # mkdocs documentation
96 | /site
97 |
98 | # mypy
99 | .mypy_cache/
100 |
101 |
102 | ### Node template
103 | # Logs
104 | logs
105 | *.log
106 | npm-debug.log*
107 | yarn-debug.log*
108 | yarn-error.log*
109 |
110 | # Runtime data
111 | pids
112 | *.pid
113 | *.seed
114 | *.pid.lock
115 |
116 | # Directory for instrumented libs generated by jscoverage/JSCover
117 | lib-cov
118 |
119 | # Coverage directory used by tools like istanbul
120 | coverage
121 |
122 | # nyc test coverage
123 | .nyc_output
124 |
125 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
126 | .grunt
127 |
128 | # Bower dependency directory (https://bower.io/)
129 | bower_components
130 |
131 | # node-waf configuration
132 | .lock-wscript
133 |
134 | # Compiled binary addons (http://nodejs.org/api/addons.html)
135 | build/Release
136 |
137 | # Dependency directories
138 | node_modules/
139 | jspm_packages/
140 |
141 | # Typescript v1 declaration files
142 | typings/
143 |
144 | # Optional npm cache directory
145 | .npm
146 |
147 | # Optional eslint cache
148 | .eslintcache
149 |
150 | # Optional REPL history
151 | .node_repl_history
152 |
153 | # Output of 'npm pack'
154 | *.tgz
155 |
156 | # Yarn Integrity file
157 | .yarn-integrity
158 |
159 |
160 | ### Linux template
161 | *~
162 |
163 | # temporary files which can be created if a process still has a handle open of a deleted file
164 | .fuse_hidden*
165 |
166 | # KDE directory preferences
167 | .directory
168 |
169 | # Linux trash folder which might appear on any partition or disk
170 | .Trash-*
171 |
172 | # .nfs files are created when an open file is removed but is still being accessed
173 | .nfs*
174 |
175 |
176 | ### VisualStudioCode template
177 | .vscode/*
178 | !.vscode/settings.json
179 | !.vscode/tasks.json
180 | !.vscode/launch.json
181 | !.vscode/extensions.json
182 |
183 |
184 | # Provided default Pycharm Run/Debug Configurations should be tracked by git
185 | # In case of local modifications made by Pycharm, use update-index command
186 | # for each changed file, like this:
187 | # git update-index --assume-unchanged .idea/todobackend.iml
188 | ### JetBrains template
189 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
190 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
191 |
192 | # User-specific stuff:
193 | .idea/**/workspace.xml
194 | .idea/**/tasks.xml
195 | .idea/dictionaries
196 |
197 | # Sensitive or high-churn files:
198 | .idea/**/dataSources/
199 | .idea/**/dataSources.ids
200 | .idea/**/dataSources.xml
201 | .idea/**/dataSources.local.xml
202 | .idea/**/sqlDataSources.xml
203 | .idea/**/dynamic.xml
204 | .idea/**/uiDesigner.xml
205 |
206 | # Gradle:
207 | .idea/**/gradle.xml
208 | .idea/**/libraries
209 |
210 | # CMake
211 | cmake-build-debug/
212 |
213 | # Mongo Explorer plugin:
214 | .idea/**/mongoSettings.xml
215 |
216 | ## File-based project format:
217 | *.iws
218 |
219 | ## Plugin-specific files:
220 |
221 | # IntelliJ
222 | out/
223 |
224 | # mpeltonen/sbt-idea plugin
225 | .idea_modules/
226 |
227 | # JIRA plugin
228 | atlassian-ide-plugin.xml
229 |
230 | # Cursive Clojure plugin
231 | .idea/replstate.xml
232 |
233 | # Crashlytics plugin (for Android Studio and IntelliJ)
234 | com_crashlytics_export_strings.xml
235 | crashlytics.properties
236 | crashlytics-build.properties
237 | fabric.properties
238 |
239 |
240 |
241 | ### Windows template
242 | # Windows thumbnail cache files
243 | Thumbs.db
244 | ehthumbs.db
245 | ehthumbs_vista.db
246 |
247 | # Dump file
248 | *.stackdump
249 |
250 | # Folder config file
251 | Desktop.ini
252 |
253 | # Recycle Bin used on file shares
254 | $RECYCLE.BIN/
255 |
256 | # Windows Installer files
257 | *.cab
258 | *.msi
259 | *.msm
260 | *.msp
261 |
262 | # Windows shortcuts
263 | *.lnk
264 |
265 |
266 | ### macOS template
267 | # General
268 | *.DS_Store
269 | .AppleDouble
270 | .LSOverride
271 |
272 | # Icon must end with two \r
273 | Icon
274 |
275 | # Thumbnails
276 | ._*
277 |
278 | # Files that might appear in the root of a volume
279 | .DocumentRevisions-V100
280 | .fseventsd
281 | .Spotlight-V100
282 | .TemporaryItems
283 | .Trashes
284 | .VolumeIcon.icns
285 | .com.apple.timemachine.donotpresent
286 |
287 | # Directories potentially created on remote AFP share
288 | .AppleDB
289 | .AppleDesktop
290 | Network Trash Folder
291 | Temporary Items
292 | .apdisk
293 |
294 |
295 | ### SublimeText template
296 | # Cache files for Sublime Text
297 | *.tmlanguage.cache
298 | *.tmPreferences.cache
299 | *.stTheme.cache
300 |
301 | # Workspace files are user-specific
302 | *.sublime-workspace
303 |
304 | # Project files should be checked into the repository, unless a significant
305 | # proportion of contributors will probably not be using Sublime Text
306 | # *.sublime-project
307 |
308 | # SFTP configuration file
309 | sftp-config.json
310 |
311 | # Package control specific files
312 | Package Control.last-run
313 | Package Control.ca-list
314 | Package Control.ca-bundle
315 | Package Control.system-ca-bundle
316 | Package Control.cache/
317 | Package Control.ca-certs/
318 | Package Control.merged-ca-bundle
319 | Package Control.user-ca-bundle
320 | oscrypto-ca-bundle.crt
321 | bh_unicode_properties.cache
322 |
323 | # Sublime-github package stores a github token in this file
324 | # https://packagecontrol.io/packages/sublime-github
325 | GitHub.sublime-settings
326 |
327 |
328 | ### Vim template
329 | # Swap
330 | [._]*.s[a-v][a-z]
331 | [._]*.sw[a-p]
332 | [._]s[a-v][a-z]
333 | [._]sw[a-p]
334 |
335 | # Session
336 | Session.vim
337 |
338 | # Temporary
339 | .netrwhist
340 |
341 | # Auto-generated tag files
342 | tags
343 |
344 |
345 | ### VirtualEnv template
346 | # Virtualenv
347 | # http://iamzed.com/2009/05/07/a-primer-on-virtualenv/
348 | [Bb]in
349 | [Ii]nclude
350 | [Ll]ib
351 | [Ll]ib64
352 | [Ll]ocal
353 | [Ss]cripts
354 | pyvenv.cfg
355 | pip-selfcheck.json
356 |
357 |
358 |
359 |
360 | todobackend/media/
361 |
362 |
363 |
--------------------------------------------------------------------------------
/config/settings/production.py:
--------------------------------------------------------------------------------
1 | """
2 | Production settings for todobackend project.
3 |
4 | - Use WhiteNoise for serving static files
5 | - Use Amazon's S3 for storing uploaded media
6 | - Use mailgun to send emails
7 | - Use Redis for cache
8 |
9 | - Use sentry for error logging
10 |
11 |
12 | """
13 |
14 |
15 | import logging
16 |
17 |
18 | from .base import * # noqa
19 |
20 | # SECRET CONFIGURATION
21 | # ------------------------------------------------------------------------------
22 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
23 | # Raises ImproperlyConfigured exception if DJANGO_SECRET_KEY not in os.environ
24 | SECRET_KEY = env('DJANGO_SECRET_KEY')
25 |
26 |
27 | # This ensures that Django will be able to detect a secure connection
28 | # properly on Heroku.
29 | SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
30 | # raven sentry client
31 | # See https://docs.sentry.io/clients/python/integrations/django/
32 | INSTALLED_APPS += ['raven.contrib.django.raven_compat', ]
33 |
34 | # Use Whitenoise to serve static files
35 | # See: https://whitenoise.readthedocs.io/
36 | WHITENOISE_MIDDLEWARE = ['whitenoise.middleware.WhiteNoiseMiddleware', ]
37 | MIDDLEWARE = WHITENOISE_MIDDLEWARE + MIDDLEWARE
38 | RAVEN_MIDDLEWARE = ['raven.contrib.django.raven_compat.middleware.SentryResponseErrorIdMiddleware']
39 | MIDDLEWARE = RAVEN_MIDDLEWARE + MIDDLEWARE
40 |
41 |
42 | # SECURITY CONFIGURATION
43 | # ------------------------------------------------------------------------------
44 | # See https://docs.djangoproject.com/en/dev/ref/middleware/#module-django.middleware.security
45 | # and https://docs.djangoproject.com/en/dev/howto/deployment/checklist/#run-manage-py-check-deploy
46 |
47 | # set this to 60 seconds and then to 518400 when you can prove it works
48 | SECURE_HSTS_SECONDS = 60
49 | SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool(
50 | 'DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS', default=True)
51 | SECURE_CONTENT_TYPE_NOSNIFF = env.bool(
52 | 'DJANGO_SECURE_CONTENT_TYPE_NOSNIFF', default=True)
53 | SECURE_BROWSER_XSS_FILTER = True
54 | SESSION_COOKIE_SECURE = True
55 | SESSION_COOKIE_HTTPONLY = True
56 | SECURE_SSL_REDIRECT = env.bool('DJANGO_SECURE_SSL_REDIRECT', default=True)
57 | CSRF_COOKIE_SECURE = True
58 | CSRF_COOKIE_HTTPONLY = True
59 | X_FRAME_OPTIONS = 'DENY'
60 |
61 | # SITE CONFIGURATION
62 | # ------------------------------------------------------------------------------
63 | # Hosts/domain names that are valid for this site
64 | # See https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts
65 | ALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS', default=['todobackend.lin.nz', ])
66 | # END SITE CONFIGURATION
67 |
68 | INSTALLED_APPS += ['gunicorn', ]
69 |
70 |
71 | # STORAGE CONFIGURATION
72 | # ------------------------------------------------------------------------------
73 | # Uploaded Media Files
74 | # ------------------------
75 | # See: http://django-storages.readthedocs.io/en/latest/index.html
76 | INSTALLED_APPS += ['storages', ]
77 |
78 | AWS_ACCESS_KEY_ID = env('DJANGO_AWS_ACCESS_KEY_ID')
79 | AWS_SECRET_ACCESS_KEY = env('DJANGO_AWS_SECRET_ACCESS_KEY')
80 | AWS_STORAGE_BUCKET_NAME = env('DJANGO_AWS_STORAGE_BUCKET_NAME')
81 | AWS_AUTO_CREATE_BUCKET = True
82 | AWS_QUERYSTRING_AUTH = False
83 |
84 | # AWS cache settings, don't change unless you know what you're doing:
85 | AWS_EXPIRY = 60 * 60 * 24 * 7
86 |
87 | AWS_S3_OBJECT_PARAMETERS = {
88 | 'CacheControl': 'max-age=%d, s-maxage=%d, must-revalidate' % (AWS_EXPIRY, AWS_EXPIRY),
89 | }
90 |
91 | # URL that handles the media served from MEDIA_ROOT, used for managing
92 | # stored files.
93 | MEDIA_URL = 'https://s3.amazonaws.com/%s/' % AWS_STORAGE_BUCKET_NAME
94 | DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
95 |
96 |
97 | # Static Assets
98 | # ------------------------
99 | # STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
100 |
101 |
102 | # EMAIL
103 | # ------------------------------------------------------------------------------
104 | DEFAULT_FROM_EMAIL = env('DJANGO_DEFAULT_FROM_EMAIL',
105 | default='todobackend ')
106 | EMAIL_SUBJECT_PREFIX = env('DJANGO_EMAIL_SUBJECT_PREFIX', default='[todobackend]')
107 | SERVER_EMAIL = env('DJANGO_SERVER_EMAIL', default=DEFAULT_FROM_EMAIL)
108 |
109 | # Anymail with Mailgun
110 | INSTALLED_APPS += ['anymail', ]
111 | ANYMAIL = {
112 | 'MAILGUN_API_KEY': env('DJANGO_MAILGUN_API_KEY'),
113 | 'MAILGUN_SENDER_DOMAIN': env('MAILGUN_SENDER_DOMAIN')
114 | }
115 | EMAIL_BACKEND = 'anymail.backends.mailgun.EmailBackend'
116 |
117 | # TEMPLATE CONFIGURATION
118 | # ------------------------------------------------------------------------------
119 | # See:
120 | # https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.loaders.cached.Loader
121 | TEMPLATES[0]['OPTIONS']['loaders'] = [
122 | ('django.template.loaders.cached.Loader', [
123 | 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ]),
124 | ]
125 |
126 | # DATABASE CONFIGURATION
127 | # ------------------------------------------------------------------------------
128 |
129 | # Use the Heroku-style specification
130 | # Raises ImproperlyConfigured exception if DATABASE_URL not in os.environ
131 | DATABASES['default'] = env.db('DATABASE_URL')
132 | DATABASES['default']['CONN_MAX_AGE'] = env.int('CONN_MAX_AGE', default=60)
133 | DATABASES['default']['ATOMIC_REQUESTS'] = True
134 |
135 | # CACHING
136 | # ------------------------------------------------------------------------------
137 | REDIS_LOCATION = '{0}/{1}'.format(env('REDIS_URL', default='redis://127.0.0.1:6379'), 0)
138 |
139 | # Heroku URL does not pass the DB number, so we parse it in
140 | CACHES = {
141 | 'default': {
142 | 'BACKEND': 'django_redis.cache.RedisCache',
143 | 'LOCATION': REDIS_LOCATION,
144 | 'OPTIONS': {
145 | 'CLIENT_CLASS': 'django_redis.client.DefaultClient',
146 | 'IGNORE_EXCEPTIONS': True, # mimics memcache behavior.
147 | # http://niwinz.github.io/django-redis/latest/#_memcached_exceptions_behavior
148 | }
149 | }
150 | }
151 |
152 |
153 | # Sentry Configuration
154 | SENTRY_DSN = env('DJANGO_SENTRY_DSN')
155 | SENTRY_CLIENT = env('DJANGO_SENTRY_CLIENT', default='raven.contrib.django.raven_compat.DjangoClient')
156 | LOGGING = {
157 | 'version': 1,
158 | 'disable_existing_loggers': True,
159 | 'root': {
160 | 'level': 'WARNING',
161 | 'handlers': ['sentry', ],
162 | },
163 | 'formatters': {
164 | 'verbose': {
165 | 'format': '%(levelname)s %(asctime)s %(module)s '
166 | '%(process)d %(thread)d %(message)s'
167 | },
168 | },
169 | 'handlers': {
170 | 'sentry': {
171 | 'level': 'ERROR',
172 | 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler',
173 | },
174 | 'console': {
175 | 'level': 'DEBUG',
176 | 'class': 'logging.StreamHandler',
177 | 'formatter': 'verbose'
178 | }
179 | },
180 | 'loggers': {
181 | 'django.db.backends': {
182 | 'level': 'ERROR',
183 | 'handlers': ['console', ],
184 | 'propagate': False,
185 | },
186 | 'raven': {
187 | 'level': 'DEBUG',
188 | 'handlers': ['console', ],
189 | 'propagate': False,
190 | },
191 | 'sentry.errors': {
192 | 'level': 'DEBUG',
193 | 'handlers': ['console', ],
194 | 'propagate': False,
195 | },
196 | 'django.security.DisallowedHost': {
197 | 'level': 'ERROR',
198 | 'handlers': ['console', 'sentry', ],
199 | 'propagate': False,
200 | },
201 | },
202 | }
203 | SENTRY_CELERY_LOGLEVEL = env.int('DJANGO_SENTRY_LOG_LEVEL', logging.INFO)
204 | RAVEN_CONFIG = {
205 | 'CELERY_LOGLEVEL': env.int('DJANGO_SENTRY_LOG_LEVEL', logging.INFO),
206 | 'DSN': SENTRY_DSN
207 | }
208 |
209 | # Custom Admin URL, use {% url 'admin:index' %}
210 | ADMIN_URL = env('DJANGO_ADMIN_URL')
211 |
212 | # Your production stuff: Below this line define 3rd party library settings
213 | # ------------------------------------------------------------------------------
214 |
--------------------------------------------------------------------------------
/docs/docker_ec2.rst:
--------------------------------------------------------------------------------
1 | Developing with Docker
2 | ======================
3 |
4 | You can develop your application in a `Docker`_ container for simpler deployment onto bare Linux machines later. This instruction assumes an `Amazon Web Services`_ EC2 instance, but it should work on any machine with Docker > 1.3 and `Docker compose`_ installed.
5 |
6 | .. _Docker: https://www.docker.com/
7 | .. _Amazon Web Services: http://aws.amazon.com/
8 | .. _Docker compose: https://docs.docker.com/compose/
9 |
10 | Setting up
11 | ^^^^^^^^^^
12 |
13 | Docker encourages running one container for each process. This might mean one container for your web server, one for Django application and a third for your database. Once you're happy composing containers in this way you can easily add more, such as a `Redis`_ cache.
14 |
15 | .. _Redis: http://redis.io/
16 |
17 | The Docker compose tool (previously known as `fig`_) makes linking these containers easy. An example set up for your Cookiecutter Django project might look like this:
18 |
19 | .. _fig: http://www.fig.sh/
20 |
21 | ::
22 |
23 | webapp/ # Your cookiecutter project would be in here
24 | Dockerfile
25 | ...
26 | database/
27 | Dockerfile
28 | ...
29 | webserver/
30 | Dockerfile
31 | ...
32 | production.yml
33 |
34 | Each component of your application would get its own `Dockerfile`_. The rest of this example assumes you are using the `base postgres image`_ for your database. Your database settings in `config/base.py` might then look something like:
35 |
36 | .. _Dockerfile: https://docs.docker.com/reference/builder/
37 | .. _base postgres image: https://registry.hub.docker.com/_/postgres/
38 |
39 | .. code-block:: python
40 |
41 | DATABASES = {
42 | 'default': {
43 | 'ENGINE': 'django.db.backends.postgresql_psycopg2',
44 | 'NAME': 'postgres',
45 | 'USER': 'postgres',
46 | 'HOST': 'database',
47 | 'PORT': 5432,
48 | }
49 | }
50 |
51 | The `Docker compose documentation`_ explains in detail what you can accomplish in the `production.yml` file, but an example configuration might look like this:
52 |
53 | .. _Docker compose documentation: https://docs.docker.com/compose/#compose-documentation
54 |
55 | .. code-block:: yaml
56 |
57 | database:
58 | build: database
59 | webapp:
60 | build: webapp:
61 | command: /usr/bin/python3.6 manage.py runserver 0.0.0.0:8000 # dev setting
62 | # command: gunicorn -b 0.0.0.0:8000 wsgi:application # production setting
63 | volumes:
64 | - webapp/your_project_name:/path/to/container/workdir/
65 | links:
66 | - database
67 | webserver:
68 | build: webserver
69 | ports:
70 | - "80:80"
71 | - "443:443"
72 | links:
73 | - webapp
74 |
75 | We'll ignore the webserver for now (you'll want to comment that part out while we do). A working Dockerfile to run your cookiecutter application might look like this:
76 |
77 | ::
78 |
79 | FROM ubuntu:14.04
80 | ENV REFRESHED_AT 2015-01-13
81 |
82 | # update packages and prepare to build software
83 | RUN ["apt-get", "update"]
84 | RUN ["apt-get", "-y", "install", "build-essential", "vim", "git", "curl"]
85 | RUN ["locale-gen", "en_GB.UTF-8"]
86 |
87 | # install latest python
88 | RUN ["apt-get", "-y", "build-dep", "python3-dev", "python3-imaging"]
89 | RUN ["apt-get", "-y", "install", "python3-dev", "python3-imaging", "python3-pip"]
90 |
91 | # prepare postgreSQL support
92 | RUN ["apt-get", "-y", "build-dep", "python3-psycopg2"]
93 |
94 | # move into our working directory
95 | # ADD must be after chown see http://stackoverflow.com/a/26145444/1281947
96 | RUN ["groupadd", "python"]
97 | RUN ["useradd", "python", "-s", "/bin/bash", "-m", "-g", "python", "-G", "python"]
98 | ENV HOME /home/python
99 | WORKDIR /home/python
100 | RUN ["chown", "-R", "python:python", "/home/python"]
101 | ADD ./ /home/python
102 |
103 | # manage requirements
104 | ENV REQUIREMENTS_REFRESHED_AT 2015-02-25
105 | RUN ["pip3", "install", "-r", "requirements.txt"]
106 |
107 | # uncomment the line below to use container as a non-root user
108 | USER python:python
109 |
110 | Running `sudo docker-compose -f production.yml build` will follow the instructions in your `production.yml` file and build the database container, then your webapp, before mounting your cookiecutter project files as a volume in the webapp container and linking to the database. Our example yaml file runs in development mode but changing it to production mode is as simple as commenting out the line using `runserver` and uncommenting the line using `gunicorn`.
111 |
112 | Both are set to run on port `0.0.0.0:8000`, which is where the Docker daemon will discover it. You can now run `sudo docker-compose -f production.yml up` and browse to `localhost:8000` to see your application running.
113 |
114 | Deployment
115 | ^^^^^^^^^^
116 |
117 | You'll need a webserver container for deployment. An example setup for `Nginx`_ might look like this:
118 |
119 | .. _Nginx: http://wiki.nginx.org/Main
120 |
121 | ::
122 |
123 | FROM ubuntu:14.04
124 | ENV REFRESHED_AT 2015-02-11
125 |
126 | # get the nginx package and set it up
127 | RUN ["apt-get", "update"]
128 | RUN ["apt-get", "-y", "install", "nginx"]
129 |
130 | # forward request and error logs to docker log collector
131 | RUN ln -sf /dev/stdout /var/log/nginx/access.log
132 | RUN ln -sf /dev/stderr /var/log/nginx/error.log
133 | VOLUME ["/var/cache/nginx"]
134 | EXPOSE 80 443
135 |
136 | # load nginx conf
137 | ADD ./site.conf /etc/nginx/sites-available/your_cookiecutter_project
138 | RUN ["ln", "-s", "/etc/nginx/sites-available/your_cookiecutter_project", "/etc/nginx/sites-enabled/your_cookiecutter_project"]
139 | RUN ["rm", "-rf", "/etc/nginx/sites-available/default"]
140 |
141 | #start the server
142 | CMD ["nginx", "-g", "daemon off;"]
143 |
144 | That Dockerfile assumes you have an Nginx conf file named `site.conf` in the same directory as the webserver Dockerfile. A very basic example, which forwards traffic onto the development server or gunicorn for processing, would look like this:
145 |
146 | ::
147 |
148 | # see http://serverfault.com/questions/577370/how-can-i-use-environment-variables-in-nginx-conf#comment730384_577370
149 | upstream localhost {
150 | server webapp_1:8000;
151 | }
152 | server {
153 | location / {
154 | proxy_pass http://localhost;
155 | }
156 | }
157 |
158 | Running `sudo docker-compose -f production.yml build webserver` will build your server container. Running `sudo docker-compose -f production.yml up` will now expose your application directly on `localhost` (no need to specify the port number).
159 |
160 | Building and running your app on EC2
161 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
162 |
163 | All you now need to do to run your app in production is:
164 |
165 | * Create an empty EC2 Linux instance (any Linux machine should do).
166 |
167 | * Install your preferred source control solution, Docker and Docker compose on the news instance.
168 |
169 | * Pull in your code from source control. The root directory should be the one with your `production.yml` file in it.
170 |
171 | * Run `sudo docker-compose -f production.yml build` and `sudo docker-compose -f production.yml up`.
172 |
173 | * Assign an `Elastic IP address`_ to your new machine.
174 |
175 | .. _Elastic IP address: https://aws.amazon.com/articles/1346
176 |
177 | * Point your domain name to the elastic IP.
178 |
179 | **Be careful with Elastic IPs** because, on the AWS free tier, if you assign one and then stop the machine you will incur charges while the machine is down (presumably because you're preventing them allocating the IP to someone else).
180 |
181 | Security advisory
182 | ^^^^^^^^^^^^^^^^^
183 |
184 | The setup described in this instruction will get you up-and-running but it hasn't been audited for security. If you are running your own setup like this it is always advisable to, at a minimum, examine your application with a tool like `OWASP ZAP`_ to see what security holes you might be leaving open.
185 |
186 | .. _OWASP ZAP: https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project
187 |
--------------------------------------------------------------------------------
/docs/conf.py:
--------------------------------------------------------------------------------
1 | # todobackend documentation build configuration file, created by
2 | # sphinx-quickstart.
3 | #
4 | # This file is execfile()d with the current directory set to its containing dir.
5 | #
6 | # Note that not all possible configuration values are present in this
7 | # autogenerated file.
8 | #
9 | # All configuration values have a default; values that are commented out
10 | # serve to show the default.
11 |
12 | import os
13 | import sys
14 |
15 | # If extensions (or modules to document with autodoc) are in another directory,
16 | # add these directories to sys.path here. If the directory is relative to the
17 | # documentation root, use os.path.abspath to make it absolute, like shown here.
18 | # sys.path.insert(0, os.path.abspath('.'))
19 |
20 | # -- General configuration -----------------------------------------------------
21 |
22 | # If your documentation needs a minimal Sphinx version, state it here.
23 | # needs_sphinx = '1.0'
24 |
25 | # Add any Sphinx extension module names here, as strings. They can be extensions
26 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
27 | extensions = []
28 |
29 | # Add any paths that contain templates here, relative to this directory.
30 | templates_path = ['_templates']
31 |
32 | # The suffix of source filenames.
33 | source_suffix = '.rst'
34 |
35 | # The encoding of source files.
36 | # source_encoding = 'utf-8-sig'
37 |
38 | # The master toctree document.
39 | master_doc = 'index'
40 |
41 | # General information about the project.
42 | project = 'todobackend'
43 | copyright = """2018, James Lin"""
44 |
45 | # The version info for the project you're documenting, acts as replacement for
46 | # |version| and |release|, also used in various other places throughout the
47 | # built documents.
48 | #
49 | # The short X.Y version.
50 | version = '0.1'
51 | # The full version, including alpha/beta/rc tags.
52 | release = '0.1'
53 |
54 | # The language for content autogenerated by Sphinx. Refer to documentation
55 | # for a list of supported languages.
56 | # language = None
57 |
58 | # There are two options for replacing |today|: either, you set today to some
59 | # non-false value, then it is used:
60 | # today = ''
61 | # Else, today_fmt is used as the format for a strftime call.
62 | # today_fmt = '%B %d, %Y'
63 |
64 | # List of patterns, relative to source directory, that match files and
65 | # directories to ignore when looking for source files.
66 | exclude_patterns = ['_build']
67 |
68 | # The reST default role (used for this markup: `text`) to use for all documents.
69 | # default_role = None
70 |
71 | # If true, '()' will be appended to :func: etc. cross-reference text.
72 | # add_function_parentheses = True
73 |
74 | # If true, the current module name will be prepended to all description
75 | # unit titles (such as .. function::).
76 | # add_module_names = True
77 |
78 | # If true, sectionauthor and moduleauthor directives will be shown in the
79 | # output. They are ignored by default.
80 | # show_authors = False
81 |
82 | # The name of the Pygments (syntax highlighting) style to use.
83 | pygments_style = 'sphinx'
84 |
85 | # A list of ignored prefixes for module index sorting.
86 | # modindex_common_prefix = []
87 |
88 |
89 | # -- Options for HTML output ---------------------------------------------------
90 |
91 | # The theme to use for HTML and HTML Help pages. See the documentation for
92 | # a list of builtin themes.
93 | html_theme = 'default'
94 |
95 | # Theme options are theme-specific and customize the look and feel of a theme
96 | # further. For a list of options available for each theme, see the
97 | # documentation.
98 | # html_theme_options = {}
99 |
100 | # Add any paths that contain custom themes here, relative to this directory.
101 | # html_theme_path = []
102 |
103 | # The name for this set of Sphinx documents. If None, it defaults to
104 | # " v documentation".
105 | # html_title = None
106 |
107 | # A shorter title for the navigation bar. Default is the same as html_title.
108 | # html_short_title = None
109 |
110 | # The name of an image file (relative to this directory) to place at the top
111 | # of the sidebar.
112 | # html_logo = None
113 |
114 | # The name of an image file (within the static path) to use as favicon of the
115 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
116 | # pixels large.
117 | # html_favicon = None
118 |
119 | # Add any paths that contain custom static files (such as style sheets) here,
120 | # relative to this directory. They are copied after the builtin static files,
121 | # so a file named "default.css" will overwrite the builtin "default.css".
122 | html_static_path = ['_static']
123 |
124 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
125 | # using the given strftime format.
126 | # html_last_updated_fmt = '%b %d, %Y'
127 |
128 | # If true, SmartyPants will be used to convert quotes and dashes to
129 | # typographically correct entities.
130 | # html_use_smartypants = True
131 |
132 | # Custom sidebar templates, maps document names to template names.
133 | # html_sidebars = {}
134 |
135 | # Additional templates that should be rendered to pages, maps page names to
136 | # template names.
137 | # html_additional_pages = {}
138 |
139 | # If false, no module index is generated.
140 | # html_domain_indices = True
141 |
142 | # If false, no index is generated.
143 | # html_use_index = True
144 |
145 | # If true, the index is split into individual pages for each letter.
146 | # html_split_index = False
147 |
148 | # If true, links to the reST sources are added to the pages.
149 | # html_show_sourcelink = True
150 |
151 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
152 | # html_show_sphinx = True
153 |
154 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
155 | # html_show_copyright = True
156 |
157 | # If true, an OpenSearch description file will be output, and all pages will
158 | # contain a tag referring to it. The value of this option must be the
159 | # base URL from which the finished HTML is served.
160 | # html_use_opensearch = ''
161 |
162 | # This is the file name suffix for HTML files (e.g. ".xhtml").
163 | # html_file_suffix = None
164 |
165 | # Output file base name for HTML help builder.
166 | htmlhelp_basename = 'todobackenddoc'
167 |
168 |
169 | # -- Options for LaTeX output --------------------------------------------------
170 |
171 | latex_elements = {
172 | # The paper size ('letterpaper' or 'a4paper').
173 | # 'papersize': 'letterpaper',
174 |
175 | # The font size ('10pt', '11pt' or '12pt').
176 | # 'pointsize': '10pt',
177 |
178 | # Additional stuff for the LaTeX preamble.
179 | # 'preamble': '',
180 | }
181 |
182 | # Grouping the document tree into LaTeX files. List of tuples
183 | # (source start file, target name, title, author, documentclass [howto/manual]).
184 | latex_documents = [
185 | ('index',
186 | 'todobackend.tex',
187 | 'todobackend Documentation',
188 | """James Lin""", 'manual'),
189 | ]
190 |
191 | # The name of an image file (relative to this directory) to place at the top of
192 | # the title page.
193 | # latex_logo = None
194 |
195 | # For "manual" documents, if this is true, then toplevel headings are parts,
196 | # not chapters.
197 | # latex_use_parts = False
198 |
199 | # If true, show page references after internal links.
200 | # latex_show_pagerefs = False
201 |
202 | # If true, show URL addresses after external links.
203 | # latex_show_urls = False
204 |
205 | # Documents to append as an appendix to all manuals.
206 | # latex_appendices = []
207 |
208 | # If false, no module index is generated.
209 | # latex_domain_indices = True
210 |
211 |
212 | # -- Options for manual page output --------------------------------------------
213 |
214 | # One entry per manual page. List of tuples
215 | # (source start file, name, description, authors, manual section).
216 | man_pages = [
217 | ('index', 'todobackend', 'todobackend Documentation',
218 | ["""James Lin"""], 1)
219 | ]
220 |
221 | # If true, show URL addresses after external links.
222 | # man_show_urls = False
223 |
224 |
225 | # -- Options for Texinfo output ------------------------------------------------
226 |
227 | # Grouping the document tree into Texinfo files. List of tuples
228 | # (source start file, target name, title, author,
229 | # dir menu entry, description, category)
230 | texinfo_documents = [
231 | ('index', 'todobackend', 'todobackend Documentation',
232 | """James Lin""", 'todobackend',
233 | """A playable todo list backend""", 'Miscellaneous'),
234 | ]
235 |
236 | # Documents to append as an appendix to all manuals.
237 | # texinfo_appendices = []
238 |
239 | # If false, no module index is generated.
240 | # texinfo_domain_indices = True
241 |
242 | # How to display URL addresses: 'footnote', 'no', or 'inline'.
243 | # texinfo_show_urls = 'footnote'
244 |
--------------------------------------------------------------------------------
/config/settings/base.py:
--------------------------------------------------------------------------------
1 | """
2 | Base settings for todobackend project.
3 |
4 | For more information on this file, see
5 | https://docs.djangoproject.com/en/dev/topics/settings/
6 |
7 | For the full list of settings and their values, see
8 | https://docs.djangoproject.com/en/dev/ref/settings/
9 | """
10 | import environ
11 |
12 | ROOT_DIR = environ.Path(__file__) - 3 # (todobackend/config/settings/base.py - 3 = todobackend/)
13 | APPS_DIR = ROOT_DIR.path('todobackend')
14 |
15 | # Load operating system environment variables and then prepare to use them
16 | env = environ.Env()
17 |
18 | # .env file, should load only in development environment
19 | READ_DOT_ENV_FILE = env.bool('DJANGO_READ_DOT_ENV_FILE', default=False)
20 |
21 | if READ_DOT_ENV_FILE:
22 | # Operating System Environment variables have precedence over variables defined in the .env file,
23 | # that is to say variables from the .env files will only be used if not defined
24 | # as environment variables.
25 | env_file = str(ROOT_DIR.path('.env'))
26 | print('Loading : {}'.format(env_file))
27 | env.read_env(env_file)
28 | print('The .env file has been loaded. See base.py for more information')
29 |
30 | # APP CONFIGURATION
31 | # ------------------------------------------------------------------------------
32 | DJANGO_APPS = [
33 | # Default Django apps:
34 | 'django.contrib.auth',
35 | 'django.contrib.contenttypes',
36 | 'django.contrib.sessions',
37 | 'django.contrib.sites',
38 | 'django.contrib.messages',
39 | 'django.contrib.staticfiles',
40 |
41 | # Useful template tags:
42 | # 'django.contrib.humanize',
43 |
44 | # Admin
45 | 'django.contrib.admin',
46 | ]
47 | THIRD_PARTY_APPS = [
48 | 'crispy_forms', # Form layouts
49 | 'allauth', # registration
50 | 'allauth.account', # registration
51 | 'allauth.socialaccount', # registration
52 | 'rest_framework',
53 | 'corsheaders',
54 | ]
55 |
56 | # Apps specific for this project go here.
57 | LOCAL_APPS = [
58 | # custom users app
59 | 'todobackend.users.apps.UsersConfig',
60 | 'todobackend.todos',
61 | # Your stuff: custom apps go here
62 | ]
63 |
64 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
65 | INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
66 |
67 | # MIDDLEWARE CONFIGURATION
68 | # ------------------------------------------------------------------------------
69 | MIDDLEWARE = [
70 | 'django.middleware.security.SecurityMiddleware',
71 | 'django.contrib.sessions.middleware.SessionMiddleware',
72 | 'corsheaders.middleware.CorsMiddleware',
73 | 'django.middleware.common.CommonMiddleware',
74 | 'django.middleware.csrf.CsrfViewMiddleware',
75 | 'django.contrib.auth.middleware.AuthenticationMiddleware',
76 | 'django.contrib.messages.middleware.MessageMiddleware',
77 | 'django.middleware.clickjacking.XFrameOptionsMiddleware',
78 | ]
79 |
80 | # MIGRATIONS CONFIGURATION
81 | # ------------------------------------------------------------------------------
82 | MIGRATION_MODULES = {
83 | 'sites': 'todobackend.contrib.sites.migrations'
84 | }
85 |
86 | # DEBUG
87 | # ------------------------------------------------------------------------------
88 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#debug
89 | DEBUG = env.bool('DJANGO_DEBUG', False)
90 |
91 | # FIXTURE CONFIGURATION
92 | # ------------------------------------------------------------------------------
93 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS
94 | FIXTURE_DIRS = (
95 | str(APPS_DIR.path('fixtures')),
96 | )
97 |
98 | # EMAIL CONFIGURATION
99 | # ------------------------------------------------------------------------------
100 | EMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND', default='django.core.mail.backends.smtp.EmailBackend')
101 |
102 | # MANAGER CONFIGURATION
103 | # ------------------------------------------------------------------------------
104 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#admins
105 | ADMINS = [
106 | ("""James Lin""", 'james@lin.net.nz'),
107 | ]
108 |
109 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#managers
110 | MANAGERS = ADMINS
111 |
112 | # DATABASE CONFIGURATION
113 | # ------------------------------------------------------------------------------
114 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#databases
115 | # Uses django-environ to accept uri format
116 | # See: https://django-environ.readthedocs.io/en/latest/#supported-types
117 | DATABASES = {
118 | 'default': env.db('DATABASE_URL', default='mysql://root:@localhost/todobackend'),
119 | }
120 | DATABASES['default']['ATOMIC_REQUESTS'] = True
121 |
122 |
123 | # GENERAL CONFIGURATION
124 | # ------------------------------------------------------------------------------
125 | # Local time zone for this installation. Choices can be found here:
126 | # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
127 | # although not all choices may be available on all operating systems.
128 | # In a Windows environment this must be set to your system time zone.
129 | TIME_ZONE = 'UTC'
130 |
131 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code
132 | LANGUAGE_CODE = 'en-nz'
133 |
134 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id
135 | SITE_ID = 1
136 |
137 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n
138 | USE_I18N = True
139 |
140 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n
141 | USE_L10N = True
142 |
143 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz
144 | USE_TZ = True
145 |
146 | # TEMPLATE CONFIGURATION
147 | # ------------------------------------------------------------------------------
148 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#templates
149 | TEMPLATES = [
150 | {
151 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATES-BACKEND
152 | 'BACKEND': 'django.template.backends.django.DjangoTemplates',
153 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs
154 | 'DIRS': [
155 | str(APPS_DIR.path('templates')),
156 | ],
157 | 'OPTIONS': {
158 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug
159 | 'debug': DEBUG,
160 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders
161 | # https://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types
162 | 'loaders': [
163 | 'django.template.loaders.filesystem.Loader',
164 | 'django.template.loaders.app_directories.Loader',
165 | ],
166 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors
167 | 'context_processors': [
168 | 'django.template.context_processors.debug',
169 | 'django.template.context_processors.request',
170 | 'django.contrib.auth.context_processors.auth',
171 | 'django.template.context_processors.i18n',
172 | 'django.template.context_processors.media',
173 | 'django.template.context_processors.static',
174 | 'django.template.context_processors.tz',
175 | 'django.contrib.messages.context_processors.messages',
176 | # Your stuff: custom template context processors go here
177 | ],
178 | },
179 | },
180 | ]
181 |
182 | # See: http://django-crispy-forms.readthedocs.io/en/latest/install.html#template-packs
183 | CRISPY_TEMPLATE_PACK = 'bootstrap4'
184 |
185 | # STATIC FILE CONFIGURATION
186 | # ------------------------------------------------------------------------------
187 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root
188 | STATIC_ROOT = str(ROOT_DIR('staticfiles'))
189 |
190 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url
191 | STATIC_URL = '/static/'
192 |
193 | # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS
194 | STATICFILES_DIRS = [
195 | str(APPS_DIR.path('static')),
196 | ]
197 |
198 | # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
199 | STATICFILES_FINDERS = [
200 | 'django.contrib.staticfiles.finders.FileSystemFinder',
201 | 'django.contrib.staticfiles.finders.AppDirectoriesFinder',
202 | ]
203 |
204 | # MEDIA CONFIGURATION
205 | # ------------------------------------------------------------------------------
206 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root
207 | MEDIA_ROOT = str(APPS_DIR('media'))
208 |
209 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url
210 | MEDIA_URL = '/media/'
211 |
212 | # URL Configuration
213 | # ------------------------------------------------------------------------------
214 | ROOT_URLCONF = 'config.urls'
215 |
216 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application
217 | WSGI_APPLICATION = 'config.wsgi.application'
218 |
219 | # PASSWORD STORAGE SETTINGS
220 | # ------------------------------------------------------------------------------
221 | # See https://docs.djangoproject.com/en/dev/topics/auth/passwords/#using-argon2-with-django
222 | PASSWORD_HASHERS = [
223 | 'django.contrib.auth.hashers.Argon2PasswordHasher',
224 | 'django.contrib.auth.hashers.PBKDF2PasswordHasher',
225 | 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
226 | 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
227 | 'django.contrib.auth.hashers.BCryptPasswordHasher',
228 | ]
229 |
230 | # PASSWORD VALIDATION
231 | # https://docs.djangoproject.com/en/dev/ref/settings/#auth-password-validators
232 | # ------------------------------------------------------------------------------
233 |
234 | AUTH_PASSWORD_VALIDATORS = [
235 | {
236 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
237 | },
238 | {
239 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
240 | },
241 | {
242 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
243 | },
244 | {
245 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
246 | },
247 | ]
248 |
249 | # AUTHENTICATION CONFIGURATION
250 | # ------------------------------------------------------------------------------
251 | AUTHENTICATION_BACKENDS = [
252 | 'django.contrib.auth.backends.ModelBackend',
253 | 'allauth.account.auth_backends.AuthenticationBackend',
254 | ]
255 |
256 | # Some really nice defaults
257 | ACCOUNT_AUTHENTICATION_METHOD = 'username'
258 | ACCOUNT_EMAIL_REQUIRED = True
259 | ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
260 |
261 | ACCOUNT_ALLOW_REGISTRATION = env.bool('DJANGO_ACCOUNT_ALLOW_REGISTRATION', True)
262 | ACCOUNT_ADAPTER = 'todobackend.users.adapters.AccountAdapter'
263 | SOCIALACCOUNT_ADAPTER = 'todobackend.users.adapters.SocialAccountAdapter'
264 |
265 | # Custom user app defaults
266 | # Select the correct user model
267 | AUTH_USER_MODEL = 'users.User'
268 | LOGIN_REDIRECT_URL = 'users:redirect'
269 | LOGIN_URL = 'account_login'
270 |
271 | # SLUGLIFIER
272 | AUTOSLUG_SLUGIFY_FUNCTION = 'slugify.slugify'
273 |
274 |
275 | # Location of root django.contrib.admin URL, use {% url 'admin:index' %}
276 | ADMIN_URL = r'^admin/'
277 |
278 | # Your common stuff: Below this line define 3rd party library settings
279 | CORS_ORIGIN_ALLOW_ALL = True
280 | # ------------------------------------------------------------------------------
281 |
--------------------------------------------------------------------------------
/todobackend/static/js/vuex.js:
--------------------------------------------------------------------------------
1 | /**
2 | * vuex v3.0.1
3 | * (c) 2017 Evan You
4 | * @license MIT
5 | */
6 | (function (global, factory) {
7 | typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
8 | typeof define === 'function' && define.amd ? define(factory) :
9 | (global.Vuex = factory());
10 | }(this, (function () { 'use strict';
11 |
12 | var applyMixin = function (Vue) {
13 | var version = Number(Vue.version.split('.')[0]);
14 |
15 | if (version >= 2) {
16 | Vue.mixin({ beforeCreate: vuexInit });
17 | } else {
18 | // override init and inject vuex init procedure
19 | // for 1.x backwards compatibility.
20 | var _init = Vue.prototype._init;
21 | Vue.prototype._init = function (options) {
22 | if ( options === void 0 ) options = {};
23 |
24 | options.init = options.init
25 | ? [vuexInit].concat(options.init)
26 | : vuexInit;
27 | _init.call(this, options);
28 | };
29 | }
30 |
31 | /**
32 | * Vuex init hook, injected into each instances init hooks list.
33 | */
34 |
35 | function vuexInit () {
36 | var options = this.$options;
37 | // store injection
38 | if (options.store) {
39 | this.$store = typeof options.store === 'function'
40 | ? options.store()
41 | : options.store;
42 | } else if (options.parent && options.parent.$store) {
43 | this.$store = options.parent.$store;
44 | }
45 | }
46 | };
47 |
48 | var devtoolHook =
49 | typeof window !== 'undefined' &&
50 | window.__VUE_DEVTOOLS_GLOBAL_HOOK__;
51 |
52 | function devtoolPlugin (store) {
53 | if (!devtoolHook) { return }
54 |
55 | store._devtoolHook = devtoolHook;
56 |
57 | devtoolHook.emit('vuex:init', store);
58 |
59 | devtoolHook.on('vuex:travel-to-state', function (targetState) {
60 | store.replaceState(targetState);
61 | });
62 |
63 | store.subscribe(function (mutation, state) {
64 | devtoolHook.emit('vuex:mutation', mutation, state);
65 | });
66 | }
67 |
68 | /**
69 | * Get the first item that pass the test
70 | * by second argument function
71 | *
72 | * @param {Array} list
73 | * @param {Function} f
74 | * @return {*}
75 | */
76 | /**
77 | * Deep copy the given object considering circular structure.
78 | * This function caches all nested objects and its copies.
79 | * If it detects circular structure, use cached copy to avoid infinite loop.
80 | *
81 | * @param {*} obj
82 | * @param {Array} cache
83 | * @return {*}
84 | */
85 |
86 |
87 | /**
88 | * forEach for object
89 | */
90 | function forEachValue (obj, fn) {
91 | Object.keys(obj).forEach(function (key) { return fn(obj[key], key); });
92 | }
93 |
94 | function isObject (obj) {
95 | return obj !== null && typeof obj === 'object'
96 | }
97 |
98 | function isPromise (val) {
99 | return val && typeof val.then === 'function'
100 | }
101 |
102 | function assert (condition, msg) {
103 | if (!condition) { throw new Error(("[vuex] " + msg)) }
104 | }
105 |
106 | var Module = function Module (rawModule, runtime) {
107 | this.runtime = runtime;
108 | this._children = Object.create(null);
109 | this._rawModule = rawModule;
110 | var rawState = rawModule.state;
111 | this.state = (typeof rawState === 'function' ? rawState() : rawState) || {};
112 | };
113 |
114 | var prototypeAccessors$1 = { namespaced: { configurable: true } };
115 |
116 | prototypeAccessors$1.namespaced.get = function () {
117 | return !!this._rawModule.namespaced
118 | };
119 |
120 | Module.prototype.addChild = function addChild (key, module) {
121 | this._children[key] = module;
122 | };
123 |
124 | Module.prototype.removeChild = function removeChild (key) {
125 | delete this._children[key];
126 | };
127 |
128 | Module.prototype.getChild = function getChild (key) {
129 | return this._children[key]
130 | };
131 |
132 | Module.prototype.update = function update (rawModule) {
133 | this._rawModule.namespaced = rawModule.namespaced;
134 | if (rawModule.actions) {
135 | this._rawModule.actions = rawModule.actions;
136 | }
137 | if (rawModule.mutations) {
138 | this._rawModule.mutations = rawModule.mutations;
139 | }
140 | if (rawModule.getters) {
141 | this._rawModule.getters = rawModule.getters;
142 | }
143 | };
144 |
145 | Module.prototype.forEachChild = function forEachChild (fn) {
146 | forEachValue(this._children, fn);
147 | };
148 |
149 | Module.prototype.forEachGetter = function forEachGetter (fn) {
150 | if (this._rawModule.getters) {
151 | forEachValue(this._rawModule.getters, fn);
152 | }
153 | };
154 |
155 | Module.prototype.forEachAction = function forEachAction (fn) {
156 | if (this._rawModule.actions) {
157 | forEachValue(this._rawModule.actions, fn);
158 | }
159 | };
160 |
161 | Module.prototype.forEachMutation = function forEachMutation (fn) {
162 | if (this._rawModule.mutations) {
163 | forEachValue(this._rawModule.mutations, fn);
164 | }
165 | };
166 |
167 | Object.defineProperties( Module.prototype, prototypeAccessors$1 );
168 |
169 | var ModuleCollection = function ModuleCollection (rawRootModule) {
170 | // register root module (Vuex.Store options)
171 | this.register([], rawRootModule, false);
172 | };
173 |
174 | ModuleCollection.prototype.get = function get (path) {
175 | return path.reduce(function (module, key) {
176 | return module.getChild(key)
177 | }, this.root)
178 | };
179 |
180 | ModuleCollection.prototype.getNamespace = function getNamespace (path) {
181 | var module = this.root;
182 | return path.reduce(function (namespace, key) {
183 | module = module.getChild(key);
184 | return namespace + (module.namespaced ? key + '/' : '')
185 | }, '')
186 | };
187 |
188 | ModuleCollection.prototype.update = function update$1 (rawRootModule) {
189 | update([], this.root, rawRootModule);
190 | };
191 |
192 | ModuleCollection.prototype.register = function register (path, rawModule, runtime) {
193 | var this$1 = this;
194 | if ( runtime === void 0 ) runtime = true;
195 |
196 | {
197 | assertRawModule(path, rawModule);
198 | }
199 |
200 | var newModule = new Module(rawModule, runtime);
201 | if (path.length === 0) {
202 | this.root = newModule;
203 | } else {
204 | var parent = this.get(path.slice(0, -1));
205 | parent.addChild(path[path.length - 1], newModule);
206 | }
207 |
208 | // register nested modules
209 | if (rawModule.modules) {
210 | forEachValue(rawModule.modules, function (rawChildModule, key) {
211 | this$1.register(path.concat(key), rawChildModule, runtime);
212 | });
213 | }
214 | };
215 |
216 | ModuleCollection.prototype.unregister = function unregister (path) {
217 | var parent = this.get(path.slice(0, -1));
218 | var key = path[path.length - 1];
219 | if (!parent.getChild(key).runtime) { return }
220 |
221 | parent.removeChild(key);
222 | };
223 |
224 | function update (path, targetModule, newModule) {
225 | {
226 | assertRawModule(path, newModule);
227 | }
228 |
229 | // update target module
230 | targetModule.update(newModule);
231 |
232 | // update nested modules
233 | if (newModule.modules) {
234 | for (var key in newModule.modules) {
235 | if (!targetModule.getChild(key)) {
236 | {
237 | console.warn(
238 | "[vuex] trying to add a new module '" + key + "' on hot reloading, " +
239 | 'manual reload is needed'
240 | );
241 | }
242 | return
243 | }
244 | update(
245 | path.concat(key),
246 | targetModule.getChild(key),
247 | newModule.modules[key]
248 | );
249 | }
250 | }
251 | }
252 |
253 | var functionAssert = {
254 | assert: function (value) { return typeof value === 'function'; },
255 | expected: 'function'
256 | };
257 |
258 | var objectAssert = {
259 | assert: function (value) { return typeof value === 'function' ||
260 | (typeof value === 'object' && typeof value.handler === 'function'); },
261 | expected: 'function or object with "handler" function'
262 | };
263 |
264 | var assertTypes = {
265 | getters: functionAssert,
266 | mutations: functionAssert,
267 | actions: objectAssert
268 | };
269 |
270 | function assertRawModule (path, rawModule) {
271 | Object.keys(assertTypes).forEach(function (key) {
272 | if (!rawModule[key]) { return }
273 |
274 | var assertOptions = assertTypes[key];
275 |
276 | forEachValue(rawModule[key], function (value, type) {
277 | assert(
278 | assertOptions.assert(value),
279 | makeAssertionMessage(path, key, type, value, assertOptions.expected)
280 | );
281 | });
282 | });
283 | }
284 |
285 | function makeAssertionMessage (path, key, type, value, expected) {
286 | var buf = key + " should be " + expected + " but \"" + key + "." + type + "\"";
287 | if (path.length > 0) {
288 | buf += " in module \"" + (path.join('.')) + "\"";
289 | }
290 | buf += " is " + (JSON.stringify(value)) + ".";
291 | return buf
292 | }
293 |
294 | var Vue; // bind on install
295 |
296 | var Store = function Store (options) {
297 | var this$1 = this;
298 | if ( options === void 0 ) options = {};
299 |
300 | // Auto install if it is not done yet and `window` has `Vue`.
301 | // To allow users to avoid auto-installation in some cases,
302 | // this code should be placed here. See #731
303 | if (!Vue && typeof window !== 'undefined' && window.Vue) {
304 | install(window.Vue);
305 | }
306 |
307 | {
308 | assert(Vue, "must call Vue.use(Vuex) before creating a store instance.");
309 | assert(typeof Promise !== 'undefined', "vuex requires a Promise polyfill in this browser.");
310 | assert(this instanceof Store, "Store must be called with the new operator.");
311 | }
312 |
313 | var plugins = options.plugins; if ( plugins === void 0 ) plugins = [];
314 | var strict = options.strict; if ( strict === void 0 ) strict = false;
315 |
316 | var state = options.state; if ( state === void 0 ) state = {};
317 | if (typeof state === 'function') {
318 | state = state() || {};
319 | }
320 |
321 | // store internal state
322 | this._committing = false;
323 | this._actions = Object.create(null);
324 | this._actionSubscribers = [];
325 | this._mutations = Object.create(null);
326 | this._wrappedGetters = Object.create(null);
327 | this._modules = new ModuleCollection(options);
328 | this._modulesNamespaceMap = Object.create(null);
329 | this._subscribers = [];
330 | this._watcherVM = new Vue();
331 |
332 | // bind commit and dispatch to self
333 | var store = this;
334 | var ref = this;
335 | var dispatch = ref.dispatch;
336 | var commit = ref.commit;
337 | this.dispatch = function boundDispatch (type, payload) {
338 | return dispatch.call(store, type, payload)
339 | };
340 | this.commit = function boundCommit (type, payload, options) {
341 | return commit.call(store, type, payload, options)
342 | };
343 |
344 | // strict mode
345 | this.strict = strict;
346 |
347 | // init root module.
348 | // this also recursively registers all sub-modules
349 | // and collects all module getters inside this._wrappedGetters
350 | installModule(this, state, [], this._modules.root);
351 |
352 | // initialize the store vm, which is responsible for the reactivity
353 | // (also registers _wrappedGetters as computed properties)
354 | resetStoreVM(this, state);
355 |
356 | // apply plugins
357 | plugins.forEach(function (plugin) { return plugin(this$1); });
358 |
359 | if (Vue.config.devtools) {
360 | devtoolPlugin(this);
361 | }
362 | };
363 |
364 | var prototypeAccessors = { state: { configurable: true } };
365 |
366 | prototypeAccessors.state.get = function () {
367 | return this._vm._data.$$state
368 | };
369 |
370 | prototypeAccessors.state.set = function (v) {
371 | {
372 | assert(false, "Use store.replaceState() to explicit replace store state.");
373 | }
374 | };
375 |
376 | Store.prototype.commit = function commit (_type, _payload, _options) {
377 | var this$1 = this;
378 |
379 | // check object-style commit
380 | var ref = unifyObjectStyle(_type, _payload, _options);
381 | var type = ref.type;
382 | var payload = ref.payload;
383 | var options = ref.options;
384 |
385 | var mutation = { type: type, payload: payload };
386 | var entry = this._mutations[type];
387 | if (!entry) {
388 | {
389 | console.error(("[vuex] unknown mutation type: " + type));
390 | }
391 | return
392 | }
393 | this._withCommit(function () {
394 | entry.forEach(function commitIterator (handler) {
395 | handler(payload);
396 | });
397 | });
398 | this._subscribers.forEach(function (sub) { return sub(mutation, this$1.state); });
399 |
400 | if (
401 | "development" !== 'production' &&
402 | options && options.silent
403 | ) {
404 | console.warn(
405 | "[vuex] mutation type: " + type + ". Silent option has been removed. " +
406 | 'Use the filter functionality in the vue-devtools'
407 | );
408 | }
409 | };
410 |
411 | Store.prototype.dispatch = function dispatch (_type, _payload) {
412 | var this$1 = this;
413 |
414 | // check object-style dispatch
415 | var ref = unifyObjectStyle(_type, _payload);
416 | var type = ref.type;
417 | var payload = ref.payload;
418 |
419 | var action = { type: type, payload: payload };
420 | var entry = this._actions[type];
421 | if (!entry) {
422 | {
423 | console.error(("[vuex] unknown action type: " + type));
424 | }
425 | return
426 | }
427 |
428 | this._actionSubscribers.forEach(function (sub) { return sub(action, this$1.state); });
429 |
430 | return entry.length > 1
431 | ? Promise.all(entry.map(function (handler) { return handler(payload); }))
432 | : entry[0](payload)
433 | };
434 |
435 | Store.prototype.subscribe = function subscribe (fn) {
436 | return genericSubscribe(fn, this._subscribers)
437 | };
438 |
439 | Store.prototype.subscribeAction = function subscribeAction (fn) {
440 | return genericSubscribe(fn, this._actionSubscribers)
441 | };
442 |
443 | Store.prototype.watch = function watch (getter, cb, options) {
444 | var this$1 = this;
445 |
446 | {
447 | assert(typeof getter === 'function', "store.watch only accepts a function.");
448 | }
449 | return this._watcherVM.$watch(function () { return getter(this$1.state, this$1.getters); }, cb, options)
450 | };
451 |
452 | Store.prototype.replaceState = function replaceState (state) {
453 | var this$1 = this;
454 |
455 | this._withCommit(function () {
456 | this$1._vm._data.$$state = state;
457 | });
458 | };
459 |
460 | Store.prototype.registerModule = function registerModule (path, rawModule, options) {
461 | if ( options === void 0 ) options = {};
462 |
463 | if (typeof path === 'string') { path = [path]; }
464 |
465 | {
466 | assert(Array.isArray(path), "module path must be a string or an Array.");
467 | assert(path.length > 0, 'cannot register the root module by using registerModule.');
468 | }
469 |
470 | this._modules.register(path, rawModule);
471 | installModule(this, this.state, path, this._modules.get(path), options.preserveState);
472 | // reset store to update getters...
473 | resetStoreVM(this, this.state);
474 | };
475 |
476 | Store.prototype.unregisterModule = function unregisterModule (path) {
477 | var this$1 = this;
478 |
479 | if (typeof path === 'string') { path = [path]; }
480 |
481 | {
482 | assert(Array.isArray(path), "module path must be a string or an Array.");
483 | }
484 |
485 | this._modules.unregister(path);
486 | this._withCommit(function () {
487 | var parentState = getNestedState(this$1.state, path.slice(0, -1));
488 | Vue.delete(parentState, path[path.length - 1]);
489 | });
490 | resetStore(this);
491 | };
492 |
493 | Store.prototype.hotUpdate = function hotUpdate (newOptions) {
494 | this._modules.update(newOptions);
495 | resetStore(this, true);
496 | };
497 |
498 | Store.prototype._withCommit = function _withCommit (fn) {
499 | var committing = this._committing;
500 | this._committing = true;
501 | fn();
502 | this._committing = committing;
503 | };
504 |
505 | Object.defineProperties( Store.prototype, prototypeAccessors );
506 |
507 | function genericSubscribe (fn, subs) {
508 | if (subs.indexOf(fn) < 0) {
509 | subs.push(fn);
510 | }
511 | return function () {
512 | var i = subs.indexOf(fn);
513 | if (i > -1) {
514 | subs.splice(i, 1);
515 | }
516 | }
517 | }
518 |
519 | function resetStore (store, hot) {
520 | store._actions = Object.create(null);
521 | store._mutations = Object.create(null);
522 | store._wrappedGetters = Object.create(null);
523 | store._modulesNamespaceMap = Object.create(null);
524 | var state = store.state;
525 | // init all modules
526 | installModule(store, state, [], store._modules.root, true);
527 | // reset vm
528 | resetStoreVM(store, state, hot);
529 | }
530 |
531 | function resetStoreVM (store, state, hot) {
532 | var oldVm = store._vm;
533 |
534 | // bind store public getters
535 | store.getters = {};
536 | var wrappedGetters = store._wrappedGetters;
537 | var computed = {};
538 | forEachValue(wrappedGetters, function (fn, key) {
539 | // use computed to leverage its lazy-caching mechanism
540 | computed[key] = function () { return fn(store); };
541 | Object.defineProperty(store.getters, key, {
542 | get: function () { return store._vm[key]; },
543 | enumerable: true // for local getters
544 | });
545 | });
546 |
547 | // use a Vue instance to store the state tree
548 | // suppress warnings just in case the user has added
549 | // some funky global mixins
550 | var silent = Vue.config.silent;
551 | Vue.config.silent = true;
552 | store._vm = new Vue({
553 | data: {
554 | $$state: state
555 | },
556 | computed: computed
557 | });
558 | Vue.config.silent = silent;
559 |
560 | // enable strict mode for new vm
561 | if (store.strict) {
562 | enableStrictMode(store);
563 | }
564 |
565 | if (oldVm) {
566 | if (hot) {
567 | // dispatch changes in all subscribed watchers
568 | // to force getter re-evaluation for hot reloading.
569 | store._withCommit(function () {
570 | oldVm._data.$$state = null;
571 | });
572 | }
573 | Vue.nextTick(function () { return oldVm.$destroy(); });
574 | }
575 | }
576 |
577 | function installModule (store, rootState, path, module, hot) {
578 | var isRoot = !path.length;
579 | var namespace = store._modules.getNamespace(path);
580 |
581 | // register in namespace map
582 | if (module.namespaced) {
583 | store._modulesNamespaceMap[namespace] = module;
584 | }
585 |
586 | // set state
587 | if (!isRoot && !hot) {
588 | var parentState = getNestedState(rootState, path.slice(0, -1));
589 | var moduleName = path[path.length - 1];
590 | store._withCommit(function () {
591 | Vue.set(parentState, moduleName, module.state);
592 | });
593 | }
594 |
595 | var local = module.context = makeLocalContext(store, namespace, path);
596 |
597 | module.forEachMutation(function (mutation, key) {
598 | var namespacedType = namespace + key;
599 | registerMutation(store, namespacedType, mutation, local);
600 | });
601 |
602 | module.forEachAction(function (action, key) {
603 | var type = action.root ? key : namespace + key;
604 | var handler = action.handler || action;
605 | registerAction(store, type, handler, local);
606 | });
607 |
608 | module.forEachGetter(function (getter, key) {
609 | var namespacedType = namespace + key;
610 | registerGetter(store, namespacedType, getter, local);
611 | });
612 |
613 | module.forEachChild(function (child, key) {
614 | installModule(store, rootState, path.concat(key), child, hot);
615 | });
616 | }
617 |
618 | /**
619 | * make localized dispatch, commit, getters and state
620 | * if there is no namespace, just use root ones
621 | */
622 | function makeLocalContext (store, namespace, path) {
623 | var noNamespace = namespace === '';
624 |
625 | var local = {
626 | dispatch: noNamespace ? store.dispatch : function (_type, _payload, _options) {
627 | var args = unifyObjectStyle(_type, _payload, _options);
628 | var payload = args.payload;
629 | var options = args.options;
630 | var type = args.type;
631 |
632 | if (!options || !options.root) {
633 | type = namespace + type;
634 | if ("development" !== 'production' && !store._actions[type]) {
635 | console.error(("[vuex] unknown local action type: " + (args.type) + ", global type: " + type));
636 | return
637 | }
638 | }
639 |
640 | return store.dispatch(type, payload)
641 | },
642 |
643 | commit: noNamespace ? store.commit : function (_type, _payload, _options) {
644 | var args = unifyObjectStyle(_type, _payload, _options);
645 | var payload = args.payload;
646 | var options = args.options;
647 | var type = args.type;
648 |
649 | if (!options || !options.root) {
650 | type = namespace + type;
651 | if ("development" !== 'production' && !store._mutations[type]) {
652 | console.error(("[vuex] unknown local mutation type: " + (args.type) + ", global type: " + type));
653 | return
654 | }
655 | }
656 |
657 | store.commit(type, payload, options);
658 | }
659 | };
660 |
661 | // getters and state object must be gotten lazily
662 | // because they will be changed by vm update
663 | Object.defineProperties(local, {
664 | getters: {
665 | get: noNamespace
666 | ? function () { return store.getters; }
667 | : function () { return makeLocalGetters(store, namespace); }
668 | },
669 | state: {
670 | get: function () { return getNestedState(store.state, path); }
671 | }
672 | });
673 |
674 | return local
675 | }
676 |
677 | function makeLocalGetters (store, namespace) {
678 | var gettersProxy = {};
679 |
680 | var splitPos = namespace.length;
681 | Object.keys(store.getters).forEach(function (type) {
682 | // skip if the target getter is not match this namespace
683 | if (type.slice(0, splitPos) !== namespace) { return }
684 |
685 | // extract local getter type
686 | var localType = type.slice(splitPos);
687 |
688 | // Add a port to the getters proxy.
689 | // Define as getter property because
690 | // we do not want to evaluate the getters in this time.
691 | Object.defineProperty(gettersProxy, localType, {
692 | get: function () { return store.getters[type]; },
693 | enumerable: true
694 | });
695 | });
696 |
697 | return gettersProxy
698 | }
699 |
700 | function registerMutation (store, type, handler, local) {
701 | var entry = store._mutations[type] || (store._mutations[type] = []);
702 | entry.push(function wrappedMutationHandler (payload) {
703 | handler.call(store, local.state, payload);
704 | });
705 | }
706 |
707 | function registerAction (store, type, handler, local) {
708 | var entry = store._actions[type] || (store._actions[type] = []);
709 | entry.push(function wrappedActionHandler (payload, cb) {
710 | var res = handler.call(store, {
711 | dispatch: local.dispatch,
712 | commit: local.commit,
713 | getters: local.getters,
714 | state: local.state,
715 | rootGetters: store.getters,
716 | rootState: store.state
717 | }, payload, cb);
718 | if (!isPromise(res)) {
719 | res = Promise.resolve(res);
720 | }
721 | if (store._devtoolHook) {
722 | return res.catch(function (err) {
723 | store._devtoolHook.emit('vuex:error', err);
724 | throw err
725 | })
726 | } else {
727 | return res
728 | }
729 | });
730 | }
731 |
732 | function registerGetter (store, type, rawGetter, local) {
733 | if (store._wrappedGetters[type]) {
734 | {
735 | console.error(("[vuex] duplicate getter key: " + type));
736 | }
737 | return
738 | }
739 | store._wrappedGetters[type] = function wrappedGetter (store) {
740 | return rawGetter(
741 | local.state, // local state
742 | local.getters, // local getters
743 | store.state, // root state
744 | store.getters // root getters
745 | )
746 | };
747 | }
748 |
749 | function enableStrictMode (store) {
750 | store._vm.$watch(function () { return this._data.$$state }, function () {
751 | {
752 | assert(store._committing, "Do not mutate vuex store state outside mutation handlers.");
753 | }
754 | }, { deep: true, sync: true });
755 | }
756 |
757 | function getNestedState (state, path) {
758 | return path.length
759 | ? path.reduce(function (state, key) { return state[key]; }, state)
760 | : state
761 | }
762 |
763 | function unifyObjectStyle (type, payload, options) {
764 | if (isObject(type) && type.type) {
765 | options = payload;
766 | payload = type;
767 | type = type.type;
768 | }
769 |
770 | {
771 | assert(typeof type === 'string', ("Expects string as the type, but found " + (typeof type) + "."));
772 | }
773 |
774 | return { type: type, payload: payload, options: options }
775 | }
776 |
777 | function install (_Vue) {
778 | if (Vue && _Vue === Vue) {
779 | {
780 | console.error(
781 | '[vuex] already installed. Vue.use(Vuex) should be called only once.'
782 | );
783 | }
784 | return
785 | }
786 | Vue = _Vue;
787 | applyMixin(Vue);
788 | }
789 |
790 | var mapState = normalizeNamespace(function (namespace, states) {
791 | var res = {};
792 | normalizeMap(states).forEach(function (ref) {
793 | var key = ref.key;
794 | var val = ref.val;
795 |
796 | res[key] = function mappedState () {
797 | var state = this.$store.state;
798 | var getters = this.$store.getters;
799 | if (namespace) {
800 | var module = getModuleByNamespace(this.$store, 'mapState', namespace);
801 | if (!module) {
802 | return
803 | }
804 | state = module.context.state;
805 | getters = module.context.getters;
806 | }
807 | return typeof val === 'function'
808 | ? val.call(this, state, getters)
809 | : state[val]
810 | };
811 | // mark vuex getter for devtools
812 | res[key].vuex = true;
813 | });
814 | return res
815 | });
816 |
817 | var mapMutations = normalizeNamespace(function (namespace, mutations) {
818 | var res = {};
819 | normalizeMap(mutations).forEach(function (ref) {
820 | var key = ref.key;
821 | var val = ref.val;
822 |
823 | res[key] = function mappedMutation () {
824 | var args = [], len = arguments.length;
825 | while ( len-- ) args[ len ] = arguments[ len ];
826 |
827 | var commit = this.$store.commit;
828 | if (namespace) {
829 | var module = getModuleByNamespace(this.$store, 'mapMutations', namespace);
830 | if (!module) {
831 | return
832 | }
833 | commit = module.context.commit;
834 | }
835 | return typeof val === 'function'
836 | ? val.apply(this, [commit].concat(args))
837 | : commit.apply(this.$store, [val].concat(args))
838 | };
839 | });
840 | return res
841 | });
842 |
843 | var mapGetters = normalizeNamespace(function (namespace, getters) {
844 | var res = {};
845 | normalizeMap(getters).forEach(function (ref) {
846 | var key = ref.key;
847 | var val = ref.val;
848 |
849 | val = namespace + val;
850 | res[key] = function mappedGetter () {
851 | if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) {
852 | return
853 | }
854 | if ("development" !== 'production' && !(val in this.$store.getters)) {
855 | console.error(("[vuex] unknown getter: " + val));
856 | return
857 | }
858 | return this.$store.getters[val]
859 | };
860 | // mark vuex getter for devtools
861 | res[key].vuex = true;
862 | });
863 | return res
864 | });
865 |
866 | var mapActions = normalizeNamespace(function (namespace, actions) {
867 | var res = {};
868 | normalizeMap(actions).forEach(function (ref) {
869 | var key = ref.key;
870 | var val = ref.val;
871 |
872 | res[key] = function mappedAction () {
873 | var args = [], len = arguments.length;
874 | while ( len-- ) args[ len ] = arguments[ len ];
875 |
876 | var dispatch = this.$store.dispatch;
877 | if (namespace) {
878 | var module = getModuleByNamespace(this.$store, 'mapActions', namespace);
879 | if (!module) {
880 | return
881 | }
882 | dispatch = module.context.dispatch;
883 | }
884 | return typeof val === 'function'
885 | ? val.apply(this, [dispatch].concat(args))
886 | : dispatch.apply(this.$store, [val].concat(args))
887 | };
888 | });
889 | return res
890 | });
891 |
892 | var createNamespacedHelpers = function (namespace) { return ({
893 | mapState: mapState.bind(null, namespace),
894 | mapGetters: mapGetters.bind(null, namespace),
895 | mapMutations: mapMutations.bind(null, namespace),
896 | mapActions: mapActions.bind(null, namespace)
897 | }); };
898 |
899 | function normalizeMap (map) {
900 | return Array.isArray(map)
901 | ? map.map(function (key) { return ({ key: key, val: key }); })
902 | : Object.keys(map).map(function (key) { return ({ key: key, val: map[key] }); })
903 | }
904 |
905 | function normalizeNamespace (fn) {
906 | return function (namespace, map) {
907 | if (typeof namespace !== 'string') {
908 | map = namespace;
909 | namespace = '';
910 | } else if (namespace.charAt(namespace.length - 1) !== '/') {
911 | namespace += '/';
912 | }
913 | return fn(namespace, map)
914 | }
915 | }
916 |
917 | function getModuleByNamespace (store, helper, namespace) {
918 | var module = store._modulesNamespaceMap[namespace];
919 | if ("development" !== 'production' && !module) {
920 | console.error(("[vuex] module namespace not found in " + helper + "(): " + namespace));
921 | }
922 | return module
923 | }
924 |
925 | var index = {
926 | Store: Store,
927 | install: install,
928 | version: '3.0.1',
929 | mapState: mapState,
930 | mapMutations: mapMutations,
931 | mapGetters: mapGetters,
932 | mapActions: mapActions,
933 | createNamespacedHelpers: createNamespacedHelpers
934 | };
935 |
936 | return index;
937 |
938 | })));
939 |
--------------------------------------------------------------------------------