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/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/__init__.py b/demo/demo/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/demo/demo/plotly_apps.py b/demo/demo/plotly_apps.py new file mode 100644 index 00000000..b223b815 --- /dev/null +++ b/demo/demo/plotly_apps.py @@ -0,0 +1,55 @@ +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 "{}" 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 [ + ("O2","Oxygen"),("N2","Nitrogen"),] + ],value="Oxygen"), + 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 new file mode 100644 index 00000000..e9384973 --- /dev/null +++ b/demo/demo/settings.py @@ -0,0 +1,122 @@ +""" +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', + + 'django_plotly_dash', +] + +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..d5aa60e9 --- /dev/null +++ b/demo/demo/urls.py @@ -0,0 +1,28 @@ +"""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 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/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/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/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 new file mode 100644 index 00000000..b03709b7 --- /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="django_plotly_dash: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/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) + 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/prepare_demo b/prepare_demo new file mode 100755 index 00000000..4021cd1c --- /dev/null +++ b/prepare_demo @@ -0,0 +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 new file mode 100644 index 00000000..06bf3f7c --- /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 +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 diff --git a/setup.py b/setup.py new file mode 100644 index 00000000..c177ddea --- /dev/null +++ b/setup.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python + +from setuptools import setup + +import django_plotly_dash as dpd + +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", + + ) +