1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

#プログラミング 学習では決して真面目に写経してはいけない ( #python #django の例 )

Last updated at Posted at 2019-05-06
  • 特に中級者は。
  • 「写経にかけるコスト」は戦略的に見計らおう。

たとえば

これ。

シェルを立ち上げて一行一行書けという。

image

やってられるか!!

これが死ぬほどハードルになって前に進めなかった。

解決策

  • プログラム全体をスクリプトに書いて、シェルからファイルを直接実行することで、かなりやりやすくなった。
  • ファイル全体を眺めていると見通しが良くなり、少しいじって動作を変えることなどもしやすくなった。
./manage.py shell < ./snippets/codes/serialize.py
# https://www.django-rest-framework.org/tutorial/1-serialization/

from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser

snippet = Snippet(code='foo = "bar"\n')
snippet.save()

snippet = Snippet(code='print("hello, world")\n')
snippet.save()

serializer = SnippetSerializer(snippet)
print(serializer.data)
# {'id': 7, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}


content = JSONRenderer().render(serializer.data)
print(content)
# b'{"id": 2, "title": "", "code": "print(\\"hello, world\\")\\n", "linenos": false, "language": "python", "style": "friendly"}'

import io

stream = io.BytesIO(content)
data = JSONParser().parse(stream)

serializer = SnippetSerializer(data=data)

serializer.is_valid()
# True

serializer.validated_data
# OrderedDict([('title', ''), ('code', 'print("hello, world")\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])

serializer.save()
# <Snippet: Snippet object>

serializer = SnippetSerializer(Snippet.objects.all(), many=True)
serializer.data
# [OrderedDict([('id', 1), ('title', ''), ('code', 'foo = "bar"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 2), ('title', ''), ('code', 'print("hello, world")\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 3), ('title', ''), ('code', 'print("hello, world")'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])]


教訓

  • チュートリアルが本当にやりやすく作られているとは限らない
  • チュートリアルの指示通りに進めるのが馬鹿らしいことだってある
  • チュートリアルはあくまで素材なので料理の腕があるなら、自分で調理しよう

Original by Github issue

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?