From 04e9e9fd499af058b91da5316cb5922d1bd417c9 Mon Sep 17 00:00:00 2001 From: Mark Gibbs Date: Mon, 7 May 2018 23:34:34 -0700 Subject: [PATCH 1/9] Initial files --- django_plotly_dash/__init__.py | 6 ++ django_plotly_dash/dash_wrapper.py | 152 +++++++++++++++++++++++++++++ make_env | 5 + requirements.txt | 26 +++++ 4 files changed, 189 insertions(+) create mode 100644 django_plotly_dash/__init__.py create mode 100644 django_plotly_dash/dash_wrapper.py create mode 100755 make_env create mode 100644 requirements.txt diff --git a/django_plotly_dash/__init__.py b/django_plotly_dash/__init__.py new file mode 100644 index 00000000..af4c6e41 --- /dev/null +++ b/django_plotly_dash/__init__.py @@ -0,0 +1,6 @@ +# + +__version__ = "0.0.1" + +from .dash_wrapper import DelayedDash + diff --git a/django_plotly_dash/dash_wrapper.py b/django_plotly_dash/dash_wrapper.py new file mode 100644 index 00000000..c988caf4 --- /dev/null +++ b/django_plotly_dash/dash_wrapper.py @@ -0,0 +1,152 @@ +from dash import Dash +from flask import Flask + +from django.urls import reverse + +uid_counter = 0 + +usable_apps = {} +app_instances = {} +nd_apps = {} + +def get_app_by_name(name): + return usable_apps.get(name,None) + +def get_app_instance_by_id(id): + return nd_apps.get(id,None) + +class DelayedDash: + def __init__(self, name=None, **kwargs): + if name is None: + global uid_counter + uid_counter += 1 + self._uid = "djdash_%i" % uid_counter + else: + self._uid = name + self.layout = None + self._rep_dash = None + self._callback_sets = [] + + global usable_apps + usable_apps[self._uid] = self + + def _RepDash(self): + if self._rep_dash is None: + self._rep_dash = self._form_repdash() + return self._rep_dash + + def _form_repdash(self): + rd = NotDash(name_root=self._uid, + app_pathname="dexy:main") + rd.layout = self.layout + for cb, func in self._callback_sets: + rd.callback(**cb)(func) + return rd + + def base_url(self): + return self._RepDash().base_url() + + def callback(self, output, inputs=[], state=[], events=[]): + callback_set = {'output':output, + 'inputs':inputs, + 'state':state, + 'events':events} + def wrap_func(func,callback_set=callback_set,callback_sets=self._callback_sets): + callback_sets.append((callback_set,func)) + return func + return wrap_func + +class NotFlask: + def __init__(self): + self.config = {} + self.endpoints = {} + + def after_request(self,*args,**kwargs): + pass + def errorhandler(self,*args,**kwargs): + return args[0] + def add_url_rule(self,*args,**kwargs): + route = kwargs['endpoint'] + self.endpoints[route] = kwargs + def before_first_request(self,*args,**kwargs): + pass + def run(self,*args,**kwargs): + pass + +class NotDash(Dash): + def __init__(self, name_root, app_pathname, **kwargs): + + global app_instances + current_instances = app_instances.get(name_root,None) + + if current_instances is not None: + self._uid = "%s-%i" % (name_root,len(current_instances)+1) + current_instances.append(self) + else: + self._uid = name_root + app_instances[name_root] = [self,] + + self._flask_app = Flask(self._uid) + self._notflask = NotFlask() + self._base_pathname = reverse(app_pathname,kwargs={'id':self._uid}) + + kwargs['url_base_pathname'] = self._base_pathname + kwargs['server'] = self._notflask + super(NotDash, self).__init__(**kwargs) + global nd_apps + nd_apps[self._uid] = self + if False: # True for some debug info and a load of errors... + self.css.config.serve_locally = True + self.scripts.config.serve_locally = True + + def flask_app(self): + return self._flask_app + + def base_url(self): + return self._base_pathname + + def app_context(self, *args, **kwargs): + return self._flask_app.app_context(*args, + **kwargs) + + def test_request_context(self, *args, **kwargs): + return self._flask_app.test_request_context(*args, + **kwargs) + + def locate_endpoint_function(self, name=None): + if name is not None: + ep = "%s_%s" %(self._base_pathname, + name) + else: + ep = self._base_pathname + return self._notflask.endpoints[ep]['view_func'] + + @Dash.layout.setter + def layout(self, value): + self._fix_component_id(value) + return Dash.layout.fset(self, value) + + def _fix_component_id(self, component): + theID = getattr(component,"id",None) + if theID is not None: + setattr(component,"id",self._fix_id(theID)) + try: + for c in component.children: + self._fix_component_id(c) + except: + pass + + def _fix_id(self, name): + return "%s_-_%s" %(self._uid, + name) + + def _fix_callback_item(self, item): + item.component_id = self._fix_id(item.component_id) + return item + + def callback(self, output, inputs=[], state=[], events=[]): + return super(NotDash, self).callback(self._fix_callback_item(output), + [self._fix_callback_item(x) for x in inputs], + [self._fix_callback_item(x) for x in state], + [self._fix_callback_item(x) for x in events]) + diff --git a/make_env b/make_env new file mode 100755 index 00000000..82d9946e --- /dev/null +++ b/make_env @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +# +virtualenv -p python3 env +source env/bin/activate +pip install -r requirements.txt diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..e22618dc --- /dev/null +++ b/requirements.txt @@ -0,0 +1,26 @@ +certifi==2018.4.16 +chardet==3.0.4 +click==6.7 +dash==0.21.1 +dash-core-components==0.22.1 +dash-html-components==0.10.1 +decorator==4.3.0 +Django==2.0.5 +Flask==1.0.2 +Flask-Compress==1.4.0 +idna==2.6 +ipython-genutils==0.2.0 +itsdangerous==0.24 +Jinja2==2.10 +jsonschema==2.6.0 +jupyter-core==4.4.0 +MarkupSafe==1.0 +nbformat==4.4.0 +pkg-resources==0.0.0 +plotly==2.5.1 +pytz==2018.4 +requests==2.18.4 +six==1.11.0 +traitlets==4.3.2 +urllib3==1.22 +Werkzeug==0.14.1 From 30c4aeef8f8a48233b6e168d631e3cdc5d2b7899 Mon Sep 17 00:00:00 2001 From: Mark Gibbs Date: Tue, 8 May 2018 00:18:12 -0700 Subject: [PATCH 2/9] Added demo app --- .gitignore | 1 + demo/demo/__init__.py | 0 demo/demo/settings.py | 120 ++++++++++++++++++++++++++++++++++++++++++ demo/demo/urls.py | 21 ++++++++ demo/demo/wsgi.py | 16 ++++++ demo/manage.py | 15 ++++++ prepare_demo | 6 +++ setup.py | 19 +++++++ 8 files changed, 198 insertions(+) create mode 100644 demo/demo/__init__.py create mode 100644 demo/demo/settings.py create mode 100644 demo/demo/urls.py create mode 100644 demo/demo/wsgi.py create mode 100755 demo/manage.py create mode 100755 prepare_demo create mode 100644 setup.py diff --git a/.gitignore b/.gitignore index 7bbc71c0..1d45c5b1 100644 --- a/.gitignore +++ b/.gitignore @@ -53,6 +53,7 @@ coverage.xml # Django stuff: *.log local_settings.py +*/db.sqlite3 # Flask stuff: instance/ diff --git a/demo/demo/__init__.py b/demo/demo/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/demo/demo/settings.py b/demo/demo/settings.py new file mode 100644 index 00000000..a12b4bd0 --- /dev/null +++ b/demo/demo/settings.py @@ -0,0 +1,120 @@ +""" +Django settings for demo project. + +Generated by 'django-admin startproject' using Django 2.0.5. + +For more information on this file, see +https://docs.djangoproject.com/en/2.0/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/2.0/ref/settings/ +""" + +import os + +# Build paths inside the project like this: os.path.join(BASE_DIR, ...) +BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'va-ndhg=u^uti9x^9^9npg=+a4p%j(=50oiee+@zklb5qcnup4' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = [] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', +] + +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 = 'demo.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 = 'demo.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/2.0/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), + } +} + + +# Password validation +# https://docs.djangoproject.com/en/2.0/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/2.0/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/2.0/howto/static-files/ + +STATIC_URL = '/static/' diff --git a/demo/demo/urls.py b/demo/demo/urls.py new file mode 100644 index 00000000..8a17999d --- /dev/null +++ b/demo/demo/urls.py @@ -0,0 +1,21 @@ +"""demo URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/2.0/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), +] diff --git a/demo/demo/wsgi.py b/demo/demo/wsgi.py new file mode 100644 index 00000000..88957211 --- /dev/null +++ b/demo/demo/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for demo 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/2.0/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo.settings") + +application = get_wsgi_application() diff --git a/demo/manage.py b/demo/manage.py new file mode 100755 index 00000000..9187e9c4 --- /dev/null +++ b/demo/manage.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +import os +import sys + +if __name__ == "__main__": + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo.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) diff --git a/prepare_demo b/prepare_demo new file mode 100755 index 00000000..55c17b77 --- /dev/null +++ b/prepare_demo @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# +source env/bin/activate +cd demo +./manage.py migrate +./manage.py runserver diff --git a/setup.py b/setup.py new file mode 100644 index 00000000..2b49e661 --- /dev/null +++ b/setup.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python + +from setuptools import setup + +import django_plotly_dash as dpd + +VERSION = dpd.__version__ + +setup( + name="django-plotly-dash", + version=VERSION, + description="Django use of plotly dash apps through template tags", + author="Mark Gibbs", + author_email="django_plotly_dash@gibbsconsulting.ca", + packages=[ + 'django_plotly_dash', + ] + ) + From 88029ea075a54070460d3427af71f328ae9661ed Mon Sep 17 00:00:00 2001 From: Mark Gibbs Date: Tue, 8 May 2018 00:51:51 -0700 Subject: [PATCH 3/9] First working demo example. Need to relocate demo template --- demo/demo/plotly_apps.py | 54 +++++++++++++++++++ demo/demo/settings.py | 2 + demo/demo/urls.py | 9 +++- django_plotly_dash/admin.py | 3 ++ django_plotly_dash/apps.py | 5 ++ django_plotly_dash/dash_wrapper.py | 2 +- django_plotly_dash/models.py | 3 ++ .../django_plotly_dash/plotly_item.html | 3 ++ django_plotly_dash/templates/index.html | 19 +++++++ django_plotly_dash/templatetags/__init__.py | 0 django_plotly_dash/templatetags/dexy.py | 13 +++++ django_plotly_dash/tests.py | 3 ++ django_plotly_dash/urls.py | 16 ++++++ django_plotly_dash/views.py | 44 +++++++++++++++ 14 files changed, 174 insertions(+), 2 deletions(-) create mode 100644 demo/demo/plotly_apps.py create mode 100644 django_plotly_dash/admin.py create mode 100644 django_plotly_dash/apps.py create mode 100644 django_plotly_dash/models.py create mode 100644 django_plotly_dash/templates/django_plotly_dash/plotly_item.html create mode 100644 django_plotly_dash/templates/index.html create mode 100644 django_plotly_dash/templatetags/__init__.py create mode 100644 django_plotly_dash/templatetags/dexy.py create mode 100644 django_plotly_dash/tests.py create mode 100644 django_plotly_dash/urls.py create mode 100644 django_plotly_dash/views.py diff --git a/demo/demo/plotly_apps.py b/demo/demo/plotly_apps.py new file mode 100644 index 00000000..00fa066d --- /dev/null +++ b/demo/demo/plotly_apps.py @@ -0,0 +1,54 @@ +import dash +import dash_core_components as dcc +import dash_html_components as html + +from django_plotly_dash import DelayedDash + +app = DelayedDash('SimpleExample') + +app.layout = html.Div([ + dcc.RadioItems( + id='dropdown-a', + options=[{'label': i, 'value': i} for i in ['Canada', 'USA', 'Mexico']], + value='Canada' + ), + html.Div(id='output-a'), + + dcc.RadioItems( + id='dropdown-b', + options=[{'label': i, 'value': i} for i in ['MTL', 'NYC', 'SF']], + value='MTL' + ), + html.Div(id='output-b') + +]) + +@app.callback( + dash.dependencies.Output('output-a', 'children'), + [dash.dependencies.Input('dropdown-a', 'value')]) +def callback_a(dropdown_value): + return 'You\'ve selected "{}"'.format(dropdown_value) + + +@app.callback( + dash.dependencies.Output('output-b', 'children'), + [dash.dependencies.Input('dropdown-a', 'value'), + dash.dependencies.Input('dropdown-b', 'value')]) +def callback_b(dropdown_value,other_dd): + return 'You\'ve selected "{}"'.format(dropdown_value) + +a2 = DelayedDash("Ex2") +a2.layout = html.Div([ + dcc.RadioItems(id="dropdown-one",options=[{'label':i,'value':j} for i,j in [ + ("BEER","Beer"),("WIne","wine"),] + ],value="Beer"), + html.Div(id="output-one") + ]) + +@a2.callback( + dash.dependencies.Output('output-one','children'), + [dash.dependencies.Input('dropdown-one','value')] + ) +def callback_c(*args,**kwargs): + return "Args are %s and kwargs are %s" %("".join(*args),str(kwargs)) + diff --git a/demo/demo/settings.py b/demo/demo/settings.py index a12b4bd0..e9384973 100644 --- a/demo/demo/settings.py +++ b/demo/demo/settings.py @@ -37,6 +37,8 @@ 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', + + 'django_plotly_dash', ] MIDDLEWARE = [ diff --git a/demo/demo/urls.py b/demo/demo/urls.py index 8a17999d..d5aa60e9 100644 --- a/demo/demo/urls.py +++ b/demo/demo/urls.py @@ -14,8 +14,15 @@ 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin -from django.urls import path +from django.urls import include, path + +from django.views.generic import TemplateView + +# Load demo plotly apps +import demo.plotly_apps urlpatterns = [ + path('', TemplateView.as_view(template_name='index.html')), path('admin/', admin.site.urls), + path('django_plotly_dash/', include('django_plotly_dash.urls')), ] diff --git a/django_plotly_dash/admin.py b/django_plotly_dash/admin.py new file mode 100644 index 00000000..8c38f3f3 --- /dev/null +++ b/django_plotly_dash/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/django_plotly_dash/apps.py b/django_plotly_dash/apps.py new file mode 100644 index 00000000..5109ed21 --- /dev/null +++ b/django_plotly_dash/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class DjangoPlotlyDashConfig(AppConfig): + name = 'django_plotly_dash' diff --git a/django_plotly_dash/dash_wrapper.py b/django_plotly_dash/dash_wrapper.py index c988caf4..b03709b7 100644 --- a/django_plotly_dash/dash_wrapper.py +++ b/django_plotly_dash/dash_wrapper.py @@ -37,7 +37,7 @@ def _RepDash(self): def _form_repdash(self): rd = NotDash(name_root=self._uid, - app_pathname="dexy:main") + app_pathname="django_plotly_dash:main") rd.layout = self.layout for cb, func in self._callback_sets: rd.callback(**cb)(func) diff --git a/django_plotly_dash/models.py b/django_plotly_dash/models.py new file mode 100644 index 00000000..71a83623 --- /dev/null +++ b/django_plotly_dash/models.py @@ -0,0 +1,3 @@ +from django.db import models + +# Create your models here. diff --git a/django_plotly_dash/templates/django_plotly_dash/plotly_item.html b/django_plotly_dash/templates/django_plotly_dash/plotly_item.html new file mode 100644 index 00000000..23d49438 --- /dev/null +++ b/django_plotly_dash/templates/django_plotly_dash/plotly_item.html @@ -0,0 +1,3 @@ +
+ +
diff --git a/django_plotly_dash/templates/index.html b/django_plotly_dash/templates/index.html new file mode 100644 index 00000000..f86db9c0 --- /dev/null +++ b/django_plotly_dash/templates/index.html @@ -0,0 +1,19 @@ + + +{%load dexy%} + Simple stuff + +
+ Content here + {%plotly_item "SimpleExample"%} +
+
+ Content here + {%plotly_item "SimpleExample"%} +
+
+ Content here + {%plotly_item "Ex2"%} +
+ + diff --git a/django_plotly_dash/templatetags/__init__.py b/django_plotly_dash/templatetags/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/django_plotly_dash/templatetags/dexy.py b/django_plotly_dash/templatetags/dexy.py new file mode 100644 index 00000000..52fce6e5 --- /dev/null +++ b/django_plotly_dash/templatetags/dexy.py @@ -0,0 +1,13 @@ +from django import template + +register = template.Library() + +from django_plotly_dash.dash_wrapper import get_app_by_name + +@register.inclusion_tag("django_plotly_dash/plotly_item.html", takes_context=True) +def plotly_item(context, app_name): + + app = get_app_by_name(app_name) + url = app.base_url() + + return locals() diff --git a/django_plotly_dash/tests.py b/django_plotly_dash/tests.py new file mode 100644 index 00000000..7ce503c2 --- /dev/null +++ b/django_plotly_dash/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/django_plotly_dash/urls.py b/django_plotly_dash/urls.py new file mode 100644 index 00000000..375cbbca --- /dev/null +++ b/django_plotly_dash/urls.py @@ -0,0 +1,16 @@ +from django.urls import path +from django.views.decorators.csrf import csrf_exempt + +from .views import routes, layout, dependencies, update, main_view + +app_name = "django_plotly_dash" + +urlpatterns = [ + path('_dash-routes', routes, name="routes"), + path('_dash-layout', layout, name="layout"), + path('_dash-dependencies', dependencies, name="dependencies"), + path('_dash-update-component', csrf_exempt(update), name="update-component"), + + path('', main_view, name="main"), + ] + diff --git a/django_plotly_dash/views.py b/django_plotly_dash/views.py new file mode 100644 index 00000000..92dc0a95 --- /dev/null +++ b/django_plotly_dash/views.py @@ -0,0 +1,44 @@ +from django.shortcuts import render + +import flask +import json + +from .dash_wrapper import get_app_instance_by_id +from django.http import HttpResponse + +def routes(*args,**kwargs): + pass + +def dependencies(request, id, **kwargs): + app = get_app_instance_by_id(id) + with app.app_context(): + mFunc = app.locate_endpoint_function('dash-dependencies') + resp = mFunc() + return HttpResponse(resp.data, + content_type=resp.mimetype) + +def layout(request, id, **kwargs): + app = get_app_instance_by_id(id) + mFunc = app.locate_endpoint_function('dash-layout') + resp = mFunc() + return HttpResponse(resp.data, + content_type=resp.mimetype) + +def update(request, id, **kwargs): + app = get_app_instance_by_id(id) + mFunc = app.locate_endpoint_function('dash-update-component') + # Fudge request object + rb = json.loads(request.body.decode('utf-8')) + with app.test_request_context(): + # inputs state and output needed in the json objects + flask.request._cached_json = (rb, flask.request._cached_json[True]) + resp = mFunc() + return HttpResponse(resp.data, + content_type=resp.mimetype) + +def main_view(request, id, **kwargs): + app = get_app_instance_by_id(id) + mFunc = app.locate_endpoint_function() + resp = mFunc() + return HttpResponse(resp) + From a77c3d80c3dda7d158ee55890629eed3cb6b2e51 Mon Sep 17 00:00:00 2001 From: Mark Gibbs Date: Tue, 8 May 2018 08:58:27 -0700 Subject: [PATCH 4/9] Fix up requirements.txt file. Removal of spurious entry --- requirements.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index e22618dc..bee12dde 100644 --- a/requirements.txt +++ b/requirements.txt @@ -16,7 +16,6 @@ jsonschema==2.6.0 jupyter-core==4.4.0 MarkupSafe==1.0 nbformat==4.4.0 -pkg-resources==0.0.0 plotly==2.5.1 pytz==2018.4 requests==2.18.4 From 9280a2266d522720a191f8f196a974fccddb1c62 Mon Sep 17 00:00:00 2001 From: Mark Gibbs Date: Tue, 8 May 2018 10:18:36 -0700 Subject: [PATCH 5/9] Update setup and related scripts --- README.md | 7 ++++++- demo/demo/plotly_apps.py | 7 ++++--- prepare_demo | 1 + requirements.txt | 1 + setup.py | 28 +++++++++++++++++++++++++++- 5 files changed, 39 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 04310c1d..aaceaab3 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,7 @@ # django-plotly-dash -Expose plotly dash apps as django tags + +Expose plotly dash apps as django tags. + +See the source for this project here: +. + diff --git a/demo/demo/plotly_apps.py b/demo/demo/plotly_apps.py index 00fa066d..b223b815 100644 --- a/demo/demo/plotly_apps.py +++ b/demo/demo/plotly_apps.py @@ -35,13 +35,14 @@ def callback_a(dropdown_value): [dash.dependencies.Input('dropdown-a', 'value'), dash.dependencies.Input('dropdown-b', 'value')]) def callback_b(dropdown_value,other_dd): - return 'You\'ve selected "{}"'.format(dropdown_value) + return 'You\'ve selected "{}" and "{}"'.format(dropdown_value, + other_dd) a2 = DelayedDash("Ex2") a2.layout = html.Div([ dcc.RadioItems(id="dropdown-one",options=[{'label':i,'value':j} for i,j in [ - ("BEER","Beer"),("WIne","wine"),] - ],value="Beer"), + ("O2","Oxygen"),("N2","Nitrogen"),] + ],value="Oxygen"), html.Div(id="output-one") ]) diff --git a/prepare_demo b/prepare_demo index 55c17b77..4021cd1c 100755 --- a/prepare_demo +++ b/prepare_demo @@ -1,6 +1,7 @@ #!/usr/bin/env bash # source env/bin/activate +python setup.py develop cd demo ./manage.py migrate ./manage.py runserver diff --git a/requirements.txt b/requirements.txt index bee12dde..06bf3f7c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,6 +4,7 @@ click==6.7 dash==0.21.1 dash-core-components==0.22.1 dash-html-components==0.10.1 +dash-renderer==0.12.1 decorator==4.3.0 Django==2.0.5 Flask==1.0.2 diff --git a/setup.py b/setup.py index 2b49e661..c177ddea 100644 --- a/setup.py +++ b/setup.py @@ -6,14 +6,40 @@ VERSION = dpd.__version__ +with open('README.md') as f: + long_description = f.read() + setup( name="django-plotly-dash", version=VERSION, + url="https://github.com/GibbsConsulting/django-plotly-dash", description="Django use of plotly dash apps through template tags", + long_description=long_description, + long_description_content_type="text/markdown", author="Mark Gibbs", author_email="django_plotly_dash@gibbsconsulting.ca", + license='MIT', packages=[ 'django_plotly_dash', - ] + ], + classifiers = [ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: MIT License', + 'Programming Language :: Python :: 3', + ], + keywords='django plotly plotly-dash dash dashboard', + project_urls = { + 'Source': "https://github.com/GibbsConsulting/django-plotly-dash", + 'Tracker': "https://github.com/GibbsConsulting/django-plotly-dash/issues", + }, + install_requires = ['plotly', + 'dash', + 'dash-core-components', + 'dash-html-components', + 'dash-renderer', + 'Django',], + python_requires=">=3", + ) From b0f1fb09c8c2190fdfc0ab1d1659e3a08e85c2ef Mon Sep 17 00:00:00 2001 From: Mark Gibbs Date: Tue, 8 May 2018 11:53:07 -0700 Subject: [PATCH 6/9] Rename template tag --- django_plotly_dash/templates/index.html | 2 +- django_plotly_dash/templatetags/{dexy.py => plotly_dash.py} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename django_plotly_dash/templatetags/{dexy.py => plotly_dash.py} (100%) diff --git a/django_plotly_dash/templates/index.html b/django_plotly_dash/templates/index.html index f86db9c0..7749878a 100644 --- a/django_plotly_dash/templates/index.html +++ b/django_plotly_dash/templates/index.html @@ -1,6 +1,6 @@ -{%load dexy%} +{%load plotly_dash%} Simple stuff
diff --git a/django_plotly_dash/templatetags/dexy.py b/django_plotly_dash/templatetags/plotly_dash.py similarity index 100% rename from django_plotly_dash/templatetags/dexy.py rename to django_plotly_dash/templatetags/plotly_dash.py From 1d5a7144ba035cab682dd32ad5c04dc641bf23ed Mon Sep 17 00:00:00 2001 From: Mark Gibbs Date: Tue, 8 May 2018 11:57:34 -0700 Subject: [PATCH 7/9] Relocate demo template inside demo, not app --- demo/demo/settings.py | 2 +- {django_plotly_dash => demo/demo}/templates/index.html | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename {django_plotly_dash => demo/demo}/templates/index.html (100%) diff --git a/demo/demo/settings.py b/demo/demo/settings.py index e9384973..08964954 100644 --- a/demo/demo/settings.py +++ b/demo/demo/settings.py @@ -56,7 +56,7 @@ TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'DIRS': [], + 'DIRS': [os.path.join(BASE_DIR,'demo','templates'),], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ diff --git a/django_plotly_dash/templates/index.html b/demo/demo/templates/index.html similarity index 100% rename from django_plotly_dash/templates/index.html rename to demo/demo/templates/index.html From 293b454ee8965422155a971d9e417878dc89ce82 Mon Sep 17 00:00:00 2001 From: Mark Gibbs Date: Tue, 8 May 2018 12:28:53 -0700 Subject: [PATCH 8/9] Adding skeleton for documentation --- README.md | 5 +- docs/Makefile | 20 ++++++ docs/conf.py | 155 +++++++++++++++++++++++++++++++++++++++++++++++ docs/index.rst | 20 ++++++ requirements.txt | 20 ------ 5 files changed, 199 insertions(+), 21 deletions(-) create mode 100644 docs/Makefile create mode 100644 docs/conf.py create mode 100644 docs/index.rst diff --git a/README.md b/README.md index aaceaab3..9d05260c 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,10 @@ # django-plotly-dash -Expose plotly dash apps as django tags. +Expose [plotly dash](https://plot.ly/products/dash/) apps as django tags. See the source for this project here: . +## Installation + +To use existing dash applications, just register thenm \ No newline at end of file diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 00000000..feb93abe --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +SPHINXPROJ = django-plotly-dash +SOURCEDIR = . +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) \ No newline at end of file diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 00000000..882ac61c --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,155 @@ +# -*- coding: utf-8 -*- +# +# Configuration file for the Sphinx documentation builder. +# +# This file does only contain a selection of the most common options. For a +# full list see the documentation: +# http://www.sphinx-doc.org/en/master/config + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +# import os +# import sys +# sys.path.insert(0, os.path.abspath('.')) + + +# -- Project information ----------------------------------------------------- + +project = 'django-plotly-dash' +copyright = '2018, Mark Gibbs' +author = 'Mark Gibbs' + +# The short X.Y version +version = '' +# The full version, including alpha/beta/rc tags +release = '' + + +# -- General configuration --------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = '.rst' + +# The master toctree document. +master_doc = 'index' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path . +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = 'alabaster' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# Custom sidebar templates, must be a dictionary that maps document names +# to template names. +# +# The default sidebars (for documents that don't match any pattern) are +# defined by theme itself. Builtin themes are using these templates by +# default: ``['localtoc.html', 'relations.html', 'sourcelink.html', +# 'searchbox.html']``. +# +# html_sidebars = {} + + +# -- Options for HTMLHelp output --------------------------------------------- + +# Output file base name for HTML help builder. +htmlhelp_basename = 'django-plotly-dashdoc' + + +# -- Options for LaTeX output ------------------------------------------------ + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'django-plotly-dash.tex', 'django-plotly-dash Documentation', + 'Mark Gibbs', 'manual'), +] + + +# -- Options for manual page output ------------------------------------------ + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'django-plotly-dash', 'django-plotly-dash Documentation', + [author], 1) +] + + +# -- Options for Texinfo output ---------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'django-plotly-dash', 'django-plotly-dash Documentation', + author, 'django-plotly-dash', 'One line description of project.', + 'Miscellaneous'), +] \ No newline at end of file diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 00000000..a064b014 --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,20 @@ +.. django-plotly-dash documentation master file, created by + sphinx-quickstart on Tue May 8 12:25:40 2018. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to django-plotly-dash's documentation! +============================================== + +.. toctree:: + :maxdepth: 2 + :caption: Contents: + + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/requirements.txt b/requirements.txt index 06bf3f7c..4c75f37e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,26 +1,6 @@ -certifi==2018.4.16 -chardet==3.0.4 -click==6.7 dash==0.21.1 dash-core-components==0.22.1 dash-html-components==0.10.1 dash-renderer==0.12.1 -decorator==4.3.0 Django==2.0.5 -Flask==1.0.2 -Flask-Compress==1.4.0 -idna==2.6 -ipython-genutils==0.2.0 -itsdangerous==0.24 -Jinja2==2.10 -jsonschema==2.6.0 -jupyter-core==4.4.0 -MarkupSafe==1.0 -nbformat==4.4.0 plotly==2.5.1 -pytz==2018.4 -requests==2.18.4 -six==1.11.0 -traitlets==4.3.2 -urllib3==1.22 -Werkzeug==0.14.1 From fbb05b9f7b5b2e3539c0abc6266ad56eceeeacb2 Mon Sep 17 00:00:00 2001 From: Mark Gibbs Date: Tue, 8 May 2018 13:51:14 -0700 Subject: [PATCH 9/9] Raw documentation files --- README.md | 96 ++++++++++++++++++++++++++++++++++++++++++- dev_requirements.txt | 54 ++++++++++++++++++++++++ docs/conf.py | 7 ++-- docs/index.rst | 7 +++- docs/installation.rst | 38 +++++++++++++++++ docs/simple_use.rst | 61 +++++++++++++++++++++++++++ setup.py | 1 + 7 files changed, 258 insertions(+), 6 deletions(-) create mode 100644 dev_requirements.txt create mode 100644 docs/installation.rst create mode 100644 docs/simple_use.rst diff --git a/README.md b/README.md index 9d05260c..f2a2070e 100644 --- a/README.md +++ b/README.md @@ -3,8 +3,100 @@ Expose [plotly dash](https://plot.ly/products/dash/) apps as django tags. See the source for this project here: -. + + +Online documentation can be found here: + ## Installation -To use existing dash applications, just register thenm \ No newline at end of file +First, install the package. This will also install plotly and some dash packages if they are not already present. + + pip install django_plotly_dash + +Then, just add `django_plotly_dash` to `INSTALLED_APPS` in your Django `settings.py` file + + INSTALLED_APPS = [ + ... + 'django_plotly_dash', + ... + ] + +## Demonstration + +The source repository contains a demo application. To clone the repo and lauch the demo: + +```bash +git clone https://github.com/GibbsConsulting/django-plotly-dash.git + +cd django-plotly-dash + +./make_env # sets up a virtual environment for development + # with direct use of the source code for the package + +./prepare_demo # prepares and launches the demo + # using the Django debug server at http://localhost:8000 +``` + +## Usage + +To use existing dash applications, first register them using the `DelayedDash` class. This +replaces the `dash.Dash` class of `plotly.py.` + +Taking as an example a slightly modified variant of one of the [getting started](https://dash.plot.ly/getting-started-part-2) examples: + +```python +import dash +import dash_core_components as dcc +import dash_html_components as html + +from django_plotly_dash import DelayedDash + +app = DelayedDash('SimpleExample') # replaces dash.Dash + +app.layout = html.Div([ + dcc.RadioItems( + id='dropdown-a', + options=[{'label': i, 'value': i} for i in ['Canada', 'USA', 'Mexico']], + value='Canada' + ), + html.Div(id='output-a'), + + dcc.RadioItems( + id='dropdown-b', + options=[{'label': i, 'value': i} for i in ['MTL', 'NYC', 'SF']], + value='MTL' + ), + html.Div(id='output-b') + +]) + +@app.callback( + dash.dependencies.Output('output-a', 'children'), + [dash.dependencies.Input('dropdown-a', 'value')]) +def callback_a(dropdown_value): + return 'You\'ve selected "{}"'.format(dropdown_value) + + +@app.callback( + dash.dependencies.Output('output-b', 'children'), + [dash.dependencies.Input('dropdown-a', 'value'), + dash.dependencies.Input('dropdown-b', 'value')]) +def callback_b(dropdown_value,other_dd): + return 'You\'ve selected "{}" and "{}"'.format(dropdown_value, + other_dd) +``` + +Note that the `DelayedDash` constructor requires a name to be specified. This name is then used to identify the dash app in +templates: + +```jinja2 +{% load plotly_dash %} + +{% plotly_item "SimpleExample" %} +``` + +Note that the registration code needs to be in a location +that will be imported into the Django process before any template tag attempts to use it. The example Django application +in the demo subdirectory achieves this through an import in the main urls.py file; any views.py would also be sufficient. + diff --git a/dev_requirements.txt b/dev_requirements.txt new file mode 100644 index 00000000..a3b7d1d1 --- /dev/null +++ b/dev_requirements.txt @@ -0,0 +1,54 @@ +alabaster==0.7.10 +argh==0.26.2 +Babel==2.5.3 +certifi==2018.4.16 +chardet==3.0.4 +click==6.7 +dash==0.21.1 +dash-core-components==0.22.1 +dash-html-components==0.10.1 +dash-renderer==0.12.1 +decorator==4.3.0 +Django==2.0.5 +-e git+https://github.com/delsim/django-plotly-dash.git@293b454ee8965422155a971d9e417878dc89ce82#egg=django_plotly_dash +docopt==0.6.2 +docutils==0.14 +Flask==1.0.2 +Flask-Compress==1.4.0 +grip==4.5.2 +idna==2.6 +imagesize==1.0.0 +ipython-genutils==0.2.0 +itsdangerous==0.24 +Jinja2==2.10 +jsonschema==2.6.0 +jupyter-core==4.4.0 +livereload==2.5.2 +Markdown==2.6.11 +MarkupSafe==1.0 +nbformat==4.4.0 +packaging==17.1 +path-and-address==2.0.1 +pathtools==0.1.2 +pkginfo==1.4.2 +plotly==2.5.1 +port-for==0.3.1 +Pygments==2.2.0 +pyparsing==2.2.0 +pytz==2018.4 +PyYAML==3.12 +requests==2.18.4 +requests-toolbelt==0.8.0 +six==1.11.0 +snowballstemmer==1.2.1 +Sphinx==1.7.4 +sphinx-autobuild==0.7.1 +sphinx-rtd-theme==0.3.1 +sphinxcontrib-websupport==1.0.1 +tornado==5.0.2 +tqdm==4.23.3 +traitlets==4.3.2 +twine==1.11.0 +urllib3==1.22 +watchdog==0.8.3 +Werkzeug==0.14.1 diff --git a/docs/conf.py b/docs/conf.py index 882ac61c..d29c14d6 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -20,7 +20,7 @@ # -- Project information ----------------------------------------------------- project = 'django-plotly-dash' -copyright = '2018, Mark Gibbs' +copyright = '2018 Gibbs Consulting, a division of 0802100 (BC) Ltd' author = 'Mark Gibbs' # The short X.Y version @@ -74,7 +74,8 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # -html_theme = 'alabaster' +#html_theme = 'alabaster' +html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the @@ -152,4 +153,4 @@ (master_doc, 'django-plotly-dash', 'django-plotly-dash Documentation', author, 'django-plotly-dash', 'One line description of project.', 'Miscellaneous'), -] \ No newline at end of file +] diff --git a/docs/index.rst b/docs/index.rst index a064b014..07d06acc 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -6,14 +6,19 @@ Welcome to django-plotly-dash's documentation! ============================================== +Contents +-------- + .. toctree:: :maxdepth: 2 :caption: Contents: + installation + simple_use Indices and tables -================== +------------------ * :ref:`genindex` * :ref:`modindex` diff --git a/docs/installation.rst b/docs/installation.rst new file mode 100644 index 00000000..ee12c752 --- /dev/null +++ b/docs/installation.rst @@ -0,0 +1,38 @@ +.. _installation: + +Installation +============ + +Use pip to install the package, preferably to a local virtualenv.:: + + pip install django_plotly_dash + +Then, add ``django_plotly_dash`` to ``INSTALLED_APPS`` in the Django settings.py file:: + + INSTALLED_APPS = [ + ... + 'django_plotly_dash', + ... + ] + +The plotly_item tag in the plotly_dash tag library can then be used to render any registered dash component. See :ref:`simple_use` for a simple example. + +Source code and demo +-------------------- + +The source code repository contains a simple demo application. + +To install and run it:: + + git clone https://github.com/GibbsConsulting/django-plotly-dash.git + + cd django-plotly-dash + + ./make_env # sets up a virtual environment + # with direct use of the source + # code for the package + + ./prepare_demo # prepares and launches the demo + # using the Django debug server + # at http://localhost:8000 + diff --git a/docs/simple_use.rst b/docs/simple_use.rst new file mode 100644 index 00000000..4d8c863a --- /dev/null +++ b/docs/simple_use.rst @@ -0,0 +1,61 @@ +.. _simple_use: + +Simple Usage +============ + +To use existing dash applications, first register them using the ``DelayedDash`` class. This +replaces the ``dash.Dash`` class of ``plotly.py`` + +Taking as an example a slightly modified variant of one of the `getting started `_ examples:: + + import dash + import dash_core_components as dcc + import dash_html_components as html + + from django_plotly_dash import DelayedDash + + app = DelayedDash('SimpleExample') # replaces dash.Dash + + app.layout = html.Div([ + dcc.RadioItems( + id='dropdown-a', + options=[{'label': i, 'value': i} for i in ['Canada', 'USA', 'Mexico']], + value='Canada' + ), + html.Div(id='output-a'), + + dcc.RadioItems( + id='dropdown-b', + options=[{'label': i, 'value': i} for i in ['MTL', 'NYC', 'SF']], + value='MTL' + ), + html.Div(id='output-b') + + ]) + + @app.callback( + dash.dependencies.Output('output-a', 'children'), + [dash.dependencies.Input('dropdown-a', 'value')]) + def callback_a(dropdown_value): + return 'You\'ve selected "{}"'.format(dropdown_value) + + + @app.callback( + dash.dependencies.Output('output-b', 'children'), + [dash.dependencies.Input('dropdown-a', 'value'), + dash.dependencies.Input('dropdown-b', 'value')]) + def callback_b(dropdown_value,other_dd): + return 'You\'ve selected "{}" and "{}"'.format(dropdown_value, + other_dd) + +Note that the ``DelayedDash`` constructor requires a name to be specified. This name is then used to identify the dash app in +templates::: + + {%load plotly_dash%} + + {%plotly_item "SimpleExample"%} + +Note that the registration code needs to be in a location +that will be imported into the Django process before any template tag attempts to use it. The example Django application +in the demo subdirectory achieves this through an import in the main urls.py file; any views.py would also be sufficient. + diff --git a/setup.py b/setup.py index c177ddea..1f1ec402 100644 --- a/setup.py +++ b/setup.py @@ -32,6 +32,7 @@ project_urls = { 'Source': "https://github.com/GibbsConsulting/django-plotly-dash", 'Tracker': "https://github.com/GibbsConsulting/django-plotly-dash/issues", + 'Documentation': 'http://django-plotly-dash.readthedocs.io/', }, install_requires = ['plotly', 'dash',