Slide 1

Slide 1 text

INTRODUCTION TO DEVELOP DJANGO PLUGIN PYCON JP 2016

Slide 2

Slide 2 text

@GIGINET

Slide 3

Slide 3 text

SELF INTRODUCTION ▸ Mobile / Rails Engineer @ Cookpad ▸ Hobby Python Programmer ▸ I’m not a professional

Slide 4

Slide 4 text

SELF INTRODUCTION ▸ Mobile / Rails Engineer @ Cookpad ▸ Hobby Python Programmer ▸ I’m not a professional

Slide 5

Slide 5 text

giginet/django-debug-toolbar-vcs-info

Slide 6

Slide 6 text

giginet/django-slack-invitation

Slide 7

Slide 7 text

giginet/django-generic-tagging

Slide 8

Slide 8 text

lambdalisue/django-permission

Slide 9

Slide 9 text

from django.db import models from django.contrib.auth.models import User class Article(models.Model): title = models.CharField('title', max_length=120) body = models.TextField('body') author = models.ForeignKey(User) collaborators = models.ManyToManyField(User) # apply AuthorPermissionLogic and CollaboratorsPermissionLogic from permission import add_permission_logic from permission.logics import AuthorPermissionLogic from permission.logics import CollaboratorsPermissionLogic add_permission_logic(Article, AuthorPermissionLogic()) add_permission_logic(Article, CollaboratorsPermissionLogic( field_name='collaborators', any_permission=False, change_permission=True, delete_permission=False, ))

Slide 10

Slide 10 text

lambdalisue/django-inspectional- registration

Slide 11

Slide 11 text

rosarior/awesome-django

Slide 12

Slide 12 text

GOAL GOAL ▸ Learn how to develop Python library ▸ especially Django plugin ▸ Develop more useful plugins ▸ Easy to use ▸ Easy to maintain

Slide 13

Slide 13 text

INTRODUCTION

Slide 14

Slide 14 text

TEXT WHAT'S DJANGO ▸ Web Application Framework in Python

Slide 15

Slide 15 text

Django 1.7 2014/9/2 Django 1.8 2015/4/1 Django 1.9 2015/12/1 Django 1.10 2016/8/1 Django 1.11 2017/4

Slide 16

Slide 16 text

No content

Slide 17

Slide 17 text

Django 1.7 2.7, 3.2, 3.3, 3.4 Django 1.8 2.7, 3.2, 3.3, 3.4, 3.5 Django 1.9 2.7, 3.4, 3.5 Django 1.10 2.7, 3.4, 3.5 Django 1.11 2.7, 3.4, 3.5

Slide 18

Slide 18 text

TEXT LANGUAGE ▸ Unfortunately, many Django applications still run on Python 2.x ▸ ☠Write in Python 2, use 2to3 ▸ ✨Write in Python 3 with compatibility with 2

Slide 19

Slide 19 text

HOW TO DEVELOP PLUGIN

Slide 20

Slide 20 text

WORKFLOW WORKFLOW 1. Implement 2. Write test 3. Setup test environment 4. Consider compatibility 5. Release

Slide 21

Slide 21 text

FILE HIERARCHY

Slide 22

Slide 22 text

FILE HIERARCHY Implementation

Slide 23

Slide 23 text

FILE HIERARCHY Testing

Slide 24

Slide 24 text

FILE HIERARCHY Documentation

Slide 25

Slide 25 text

FILE HIERARCHY Deploy

Slide 26

Slide 26 text

your_plugin __init__.py models.py, views.py, templates, etc… tests __init__.py test_foobar.py ….

Slide 27

Slide 27 text

FILE HIERARCHY Implementation

Slide 28

Slide 28 text

your_plugin __init__.py models.py, views.py, templates, etc… tests __init__.py test_foobar.py ….

Slide 29

Slide 29 text

HOW TO RETAIN COMPATIBILITY ▸ Use back-porting libraries ▸ __future__ ▸ cf. enum34, mock, pathlib, etc… ▸ http://python-future.org/ standard_library_imports.html

Slide 30

Slide 30 text

HOW TO RETAIN COMPATIBILITY ▸ six ▸ Utilities collection to compatible with 2 and 3 ▸ https://pythonhosted.org/six/

Slide 31

Slide 31 text

HOW TO RETAIN COMPATIBILITY from six import python_2_unicode_compatible @python_2_unicode_compatible class Cat(object): name = 'Tama' def __str__(self): return self

Slide 32

Slide 32 text

try: # Python 3 from urllib.parse import urljoin except ImportError: # Python 2 from urlparse import urljoin compat.py

Slide 33

Slide 33 text

TESTING

Slide 34

Slide 34 text

WHY TESTING ▸ Easy to check behavior ▸ Easy to maintain ▸ Follow dependencies(major version up of Django) ▸ Encourage contribution

Slide 35

Slide 35 text

FILE HIERARCHY Testing

Slide 36

Slide 36 text

import os import sys import django from django.conf import settings from django.test.utils import get_runner if __name__ == "__main__": os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' django.setup() TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_runner.run_tests([“your_plugin”]) sys.exit(bool(failures)) https://docs.djangoproject.com/en/1.10/topics/testing/advanced/ runtests.py

Slide 37

Slide 37 text

INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'your_plugin', ] tests/settings.py

Slide 38

Slide 38 text

if django.VERSION >= (1, 10): TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'OPTIONS': { 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ], 'debug': DEBUG, }, } ] else: TEMPLATE_DEBUG = DEBUG TEMPLATE_DIRS = ( ) TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', )

Slide 39

Slide 39 text

from django.test import TestCase class CalculatorTestCase(TestCase): def test_add(self): self.assertEqual(1 + 1, 2) your_plugin/tests/test_calculator.py

Slide 40

Slide 40 text

$ python runtests.py Creating test database for alias 'default'... . --------------------------------------------------- ------------------- Ran 1 test in 0.001s OK Destroying test database for alias 'default'...

Slide 41

Slide 41 text

https://tox.readthedocs.io/en/latest/ 442742 442742 tox

Slide 42

Slide 42 text

[tox] envlist = py33-django{17,18}, {py27,py34}-django{17,18,19,110} py35-django{18,19,110} [testenv] basepython = py27: python2.7 py33: python3.3 py34: python3.4 py35: python3.5 deps= django17: django>=1.7,<1.8 django18: django>=1.8,<1.9 django19: django>=1.9,<1.10 django110: django>=1.10,<1.11 tox.ini

Slide 43

Slide 43 text

$ tox py33-django17: commands succeeded py33-django18: commands succeeded py27-django17: commands succeeded py27-django18: commands succeeded py27-django19: commands succeeded py27-django110: commands succeeded py34-django17: commands succeeded py34-django18: commands succeeded py34-django19: commands succeeded py34-django110: commands succeeded py35-django18: commands succeeded py35-django19: commands succeeded py35-django110: commands succeeded congratulations :)

Slide 44

Slide 44 text

$ tox -e py35-django110

Slide 45

Slide 45 text

USE DJANGO TESTING UTILITIES ▸ There are useful testing utilities in Django ▸ django.test.utils ▸ https://docs.djangoproject.com/en/1.10/_modules/ django/test/utils/

Slide 46

Slide 46 text

from django.test import TestCase, override_settings from django.conf import settings class APIClientTest(TestCase): @override_settings(API_TOKEN='token') def test_override_settings(self): self.assetEqual(settings['API_TOKEN'], 'token')

Slide 47

Slide 47 text

import time from django.test.utils import freeze_time def test_freeze_time(self): frozen_time = time.time() with freeze_time(frozen_time): self.assertEqual(time.time(), frozen_time)

Slide 48

Slide 48 text

from unittest import TestCase from .compat import Mock, patch class UserClientTest(TestCase): def test_request(self): response = Mock() response.json.side_effect = lambda: {'name': 'giginet'} response.status_code = 200 client = APIClient() with patch('requests.get', return_value=response) as get: user = client.users(name='giginet') get.assert_called_with('https://example.com/api/users', params={'name': 'giginet'})

Slide 49

Slide 49 text

try: from unittest.mock import patch, Mock except ImportError: from mock import patch, Mock

Slide 50

Slide 50 text

from django.db import models class TestArticle(models.Model): title = models.CharField('Title', max_length=255) class Meta: app_label = 'your_plugin' your_plugin/tests/models.py

Slide 51

Slide 51 text

INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'your_plugin', 'your_plugin.tests' ] tests/settings.py

Slide 52

Slide 52 text

class UserFactory(factory.Factory): class Meta: model = models.User first_name = 'John' last_name = 'Doe' email = factory.Sequence(lambda n: 'person{0}@example.com'.format(n)) >>> UserFactory().email '[email protected]' >>> UserFactory().email '[email protected]' FactoryBoy/factory_boy

Slide 53

Slide 53 text

CONTINUOUS INTEGRATION

Slide 54

Slide 54 text

No content

Slide 55

Slide 55 text

sudo: false language: python python: - 2.7 - 3.3 - 3.4 - 3.5 install: - pip install tox tox-travis - pip install coverage coveralls script: - tox after_success: - coverage report - coveralls .travis.yml

Slide 56

Slide 56 text

ryanhiebert/tox-travis

Slide 57

Slide 57 text

sudo: false language: python python: - 2.7 - 3.3 - 3.4 - 3.5 install: - pip install tox tox-travis - pip install coverage coveralls script: - tox after_success: - coverage report - coveralls .travis.yml

Slide 58

Slide 58 text

coveralls.io

Slide 59

Slide 59 text

No content

Slide 60

Slide 60 text

sudo: false language: python python: - 2.7 - 3.3 - 3.4 - 3.5 install: - pip install tox tox-travis - pip install coverage coveralls script: - tox after_success: - coverage report - coveralls .travis.yml

Slide 61

Slide 61 text

USEFUL TOOLS ▸ requires.io ▸ scrutinizer ▸ landscape.io

Slide 62

Slide 62 text

requires.io

Slide 63

Slide 63 text

scrutinizer

Slide 64

Slide 64 text

landscape.io

Slide 65

Slide 65 text

DOCUMENTATION

Slide 66

Slide 66 text

No content

Slide 67

Slide 67 text

https://docs.readthedocs.io/en/latest/getting_started.html $ pip install sphinx sphinx- autobuild $ mkdir docs $ cd docs $ sphinx-quickstart $ make html

Slide 68

Slide 68 text

https://pythonhosted.org/an_example_pypi_project/sphinx.html def public_fn_with_sphinxy_docstring(name, state=None): """This function does something. :param name: The name to use. :type name: str. :param state: Current state to be in. :type state: bool. :returns: int -- the return code. :raises: AttributeError, KeyError """ return 0

Slide 69

Slide 69 text

No content

Slide 70

Slide 70 text

https://pythonhosted.org/an_example_pypi_project/sphinx.html def public_fn_with_googley_docstring(name, state=None): """This function does something. Args: name (str): The name to use. Kwargs: state (bool): Current state to be in. Returns: int. The return code:: 0 -- Success! 1 -- No good. 2 -- Try again. Raises: AttributeError, KeyError A really great idea. A way you might use me is >>> print public_fn_with_googley_docstring(name='foo', state=None)

Slide 71

Slide 71 text

readthedocs

Slide 72

Slide 72 text

DEPLOY

Slide 73

Slide 73 text

TEXT ▸ MANIFEST.in ▸ LICENSE.rst ▸ README.rst ▸ setup.py

Slide 74

Slide 74 text

include README.rst include LICENSE.rst include requirements.txt include requirements-test.txt MANIFEST.IN

Slide 75

Slide 75 text

README.rst

Slide 76

Slide 76 text

shields.io

Slide 77

Slide 77 text

from setuptools import setup, find_packages setup( name=NAME, version=VERSION, description='A Django Debug Toolbar panel to show VCS info', long_description=read('README.rst'), classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: Libraries :: Application Frameworks', 'Topic :: Software Development :: Libraries :: Python Modules', ], keywords='django django-debug-toolbar git vcs info revision hash panel', author='giginet', author_email='[email protected]', url='https://github.com/giginet/%s' % NAME, download_url='https://github.com/giginet/%s/tarball/master' % NAME, license='MIT', packages=find_packages(), include_package_data=True, package_data={ '': ['README.rst', 'requirements.txt', 'requirements-test.txt'], }, zip_safe=True, install_requires=readlist('requirements.txt'), test_suite='runtests.run_tests', tests_require=readlist('requirements-test.txt'), )

Slide 78

Slide 78 text

$ python setup.py register $ python setup.py sdist upload

Slide 79

Slide 79 text

No content

Slide 80

Slide 80 text

No content

Slide 81

Slide 81 text

CONCLUSION ▸ How to develop Django plugin ▸ Workflow ▸ Testing ▸ Testing is IMPORTANT ▸ Documentation ▸ Deploying

Slide 82

Slide 82 text

ANY QUESTIONS?