~sirodoht/mataroa

5ff277da71fb653631ea38407cd6154e831be540 — Theodore Keloglou 10 months ago
project init
A  => .editorconfig +15 -0
@@ 1,15 @@
root = true

[*]
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
indent_style = space
indent_size = 4

[*.md]
trim_trailing_whitespace = false

[*.yml]
indent_size = 2

A  => .env.example +2 -0
@@ 1,2 @@
SECRET_KEY="secret_is_here"
DATABASE_URL="postgres://postgres:postgres@db:5432/postgres"

A  => .github/workflows/django.yml +41 -0
@@ 1,41 @@
name: Django CI

on:
  push:
    branches: [ master ]
  pull_request:
    branches: [ master ]

jobs:
  build:
    runs-on: ubuntu-latest

    services:
      postgres:
        image: postgres
        env:
          POSTGRES_PASSWORD: postgres
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
        ports:
          - 5432:5432

    steps:
    - uses: actions/checkout@v2
    - name: Set up Python 3.8
      uses: actions/setup-python@v1
      with:
        python-version: 3.8
    - name: Install Dependencies
      run: |
        python -m pip install --upgrade pip
        pip install -r requirements.txt
    - name: Run Tests
      run: |
        python manage.py test
      env:
        SECRET_KEY: "thisisthesecretkey"
        DATABASE_URL: "postgres://postgres:postgres@localhost:5432/postgres"

A  => .gitignore +4 -0
@@ 1,4 @@
venv/
db_data/
*.pyc
.env

A  => DOKKU_SCALE +1 -0
@@ 1,1 @@
web=1

A  => Dockerfile +16 -0
@@ 1,16 @@
FROM python:3.8.2
ENV PYTHONUNBUFFERED 1
RUN apt-get update && \
    apt-get install -y --no-install-recommends \
    swig \
    libssl-dev \
    dpkg-dev \
    netcat \
    && rm -rf /var/lib/apt/lists/*

COPY requirements.txt /code/
RUN pip install -U pip && pip install -Ur /code/requirements.txt

WORKDIR /code
COPY . /code/
RUN /code/manage.py collectstatic --noinput

A  => LICENSE +21 -0
@@ 1,21 @@
MIT License

Copyright (c) 2020 Theodore Keloglou

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:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

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.

A  => Procfile +1 -0
@@ 1,1 @@
web: /usr/local/bin/uwsgi --chdir=/code --ini=/code/uwsgi.ini

A  => README.md +135 -0
@@ 1,135 @@
# mataroa

Blogging unplatform.

## Development

This is a [Django](https://www.djangoproject.com/) codebase. Check out the
[Django docs](https://docs.djangoproject.com/) for general technical documentation.

### Structure

The Django project is `mataroa`. There is one Django app, `main`,  with all business logic.

### Dependencies

Using [venv](https://docs.python.org/3/library/venv.html):

```sh
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
```

This project also uses [pip-tools](https://github.com/jazzband/pip-tools) for
dependencies management.

### Environment variables

You need to create a new file named `.env` in the root of this project once you cloned it.

`.env` should contain the following env variables:

```sh
SECRET_KEY="thisisthesecretkey"
DATABASE_URL="postgres://username:password@localhost:5432/db_name"
EMAIL_HOST_USER="smtp_user"
EMAIL_HOST_PASSWORD="smtp_password"
```

### Database

This project uses PostgreSQL. See above on how to configure access to it using
the `.env` file.

There is no need to create manually one if you're using Docker and
[Docker Compose](https://docs.docker.com/compose/). Run this to spin up the
database in the background:

```sh
docker-compose up -d db
```

The database data will be saved in a gitignored directory, `db_data`, in the root of
the project.

To create the database schema:

```sh
python manage.py migrate
```

### Serve

To run the Django development server:

```sh
python manage.py runserver
```

Or, if you prefer to run the web server under Docker:

```sh
docker-compose up web
```

In which case, `DATABASE_URL` in `.env` should be like this:

```sh
DATABASE_URL="postgres://postgres:postgres@db:5432/postgres"
```

You can also run just the database using Docker and the webserver without,
in which case `.env` would be like this:

```sh
DATABASE_URL="postgres://postgres:postgres@127.0.0.1:5432/postgres"
```

and you would start the database like so:

```sh
docker-compose up db
```

## Testing

```sh
python manage.py test
```

## Code linting & formatting

```sh
black . && isort -y && flake8
```

## Deployment

Deployment [is configured](uwsgi.ini) using the production-grade
[uwsgi](https://uwsgi-docs.readthedocs.io/en/latest/) server.

```sh
uwsgi --ini=uwsgi.ini -H venv/
```

You also need to populate your shell environment:

```sh
export SECRET_KEY="thisisthesecretkey"
export DATABASE_URL="postgres://username:password@localhost:5432/db_name"
export EMAIL_HOST_USER="smtp_user"
export EMAIL_HOST_PASSWORD="smtp_password"
```

## Dokku

This project is also configured to deploy to [dokku](http://dokku.viewdocs.io/dokku/).
* [Procfile](Procfile): app init command
* [app.json](app.json): predeploy tasks
* [DOKKU_SCALE](DOKKU_SCALE): process scaling

## License

This software is licensed under the MIT license.
For more information, read the [LICENSE](LICENSE) file.

A  => app.json +7 -0
@@ 1,7 @@
{
  "scripts": {
    "dokku": {
      "predeploy": "python /code/manage.py migrate --noinput"
    }
  }
}

A  => docker-compose.yml +28 -0
@@ 1,28 @@
version: '3.6'

services:
  db:
    image: postgres:11.6
    environment:
      POSTGRES_PASSWORD: postgres
    volumes:
      - ./db_data:/var/lib/postgresql/data
    ports:
      - "5432:5432"
  web:
    # Docker hack to wait until postgres is up
    command: >
      bash -c "while ! nc -w 1 -z db 5432;
               do sleep 0.1;
               done;
               ./manage.py migrate;
               ./manage.py collectstatic --noinput;
               ./manage.py runserver 0.0.0.0:8000"
    build: .
    image: mataroa
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db

A  => main/__init__.py +0 -0
A  => main/admin.py +3 -0
@@ 1,3 @@
# from django.contrib import admin

# Register your models here.

A  => main/apps.py +5 -0
@@ 1,5 @@
from django.apps import AppConfig


class MainConfig(AppConfig):
    name = "main"

A  => main/migrations/__init__.py +0 -0
A  => main/models.py +3 -0
@@ 1,3 @@
# from django.db import models

# Create your models here.

A  => main/tests.py +8 -0
@@ 1,8 @@
from django.test import TestCase
from django.urls import reverse


class IndexTestCase(TestCase):
    def test_index(self):
        response = self.client.get(reverse("index"))
        self.assertEqual(response.status_code, 200)

A  => main/urls.py +10 -0
@@ 1,10 @@
from django.contrib import admin
from django.urls import path

from main import views

admin.site.site_header = "mataroa administration"

urlpatterns = [
    path("", views.index, name="index"),
]

A  => main/views.py +4 -0
@@ 1,4 @@
from django.shortcuts import render

def index(request):
    return render(request, "main/index.html")

A  => manage.py +25 -0
@@ 1,25 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys

import dotenv


def main():
    dotenv.read_dotenv()

    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mataroa.settings")
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)


if __name__ == "__main__":
    main()

A  => mataroa/__init__.py +0 -0
A  => mataroa/asgi.py +16 -0
@@ 1,16 @@
"""
ASGI config for mataroa project.

It exposes the ASGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mataroa.settings")

application = get_asgi_application()

A  => mataroa/settings.py +129 -0
@@ 1,129 @@
"""
Django settings for mataroa project.

Generated by 'django-admin startproject' using Django 3.0.6.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os

import dj_database_url

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get("SECRET_KEY", "nonrandom_secret")

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True if os.environ.get("NODEBUG") is None else False

ALLOWED_HOSTS = ["localhost", "127.0.0.1"]


# Application definition

INSTALLED_APPS = [
    "main.apps.MainConfig",
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "mataroa.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

WSGI_APPLICATION = "mataroa.wsgi.application"

SESSION_COOKIE_AGE = 31449600  # 60 * 60 * 24 * 7 * 52 = 1 year in seconds


# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {"default": {"ENGINE": "django.db.backends.postgresql"}}
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES["default"].update(db_from_env)


# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"
    },
    {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
    {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
    {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
]


# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = False

USE_L10N = False

USE_TZ = False


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = "/static/"
STATIC_ROOT = os.path.join(BASE_DIR, "_static")


# Security middleware

if not DEBUG:
    SECURE_CONTENT_TYPE_NOSNIFF = True
    SECURE_BROWSER_XSS_FILTER = True
    X_FRAME_OPTIONS = "DENY"
    SESSION_COOKIE_SECURE = True
    CSRF_COOKIE_SECURE = True
    SECURE_SSL_REDIRECT = True

A  => mataroa/urls.py +22 -0
@@ 1,22 @@
"""mataroa URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path("admin/", admin.site.urls),
    path("", include("main.urls")),
]

A  => mataroa/wsgi.py +16 -0
@@ 1,16 @@
"""
WSGI config for mataroa project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mataroa.settings")

application = get_wsgi_application()

A  => pyproject.toml +2 -0
@@ 1,2 @@
[tool.black]
exclude = '/(\.git|venv)/'

A  => requirements.in +10 -0
@@ 1,10 @@
django
psycopg2-binary
dj-database-url
whitenoise
uwsgi
django-dotenv
isort
flake8
black
markdown

A  => requirements.txt +31 -0
@@ 1,31 @@
#
# This file is autogenerated by pip-compile
# To update, run:
#
#    pip-compile
#
appdirs==1.4.4            # via black
asgiref==3.2.7            # via django
attrs==19.3.0             # via black
black==19.10b0            # via -r requirements.in
click==7.1.2              # via black
dj-database-url==0.5.0    # via -r requirements.in
django-dotenv==1.4.2      # via -r requirements.in
django==3.0.6             # via -r requirements.in
flake8==3.8.2             # via -r requirements.in
importlib-metadata==1.6.0  # via flake8, markdown
isort==4.3.21             # via -r requirements.in
markdown==3.2.2           # via -r requirements.in
mccabe==0.6.1             # via flake8
pathspec==0.8.0           # via black
psycopg2-binary==2.8.5    # via -r requirements.in
pycodestyle==2.6.0        # via flake8
pyflakes==2.2.0           # via flake8
pytz==2020.1              # via django
regex==2020.5.14          # via black
sqlparse==0.3.1           # via django
toml==0.10.1              # via black
typed-ast==1.4.1          # via black
uwsgi==2.0.18             # via -r requirements.in
whitenoise==5.1.0         # via -r requirements.in
zipp==3.1.0               # via importlib-metadata

A  => setup.cfg +13 -0
@@ 1,13 @@
[isort]
multi_line_output = 3
include_trailing_comma = True
force_grid_wrap = 0
combine_as_imports = True
line_length = 88
skip=.git/,venv/

[flake8]
ignore = E203, E266, E501, W503
max-line-length = 88
max-complexity = 18
exclude=.git/,venv/

A  => uwsgi.ini +9 -0
@@ 1,9 @@
[uwsgi]
module=mataroa.wsgi:application
master=True
vacuum=True
max-requests=5000
http-socket=:5000
processes=3
harakiri=120
enable-threads=True