Closed34

poetry & django & pysen の環境づくり

tkttkt
# poetry init

This command will guide you through creating your pyproject.toml config.

Package name [workspace]:  django_poetry_pysen
Version [0.1.0]:  
Description []:  
Author [None, n to skip]:  tktcorporation
License []:  MIT
Compatible Python versions [^3.9]:  

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 = "django_poetry_pysen"
version = "0.1.0"
description = ""
authors = ["tktcorporation"]
license = "MIT"

[tool.poetry.dependencies]
python = "^3.9"

[tool.poetry.dev-dependencies]

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"


Do you confirm generation? (yes/no) [yes]

pyproject.yml ができた

tkttkt
# poetry add django
Skipping virtualenv creation, as specified in config file.
Using version ^3.2 for Django

Updating dependencies
Resolving dependencies... (1.2s)

Writing lock file

Package operations: 4 installs, 0 updates, 0 removals

  • Installing asgiref (3.3.2)
  • Installing pytz (2021.1)
  • Installing sqlparse (0.4.1)
  • Installing django (3.2)

django入れる

tkttkt
django-admin startproject django_pysen .

django 用の諸々を作成

tkttkt
# poetry run ./manage.py
Skipping virtualenv creation, as specified in config file.

Type 'manage.py help <subcommand>' for help on a specific subcommand.

Available subcommands:

[auth]
    changepassword
    createsuperuser

[contenttypes]
    remove_stale_contenttypes

[django]
    check
    compilemessages
    createcachetable
    dbshell
    diffsettings
    dumpdata
    flush
    inspectdb
    loaddata
    makemessages
    makemigrations
    migrate
    sendtestemail
    shell
    showmigrations
    sqlflush
    sqlmigrate
    sqlsequencereset
    squashmigrations
    startapp
    startproject
    test
    testserver

[sessions]
    clearsessions

[staticfiles]
    collectstatic
    findstatic
    runserver

見えるようになった

tkttkt
# poetry run ./manage.py runserver 0.0.0.0:8000 --nostatic
Skipping virtualenv creation, as specified in config file.
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
April 06, 2021 - 14:45:50
Django version 3.2, using settings 'django_pysen.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.

migrate しろって言われた
でも見れた

tkttkt
# poetry run ./manage.py migrate
Skipping virtualenv creation, as specified in config file.
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying sessions.0001_initial... OK

migrate もできた
最初から migrate 用のファイルが用意されてるのか

tkttkt
# poetry add -D pysen
Skipping virtualenv creation, as specified in config file.
Using version ^0.9.1 for pysen

Updating dependencies
Resolving dependencies... (2.9s)

Writing lock file

Package operations: 7 installs, 0 updates, 0 removals

  • Installing smmap (4.0.0)
  • Installing gitdb (4.0.7)
  • Installing colorlog (4.8.0)
  • Installing dacite (1.6.0)
  • Installing gitpython (3.1.14)
  • Installing unidiff (0.6.0)
  • Installing pysen (0.9.1)
tkttkt
# pysen lint
[pysen.git_utils] git is not available
Consider specifying 'version' under [tool.pysen] section in your pyproject.toml to check compliance against the version of the installed pysen. (File: /workspace/pyproject.toml)
error occured while loading /workspace/pyproject.toml: Expected isort to be installed but pkg_resources could not find it.
Hint: Did you install "isort" in the same Python environment as pysen?

入れてからいろいろしないといけないらしい

tkttkt
# poetry add -D pysen -E lint
Skipping virtualenv creation, as specified in config file.
Using version ^0.9.1 for pysen

Updating dependencies
Resolving dependencies... (12.6s)

Writing lock file

Package operations: 16 installs, 0 updates, 0 removals

  • Installing mccabe (0.6.1)
  • Installing pycodestyle (2.7.0)
  • Installing pyflakes (2.3.1)
  • Installing attrs (20.3.0)
  • Installing click (7.1.2)
  • Installing flake8 (3.9.0)
  • Installing mypy-extensions (0.4.3)
  • Installing pathspec (0.8.1)
  • Installing regex (2021.4.4)
  • Installing toml (0.10.2)
  • Installing typed-ast (1.4.2)
  • Installing typing-extensions (3.7.4.3)
  • Installing black (20.8b1)
  • Installing flake8-bugbear (21.4.3)
  • Installing isort (5.1.4)
  • Installing mypy (0.790)

違うコマンドで入れ直し

tkttkt
pyproject.toml
[tool.pysen]
version = "0.9"

[tool.pysen.lint]
enable_black = true
enable_flake8 = true
enable_isort = true
enable_mypy = true
mypy_preset = "strict"
line_length = 88
py_version = "py37"
[[tool.pysen.lint.mypy_targets]]
  paths = ["."]

これ書けって書いてたので書いた

tkttkt
# pysen lint
[pysen.git_utils] git is not available

怒られたので git を入れる

tkttkt
# pysen run lint
Running commands concurrently...
... concurrent execution done
Running: black
Checking 0 files
Running: flake8
Checking 0 files
Running: isort
Checking 0 files
Running: mypy
[1/1] Checking 1 entries
/workspace/manage.py:7: error: Function is missing a return type annotation 
[no-untyped-def]
    def main():
    ^
/workspace/manage.py:7: note: Use "-> None" if function does not return a value
/workspace/manage.py:22: error: Call to untyped function "main" in typed
context  [no-untyped-call]
        main()
        ^
/workspace/django_pysen/settings.py:28: error: Need type annotation for
'ALLOWED_HOSTS' (hint: "ALLOWED_HOSTS: List[<type>] = ...")  [var-annotated]
    ALLOWED_HOSTS = []
    ^
Found 3 errors in 2 files (checked 6 source files)

 ** execution summary **
isort .......... OK (0.14 sec)
black .......... OK (0.15 sec)
flake8 .......... OK (0.16 sec)
mypy .......... Failed (4.39 sec)

lint finished with error(s)
Errored:
 - mypy
tkttkt
# pysen run -h
usage: pysen run [-h] [--error-format {gnu}] [--no-parallel] {lint,format} [{lint,format} ...]

positional arguments:
  {lint,format}         target to run

optional arguments:
  -h, --help            show this help message and exit
  --error-format {gnu}
  --no-parallel
tkttkt

vscode から使いたいときとか、ファイル単位でかけたいときはどうするんだろうか

tkttkt

vscode 拡張入れたけどなんかうまく動いてくれない

tkttkt

python 公式の 拡張入れたらそっちが優先されて動かないパターンかな

tkttkt

一度消してみる

tkttkt

python 標準の extension を消して reload したら動くようになった

tkttkt
# pysen run lint
Running commands concurrently...
... concurrent execution done
Running: black
Checking 6 files
--- /workspace/django_pysen/asgi.py     2021-04-06 14:38:23.597313 +0000
+++ /workspace/django_pysen/asgi.py     2021-04-06 15:47:26.485009 +0000
@@ -9,8 +9,8 @@
 
 import os
 
 from django.core.asgi import get_asgi_application
 
-os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_pysen.settings')
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_pysen.settings")
 
 application = get_asgi_application()
would reformat /workspace/django_pysen/asgi.py
--- /workspace/django_pysen/wsgi.py     2021-04-06 14:38:23.597313 +0000
+++ /workspace/django_pysen/wsgi.py     2021-04-06 15:47:26.489396 +0000
@@ -9,8 +9,8 @@
 
 import os
 
 from django.core.wsgi import get_wsgi_application
 
-os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_pysen.settings')
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_pysen.settings")
 
 application = get_wsgi_application()
would reformat /workspace/django_pysen/wsgi.py
--- /workspace/django_pysen/urls.py     2021-04-06 14:38:23.597313 +0000
+++ /workspace/django_pysen/urls.py     2021-04-06 15:47:26.492871 +0000
@@ -15,7 +15,7 @@
 """
 from django.contrib import admin
 from django.urls import path
 
 urlpatterns = [
-    path('admin/', admin.site.urls),
+    path("admin/", admin.site.urls),
 ]
would reformat /workspace/django_pysen/urls.py
--- /workspace/manage.py        2021-04-06 14:38:23.593313 +0000
+++ /workspace/manage.py        2021-04-06 15:47:26.498121 +0000
@@ -4,11 +4,11 @@
 import sys
 
 
 def main():
     """Run administrative tasks."""
-    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_pysen.settings')
+    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_pysen.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 "
@@ -16,7 +16,7 @@
             "forget to activate a virtual environment?"
         ) from exc
     execute_from_command_line(sys.argv)
 
 
-if __name__ == '__main__':
+if __name__ == "__main__":
     main()
would reformat /workspace/manage.py
Oh no! 💥 💔 💥
4 files would be reformatted, 2 files would be left unchanged.
Running: flake8
Checking 6 files
Running: isort
Checking 6 files
Running: mypy
[1/1] Checking 1 entries
/workspace/manage.py:7: error: Function is missing a return type annotation 
[no-untyped-def]
    def main():
    ^
/workspace/manage.py:7: note: Use "-> None" if function does not return a value
/workspace/manage.py:22: error: Call to untyped function "main" in typed
context  [no-untyped-call]
        main()
        ^
/workspace/django_pysen/settings.py:28: error: Need type annotation for
'ALLOWED_HOSTS' (hint: "ALLOWED_HOSTS: List[<type>] = ...")  [var-annotated]
    ALLOWED_HOSTS = []
    ^
Found 3 errors in 2 files (checked 6 source files)

 ** execution summary **
isort .......... OK (0.49 sec)
black .......... Failed (0.46 sec)
flake8 .......... OK (0.47 sec)
mypy .......... Failed (0.66 sec)

lint finished with error(s)
Errored:
 - black
 - mypy
# pysen run_files lint django_pysen
Running commands concurrently...
... concurrent execution done
Running: black
Skipping /workspace/django_pysen for black
Running: flake8
Skipping /workspace/django_pysen for flake8
Running: isort
Skipping /workspace/django_pysen for isort
Running: mypy
/workspace/django_pysen/settings.py:28: error: Need type annotation for
'ALLOWED_HOSTS' (hint: "ALLOWED_HOSTS: List[<type>] = ...")  [var-annotated]
    ALLOWED_HOSTS = []
    ^
Found 1 error in 1 file (checked 5 source files)

 ** execution summary **
isort .......... OK (0.02 sec)
black .......... OK (0.03 sec)
flake8 .......... OK (0.05 sec)
mypy .......... Failed (0.64 sec)

lint finished with error(s)
Errored:
 - mypy

run_files でファイル、ディレクトリ指定で実行できるみたい

tkttkt
# pysen run format
Running commands
Running: isort
Checking 6 files
Running: black
Checking 6 files
reformatted /workspace/django_pysen/asgi.py
reformatted /workspace/django_pysen/urls.py
reformatted /workspace/django_pysen/wsgi.py
All done! ✨ 🍰 ✨
3 files reformatted, 3 files left unchanged.

 ** execution summary **
isort .......... OK (0.43 sec)
black .......... OK (0.37 sec)

いい感じに直してくれた

tkttkt

mypy で引っかかってたところは手動で直した

このスクラップは2021/04/07にクローズされました