Merge pull request #1 from imakecodes/feature/bootstrap

Adding the initial files for the API
This commit is contained in:
2020-11-04 22:46:52 -03:00
committed by GitHub
26 changed files with 632 additions and 1 deletions

20
.editorconfig Normal file
View File

@@ -0,0 +1,20 @@
# editorconfig.org
root = true
[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.yml]
indent_size = 2
[*.yaml]
indent_size = 2
[Makefile]
indent_style = tab
indent_size = 4

2
.flake8 Normal file
View File

@@ -0,0 +1,2 @@
[flake8]
max-line-length = 120

2
.gitignore vendored
View File

@@ -1,3 +1,5 @@
.vscode
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]

12
Dockerfile Normal file
View File

@@ -0,0 +1,12 @@
FROM python:3.8
ADD . /app
WORKDIR /app
RUN apt-get update && apt-get install -y \
bash \
default-libmysqlclient-dev \
build-essential \
&& pip install --no-cache-dir -r /app/requirements.txt
CMD ["/app/commands/run-prod.sh"]

20
Makefile Normal file
View File

@@ -0,0 +1,20 @@
all: help
help:
@echo "―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――"
@echo " Available commands "
@echo "―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――"
@echo "⭐️ help : Show this message"
@echo "⭐️ clean : Removes all python cache and temporary files"
@echo "⭐️ run : Runs the application using docker-compose"
@echo "―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――"
clean:
@find . -name '*.pyc' -exec rm -f {} +
@find . -name '*.pyo' -exec rm -f {} +
@find . -name '*~' -exec rm -f {} +
@find . -name '__pycache__' -exec rm -fr {} +
run:
@docker-compose up

View File

@@ -1 +1,2 @@
# minesweeper-backend
# Minesweeper (backend)

0
app/__init__.py Normal file
View File

16
app/asgi.py Normal file
View File

@@ -0,0 +1,16 @@
"""
ASGI config for app 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.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")
application = get_asgi_application()

114
app/settings.py Normal file
View File

@@ -0,0 +1,114 @@
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.getenv("SECRET_KEY", "changeme")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.getenv("DEBUG", "0") in ["1", "true"]
ALLOWED_HOSTS = os.getenv("ALLOWED_HOSTS", "127.0.0.1,localhost").split(",")
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"core",
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = "app.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 = "app.wsgi.application"
AUTH_USER_MODEL = "core.User"
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.mysql",
"NAME": os.getenv("DB_NAME"),
"USER": os.getenv("DB_USER"),
"PASSWORD": os.getenv("DB_PASS"),
"HOST": os.getenv("DB_HOST"),
"PORT": os.getenv("DB_PORT"),
"OPTIONS": {
"charset": "utf8mb4",
},
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/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.1/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = "/static/"

21
app/urls.py Normal file
View File

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

16
app/wsgi.py Normal file
View File

@@ -0,0 +1,16 @@
"""
WSGI config for app 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.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")
application = get_wsgi_application()

2
commands/run-prod.sh Executable file
View File

@@ -0,0 +1,2 @@
#!/bin/bash
uwsgi --module app.wsgi --http 0.0.0.0:8000 --enable-threads --thunder-lock

2
commands/run.sh Executable file
View File

@@ -0,0 +1,2 @@
#!/bin/bash
/commands/wait-for-it.sh "${DB_HOST}:${DB_PORT}" --timeout=90 --strict -- python manage.py runserver 0.0.0.0:8000

177
commands/wait-for-it.sh Executable file
View File

@@ -0,0 +1,177 @@
#!/bin/bash
# Use this script to test if a given TCP host/port are available
cmdname=$(basename $0)
echoerr() { if [[ $QUIET -ne 1 ]]; then echo "$@" 1>&2; fi }
usage()
{
cat << USAGE >&2
Usage:
$cmdname host:port [-s] [-t timeout] [-- command args]
-h HOST | --host=HOST Host or IP under test
-p PORT | --port=PORT TCP port under test
Alternatively, you specify the host and port as host:port
-s | --strict Only execute subcommand if the test succeeds
-q | --quiet Don't output any status messages
-t TIMEOUT | --timeout=TIMEOUT
Timeout in seconds, zero for no timeout
-- COMMAND ARGS Execute command with args after the test finishes
USAGE
exit 1
}
wait_for()
{
if [[ $TIMEOUT -gt 0 ]]; then
echoerr "$cmdname: waiting $TIMEOUT seconds for $HOST:$PORT"
else
echoerr "$cmdname: waiting for $HOST:$PORT without a timeout"
fi
start_ts=$(date +%s)
while :
do
if [[ $ISBUSY -eq 1 ]]; then
nc -z $HOST $PORT
result=$?
else
(echo > /dev/tcp/$HOST/$PORT) >/dev/null 2>&1
result=$?
fi
if [[ $result -eq 0 ]]; then
end_ts=$(date +%s)
echoerr "$cmdname: $HOST:$PORT is available after $((end_ts - start_ts)) seconds"
break
fi
sleep 1
done
return $result
}
wait_for_wrapper()
{
# In order to support SIGINT during timeout: http://unix.stackexchange.com/a/57692
if [[ $QUIET -eq 1 ]]; then
timeout $BUSYTIMEFLAG $TIMEOUT $0 --quiet --child --host=$HOST --port=$PORT --timeout=$TIMEOUT &
else
timeout $BUSYTIMEFLAG $TIMEOUT $0 --child --host=$HOST --port=$PORT --timeout=$TIMEOUT &
fi
PID=$!
trap "kill -INT -$PID" INT
wait $PID
RESULT=$?
if [[ $RESULT -ne 0 ]]; then
echoerr "$cmdname: timeout occurred after waiting $TIMEOUT seconds for $HOST:$PORT"
fi
return $RESULT
}
# process arguments
while [[ $# -gt 0 ]]
do
case "$1" in
*:* )
hostport=(${1//:/ })
HOST=${hostport[0]}
PORT=${hostport[1]}
shift 1
;;
--child)
CHILD=1
shift 1
;;
-q | --quiet)
QUIET=1
shift 1
;;
-s | --strict)
STRICT=1
shift 1
;;
-h)
HOST="$2"
if [[ $HOST == "" ]]; then break; fi
shift 2
;;
--host=*)
HOST="${1#*=}"
shift 1
;;
-p)
PORT="$2"
if [[ $PORT == "" ]]; then break; fi
shift 2
;;
--port=*)
PORT="${1#*=}"
shift 1
;;
-t)
TIMEOUT="$2"
if [[ $TIMEOUT == "" ]]; then break; fi
shift 2
;;
--timeout=*)
TIMEOUT="${1#*=}"
shift 1
;;
--)
shift
CLI=("$@")
break
;;
--help)
usage
;;
*)
echoerr "Unknown argument: $1"
usage
;;
esac
done
if [[ "$HOST" == "" || "$PORT" == "" ]]; then
echoerr "Error: you need to provide a host and port to test."
usage
fi
TIMEOUT=${TIMEOUT:-15}
STRICT=${STRICT:-0}
CHILD=${CHILD:-0}
QUIET=${QUIET:-0}
# check to see if timeout is from busybox?
# check to see if timeout is from busybox?
TIMEOUT_PATH=$(realpath $(which timeout))
if [[ $TIMEOUT_PATH =~ "busybox" ]]; then
ISBUSY=1
BUSYTIMEFLAG="-t"
else
ISBUSY=0
BUSYTIMEFLAG=""
fi
if [[ $CHILD -gt 0 ]]; then
wait_for
RESULT=$?
exit $RESULT
else
if [[ $TIMEOUT -gt 0 ]]; then
wait_for_wrapper
RESULT=$?
else
wait_for
RESULT=$?
fi
fi
if [[ $CLI != "" ]]; then
if [[ $RESULT -ne 0 && $STRICT -eq 1 ]]; then
echoerr "$cmdname: strict mode, refusing to execute subprocess"
exit $RESULT
fi
exec "${CLI[@]}"
else
exit $RESULT
fi

0
core/__init__.py Normal file
View File

16
core/admin.py Normal file
View File

@@ -0,0 +1,16 @@
from django.contrib import admin
from .models import User
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
search_fields = ("id", "email", "first_name", "last_name")
list_display = (
"id",
"first_name",
"last_name",
"is_active",
"email",
"date_joined",
)

5
core/apps.py Normal file
View File

@@ -0,0 +1,5 @@
from django.apps import AppConfig
class CoreConfig(AppConfig):
name = 'core'

29
core/managers.py Normal file
View File

@@ -0,0 +1,29 @@
from django.contrib.auth.base_user import BaseUserManager
class UserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, email, password, **extra_fields):
"""
Creates and saves a User with the given email and password.
"""
if not email:
raise ValueError("The given email must be set")
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
extra_fields.setdefault("is_superuser", False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault("is_superuser", True)
if extra_fields.get("is_superuser") is not True:
raise ValueError("Superuser must have is_superuser=True.")
return self._create_user(email, password, **extra_fields)

View File

@@ -0,0 +1,42 @@
# Generated by Django 3.1.3 on 2020-11-05 00:51
import core.managers
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('email', models.EmailField(max_length=254, unique=True, verbose_name='E-mail')),
('first_name', models.CharField(blank=True, max_length=30, verbose_name='First name')),
('last_name', models.CharField(blank=True, max_length=30, verbose_name='Last name')),
('date_joined', models.DateTimeField(auto_now_add=True, verbose_name='date joined')),
('is_active', models.BooleanField(default=True, verbose_name='User active?')),
('is_staff', models.BooleanField(default=False, verbose_name='Staff?')),
('is_superuser', models.BooleanField(default=False, verbose_name='Superuser?')),
('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')),
('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')),
],
options={
'verbose_name': 'User',
'verbose_name_plural': 'Users',
'db_table': 'users',
'ordering': ['first_name', 'last_name'],
},
managers=[
('objects', core.managers.UserManager()),
],
),
]

View File

41
core/models.py Normal file
View File

@@ -0,0 +1,41 @@
from django.db import models
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from .managers import UserManager
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField("E-mail", unique=True)
first_name = models.CharField("First name", max_length=30, blank=True)
last_name = models.CharField("Last name", max_length=30, blank=True)
date_joined = models.DateTimeField("date joined", auto_now_add=True)
is_active = models.BooleanField("User active?", default=True)
is_staff = models.BooleanField("Staff?", default=False)
is_superuser = models.BooleanField("Superuser?", default=False)
objects = UserManager()
USERNAME_FIELD = "email"
class Meta:
ordering = ["first_name", "last_name"]
verbose_name = "User"
verbose_name_plural = "Users"
db_table = "users"
def get_full_name(self):
"""
Returns the first_name plus the last_name, with a space in between.
"""
full_name = f"{self.first_name} {self.last_name}"
return full_name.strip()
def get_short_name(self):
"""
Returns the short name for the user.
"""
return self.first_name or "Unamed"

3
core/tests.py Normal file
View File

@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

3
core/views.py Normal file
View File

@@ -0,0 +1,3 @@
from django.shortcuts import render
# Create your views here.

29
docker-compose.yml Normal file
View File

@@ -0,0 +1,29 @@
version: "3"
services:
app:
build: .
container_name: mines-app
volumes:
- ./commands:/commands
- .:/app
command: /app/commands/run.sh
environment:
- DB_USER=root
- DB_PASS=minesweeper
- DB_HOST=db
- DB_NAME=minesweeper
- DB_PORT=3306
- DEBUG=1
ports:
- 8000:8000
links:
- db
db:
image: mysql:8
container_name: mines-db
command: --default-authentication-plugin=mysql_native_password
ports:
- 3306:3306
environment:
- MYSQL_ROOT_PASSWORD=minesweeper
- MYSQL_DATABASE=minesweeper

22
manage.py Executable file
View File

@@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.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()

36
requirements.txt Normal file
View File

@@ -0,0 +1,36 @@
#
# This file is autogenerated by pip-compile
# To update, run:
#
# pip-compile requirements.txt
#
appdirs==1.4.4 # via -r requirements.txt, black
asgiref==3.3.0 # via -r requirements.txt, django
black==20.8b1 # via -r requirements.txt
click==7.1.2 # via -r requirements.txt, black
django-dbml==0.3.5 # via -r requirements.txt
django-mysql==3.9.0 # via -r requirements.txt
django==3.1.3 # via -r requirements.txt, django-mysql, djangorestframework
djangorestframework==3.12.1 # via -r requirements.txt
gevent==20.9.0 # via -r requirements.txt
greenlet==0.4.17 # via -r requirements.txt, gevent
mypy-extensions==0.4.3 # via -r requirements.txt, black
mysqlclient==2.0.1 # via -r requirements.txt
pathspec==0.8.0 # via -r requirements.txt, black
pendulum==2.1.2 # via -r requirements.txt
python-dateutil==2.8.1 # via -r requirements.txt, pendulum
pytz==2020.4 # via -r requirements.txt, django
pytzdata==2020.1 # via -r requirements.txt, pendulum
regex==2020.10.28 # via -r requirements.txt, black
six==1.15.0 # via -r requirements.txt, python-dateutil
sqlparse==0.4.1 # via -r requirements.txt, django
toml==0.10.2 # via -r requirements.txt, black
typed-ast==1.4.1 # via -r requirements.txt, black
typing-extensions==3.7.4.3 # via -r requirements.txt, black
uwsgi==2.0.19.1 # via -r requirements.txt
zope.event==4.5.0 # via -r requirements.txt, gevent
zope.interface==5.1.2 # via -r requirements.txt, gevent
flake8
# The following packages are considered to be unsafe in a requirements file:
# setuptools