$ docker-compose rum --rm web python manage.py migrate example_app zero Creating example-app_web_run ... done Operations to perform: Unapply all migrations: example_app Running migrations: Rendering model states... DONE Unapplying example_app.0001_initial... OK
$ docker-compose run --rm web python manage.py migrate example_app Creating example-app_web_run ... done Operations to perform: Apply all migrations: example_app Running migrations: Applying example_app.0001_initial... OK
$ docker-compose run --rm web python manage.py dbshell Creating example-app_web_run ... done Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A
Welcome to the MariaDB monitor. Commands end with ; or \g. Your MySQL connection id is 30 Server version: 5.7.36 MySQL Community Server (GPL)
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend
UserModel = get_user_model()
class EmailAuthenticationBackend(ModelBackend): def authenticate(self, request, email=None, password=None, **credentials): try: user = UserModel.objects.get(email=email) except UserModel.DoesNotExist: return None else: if user.check_password(password) and self.user_can_authenticate(user): return user
from django import forms from django.contrib.auth import authenticate, get_user_model from django.utils.text import capfirst from django.utils.translation import gettext_lazy as _
self.email_field = UserModel._meta.get_field("email") if self.fields["email"].label is None: self.fields["email"].label = capfirst(self.email_field.verbose_name)
if email is not None and password: self.user_cache = authenticate(self.request, email=email, password=password) if self.user_cache is None: raise forms.ValidationError( self.error_messages['invalid_login'], code='invalid_login', params={"email": self.email_field.verbose_name} ) else: self.confirm_login_allowed(self.user_cache)
return self.cleaned_data
def confirm_login_allowed(self, user): if not user.is_active: raise forms.ValidationError(self.error_messages["inactive"], code='inactive')
def get_user_id(self): if self.user_cache: return self.user_cache.id return None
$ docker-compose run --rm web poetry add django-bootstrap5 Creating example_web_run ... done Skipping virtualenv creation, as specified in config file. Using version ^21.3 for django-bootstrap5
$ docker-compose run --rm web python manage.py shell_plus Creating example_web_run ... done # Shell Plus Model Imports from django.contrib.admin.models import LogEntry from django.contrib.auth.models import Group, Permission, User from django.contrib.contenttypes.models import ContentType from django.contrib.sessions.models import Session # Shell Plus Django Imports from django.core.cache import cache from django.conf import settings from django.contrib.auth import get_user_model from django.db import transaction from django.db.models import Avg, Case, Count, F, Max, Min, Prefetch, Q, Sum, When from django.utils import timezone from django.urls import reverse from django.db.models import Exists, OuterRef, Subquery >>> settings.LOGIN_REDIRECT_URL '/accounts/profile/'
Many configuration options can be passed as flags to mysqld. This will give you the flexibility to customize the container without needing a cnf file. For example, if you want to change the default encoding and collation for all tables to use UTF-8 (utf8mb4) just run the following:
$ docker-compose run --rm web python manage.py dbshell Creating djangosnippets_web_run ... done Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A
Welcome to the MariaDB monitor. Commands end with ; or \g. Your MySQL connection id is 24 Server version: 5.7.36 MySQL Community Server (GPL)
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MySQL [djangosnippets]>
文字コードを確認します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
MySQL [djangosnippets]> show variables like '%char%'; +--------------------------+----------------------------+ | Variable_name | Value | +--------------------------+----------------------------+ | character_set_client | utf8mb4 | | character_set_connection | utf8mb4 | | character_set_database | utf8mb4 | | character_set_filesystem | binary | | character_set_results | utf8mb4 | | character_set_server | utf8mb4 | | character_set_system | utf8 | | character_sets_dir | /usr/share/mysql/charsets/ | +--------------------------+----------------------------+ 8 rows in set (0.011 sec)
$ docker-compose run --rm web python manage.py test Creating test database for alias 'default'... Got an error creating the test database: (1044, "Access denied for user 'django'@'%' to database 'test_example'") ERROR: 2
テストデータベースのデフォルトの名前は、 DATABASES 設定内の各 NAME の値の前に test_ を付けたものになります。設定の DATABASES 内の TEST ディクショナリには、テストデータベースに対するいろいろな設定を書くことができます。例えば、別のデータベース名を指定したければ、 TEST ディクショナリの NAME に、 DATABASES の中から好きなデータベースを選んで指定することができます。
$ docker-compose run --rm web python manage.py dbshell MySQL[example]> show databases; +---------------------+ | Database | +---------------------+ | information_schema | | example | +---------------------+ 2 rows in set (0.001 sec)
MySQL[example]> show grants for 'django'@'%'; +-----------------------------------------------------+ | Grants for django@% | +-----------------------------------------------------+ | GRANT USAGE ON *.* TO 'django'@'%' | | GRANT ALL PRIVILEGES ON `example`.* TO 'django'@'%' | +-----------------------------------------------------+ 2 rows in set (0.001 sec)
GRANT USAGEは見慣れない権限なのですが、権限を与えないということのようです。全ての権限をなくしてからexampleデータベースにのみ全権限を与えているということのようです。
これでは現状がわからないのでrootで接続してみます。
webコンテナにログインしてからmysqlクライアントで接続します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
$ docker-compose run --rm web /bin/bash Creating example_web_run ... done root@6e114e4f73b3:/code# root@6e114e4f73b3:/code# mysql -u root -p -h db Enter password: Welcome to the MariaDB monitor. Commands end with ; or \g. Your MySQL connection id is 8 Server version: 5.7.36 MySQL Community Server (GPL)
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MySQL [(none)]> show databases; +--------------------------+ | Database | +--------------------------+ | example | | information_schema | | mysql | | performance_schema | | sys | | test_example | +--------------------------+ 6 rows in set (0.001 sec)
権限も付与します。
1 2 3 4 5 6 7 8 9 10 11 12 13
MySQL [(none)]> grant all privileges on `test_example`.* to 'django'@'%'; Query OK, 0 rows affected (0.003 sec)
MySQL [(none)]> MySQL [(none)]> show grants for 'django'@'%'; +----------------------------------------------------------------------+ | Grants for django@% | +----------------------------------------------------------------------+ | GRANT USAGE ON *.* TO 'django'@'%' | | GRANT ALL PRIVILEGES ON `example`.* TO 'django'@'%' | | GRANT ALL PRIVILEGES ON `test_example`.* TO 'django'@'%' | +----------------------------------------------------------------------+ 3 rows in set (0.001 sec)
権限の付与ができました。
テスト再実行
ではテストを再実行してみます。
1 2 3 4 5 6 7 8 9 10 11 12 13
$ docker-compose run --rm web python manage.py test Creating example_web_run ... done Creating test database for alias 'default'... Got an error creating the test database: (1007, "Can't create database 'test_example'; database exists") Type 'yes' if you would like to try deleting the test database 'test_example', or 'no' to cancel: yes Destroying old test database for alias 'default'... System check identified no issues (0 silenced). .. ---------------------------------------------------------------------- Ran 2 tests in 0.006s
OK Destroying test database for alias 'default'...
$ docker-compose run --rm web python manage.py test Creating example_web_run ... done Creating test database for alias 'default'... System check identified no issues (0 silenced). .. ---------------------------------------------------------------------- Ran 2 tests in 0.010s
OK Destroying test database for alias 'default'...
Do note that none of the variables below will have any effect if you start the container with a data directory that already contains a database: any pre-existing database will always be left untouched on container startup.
$ docker-compose run --rm web python -m pipenv sync --system Creating a virtualenv for this project... Pipfile: /code/Pipfile Using /usr/local/bin/python3 (3.10.0) to create virtualenv... ⠦ Creating virtual environment...created virtual environment CPython3.10.0.final.0-64 in 391ms creator CPython3Posix(dest=/root/.local/share/virtualenvs/code-_Py8Si6I, clear=False, no_vcs_ignore=False, global=False) seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/root/.local/share/virtualenv) added seed packages: pip==21.3.1, setuptools==58.3.0, wheel==0.37.0 activators BashActivator,CShellActivator,FishActivator,NushellActivator,PowerShellActivator,PythonActivator
✔ Successfully created virtual environment! Virtualenv location: /root/.local/share/virtualenvs/code-_Py8Si6I Installing dependencies from Pipfile.lock (d9bd7e)... 🐍 ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 15/15 — 00:00:02 All dependencies are now up-to-date!
This command will guide you through creating your pyproject.toml config.
Package name [code]: Version [0.1.0]: Description []: Author [None, n to skip]: expected string or bytes-like object Author [None, n to skip]: n License []: Compatible Python versions [^3.10]:
Would you like to define your main dependencies interactively? (yes/no) [yes] You can specify a package in the following forms: - A single name (requests) - A name and a constraint (requests@^2.23.0) - A git url (git+https://github.com/python-poetry/poetry.git) - A git url with a revision (git+https://github.com/python-poetry/poetry.git#develop) - A file path (../my-package/my-package.whl) - A directory (../my-package/) - A url (https://example.com/packages/my-package-0.1.0.tar.gz)
Search for package to add (or leave blank to continue):
Would you like to define your development dependencies interactively? (yes/no) [yes] Search for package to add (or leave blank to continue):
Generated file
[tool.poetry] name = "code" version = "0.1.0" description = "" authors = ["Your Name <you@example.com>"]
$ docker-compose run --rm web poetry add boto3 Creating virtualenv code-MATOk_fk-py3.10 in /root/.cache/pypoetry/virtualenvs Using version ^1.20.1 for boto3