• Stars
    star
    167
  • Rank 226,635 (Top 5 %)
  • Language
    Python
  • License
    MIT License
  • Created over 9 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Django/PostgreSQL implementation of the Meteor server.

Django DDP

Django DDP is a Django/PostgreSQL implementation of the Meteor DDP server, allowing Meteor to subscribe to changes on Django models. Released under the MIT license.

Requirements

You must be using PostgreSQL with psycopg2 in your Django project for django-ddp to work. There is no requirement on any asynchronous framework such as Redis or crossbar.io as they are simply not needed given the asynchronous support provided by PostgreSQL with psycopg2.

Since the test suite includes an example Meteor project, running that requires that Meteor is installed (and meteor is in your PATH).

Installation

Install the latest release from pypi (recommended):

pip install django-ddp

Clone and use development version direct from GitHub to test pre-release code (no GitHub account required):

pip install -e git+https://github.com/commoncode/django-ddp@develop#egg=django-ddp

Overview and getting started

  1. Django DDP registers handlers for Django signals on all model save/update operations.
    • Add 'dddp' to INSTALLED_APPS in your project settings file.
  2. Each Django application (ie: your code) registers Collections and Publications via ddp sub-modules for all INSTALLED_APPS.
    • Register collections and publications in a file named dddp.py inside your application module.
  3. Clients subscribe to publications, entries are written into the dddp.Subscription and dddp.SubscriptionCollection model tables and the get_queries method of publications are called to retrieve the Django ORM queries that contain the objects that will be sent to the client.
    • Run manage.py migrate to update your database so it has the necessary tables needed for tracking client subscriptions.
  4. When models are saved, the Django DDP signal handlers send change messages to clients subscribed to relevant publications.
    • Use the model save() and delete() methods as appropriate in your application code so that appropriate signals are raised and change messages are sent.
  5. Gevent is used to run WebSocket connections concurrently along with any Django views defined in your project (via your project urls.py).
    • Run your application using the dddp command which sets up the gevent mainloop and serves your Django project views. This command takes care of routing WebSocket connections according to the URLs that Meteor uses, do not add URLs for WebSocket views to your project urls.py.

Scalability

All database queries to support DDP events are done once by the server instance that has made changes via the Django ORM. Django DDP multiplexes messages for active subscriptions, broadcasting an aggregated change message on channels specific to each Django model that has been published.

Peer servers subscribe to aggregate broadcast events which are de-multiplexed and dispatched to individual client connections. No additional database queries are required for de-multiplexing or dispatch by peer servers.

Limitations

  • No support for the SockJS XHR fallback protocol to support browsers that don't have WebSockets (see http://caniuse.com/websockets for supported browsers). It is noteworthy that the only current browser listed that doesn't support WebSockets is Opera Mini, which doesn't support pages that use EcmaScript (JavaScript) for interactivity anyway. Offering SockJS XHR fallback wouldn't help to substantially increase browser support: if Opera Mini is excluded then all current browser versions including IE, Edge, Firefox, Chrome, Safari, Opera, iOS Safari, Android Browser Android and Chrome for Android are supported. Having said all that, pull requests are welcome.
  • Changes must be made via the Django ORM as django-ddp uses Django signals to receive model save/update signals. There are no technical reasons why database triggers couldn't be used - pull requests are welcome.

Example usage

Add 'dddp' to your settings.INSTALLED_APPS:

# settings.py
...
INSTALLED_APPS = list(INSTALLED_APPS) + ['dddp']

If you'd like support for the Meteor Accounts package (ie: login/logout with django.contrib.auth) consult the section on authentication below and use the following line instead:

# settings.py
...
INSTALLED_APPS = list(INSTALLED_APPS) + ['dddp', 'dddp.accounts']

Add ddp.py to your Django application:

# bookstore/ddp.py

from dddp.api import API, Collection, Publication
from bookstore import models

class Book(Collection):
    model = models.Book


class Author(Collection):
    model = models.Author


class AllBooks(Publication):
    queries = [
        models.Author.objects.all(),
        models.Book.objects.all(),
    ]


class BooksByAuthorEmail(Publication):
    def get_queries(self, author_email):
        return [
            models.Author.objects.filter(
                email=author_email,
            ),
            models.Book.objects.filter(
                author__email=author_email,
            ),
        ]


API.register(
    [Book, Author, AllBooks, BooksByAuthorEmail]
)

Start the Django DDP service:

DJANGO_SETTINGS_MODULE=myproject.settings dddp

Using django-ddp as a secondary DDP connection (RAPID DEVELOPMENT)

Running in this manner allows rapid development through use of the hot code push features provided by Meteor.

Connect your Meteor application to the Django DDP service:

// bookstore.js
if (Meteor.isClient) {
    // Connect to Django DDP service
    Django = DDP.connect('http://'+window.location.hostname+':8000/');
    // Create local collections for Django models received via DDP
    Authors = new Mongo.Collection("bookstore.author", {connection: Django});
    Books = new Mongo.Collection("bookstore.book", {connection: Django});
    // Subscribe to all books by Janet Evanovich
    Django.subscribe('BooksByAuthorEmail', '[email protected]');
}

Start Meteor (from within your meteor application directory):

meteor

Using django-ddp as the primary DDP connection (RECOMMENDED)

If you'd prefer to not have two DDP connections (one to Meteor and one to django-ddp) you can set the DDP_DEFAULT_CONNECTION_URL environment variable to use the specified URL as the primary DDP connection in Meteor. When doing this, you won't need to use DDP.connect(...) or specify {connection: Django} on your collections. Running with django-ddp as the primary connection is recommended, and indeed required if you wish to use dddp.accounts to provide authentication using django.contrib.auth to your meteor app.

DDP_DEFAULT_CONNECTION_URL=http://localhost:8000/ meteor

Serving your Meteor applications from django-ddp

First, you will need to build your meteor app into a directory (examples below assume target directory named myapp):

meteor build ../myapp

Then, add a MeteorView to your urls.py:

from dddp.views import MeteorView

urlpatterns = patterns(
    url('^(?P<path>/.*)$', MeteorView.as_view(
        json_path=os.path.join(
            settings.PROJ_ROOT, 'myapp', 'bundle', 'star.json',
        ),
    ),
)

Adding API endpoints (server method definitions)

API endpoints can be added by calling register method of the dddp.api.API object from the ddp.py module of your Django app, on a subclass of dddp.api.APIMixin - both dddp.api.Collection and dddp.api.Publication are suitable, or you may define your own subclass of dddp.api.APIMixin. A good example of this can be seen in dddp/accounts/ddp.py in the source of django-ddp.

Authentication

Authentication is provided using the standard meteor accounts system, along with the accounts-secure package which turns off Meteor's password hashing in favour of using TLS (HTTPS + WebSockets). This ensures strong protection for all data over the wire. Correctly using TLS/SSL also protects your site against man-in-the-middle and replay attacks - Meteor is vulnerable to both of these without using encryption.

Add dddp.accounts to your settings.INSTALLED_APPS as described in the example usage section above, then add tysonclugg:accounts-secure to your Meteor application (from within your meteor application directory):

meteor add tysonclugg:accounts-secure

Then follow the normal procedure to add login/logout views to your Meteor application.

Contributors

Tyson Clugg
  • Author, conceptual design.
Yan Le
  • Validate and bug fix dddp.accounts submodule.
MEERQAT
  • Project sponsor - many thanks for allowing this to be released under an open source license!
David Burles
  • Expert guidance on how DDP works in Meteor.
Brenton Cleeland
  • Great conversations around how collections and publications can limit visibility of published documents to specific users.
Muhammed Thanish

This project is forever grateful for the love, support and respect given by the awesome team at Common Code.

More Repositories

1

django-debug-toolbar

A configurable set of panels that display various debug information about the current request/response.
Python
8,023
star
2

pip-tools

A set of tools to keep your pinned Python dependencies fresh.
Python
7,668
star
3

tablib

Python Module for Tabular Datasets in XLS, CSV, JSON, YAML, &c.
Python
4,586
star
4

django-silk

Silky smooth profiling for Django
Python
4,380
star
5

djangorestframework-simplejwt

A JSON Web Token authentication plugin for the Django REST Framework.
Python
3,957
star
6

django-taggit

Simple tagging for django
Python
3,307
star
7

django-oauth-toolkit

OAuth2 goodies for the Djangonauts!
Python
3,148
star
8

django-redis

Full featured redis cache backend for Django.
Python
2,860
star
9

django-model-utils

Django model mixins and utilities.
Python
2,638
star
10

Watson

⌚ A wonderful CLI to track your time!
Python
2,450
star
11

django-push-notifications

Send push notifications to mobile devices through GCM or APNS in Django.
Python
2,275
star
12

django-simple-history

Store model history and view/revert changes from admin site.
Python
2,189
star
13

django-widget-tweaks

Tweak the form field rendering in templates, not in python-level form definitions. CSS classes and HTML attributes can be altered.
Python
2,077
star
14

sorl-thumbnail

Thumbnails for Django
Python
1,743
star
15

django-constance

Dynamic Django settings.
Python
1,687
star
16

django-two-factor-auth

Complete Two-Factor Authentication for Django providing the easiest integration into most Django projects.
Python
1,679
star
17

django-polymorphic

Improved Django model inheritance with automatic downcasting
Python
1,648
star
18

django-pipeline

Pipeline is an asset packaging library for Django.
Python
1,508
star
19

dj-database-url

Use Database URLs in your Django Application.
Python
1,471
star
20

django-axes

Keep track of failed login attempts in Django-powered sites.
Python
1,463
star
21

prettytable

Display tabular data in a visually appealing ASCII table format
Python
1,336
star
22

django-tinymce

TinyMCE integration for Django
JavaScript
1,270
star
23

django-analytical

Analytics services for Django projects
Python
1,197
star
24

django-admin2

Extendable, adaptable rewrite of django.contrib.admin
Python
1,185
star
25

django-rest-knox

Authentication Module for django rest auth
Python
1,130
star
26

django-waffle

A feature flipper for Django
Python
1,128
star
27

django-smart-selects

chained and grouped selects for django forms
Python
1,125
star
28

django-auditlog

A Django app that keeps a log of changes made to an object.
Python
1,108
star
29

django-configurations

A helper for organizing Django project settings by relying on well established programming patterns.
Python
1,085
star
30

django-defender

A simple super fast django reusable app that blocks people from brute forcing login attempts
Python
1,035
star
31

django-payments

Universal payment handling for Django.
Python
1,023
star
32

django-hosts

Dynamic and static host resolving for Django. Maps hostnames to URLconfs.
Python
977
star
33

django-dbbackup

Management commands to help backup and restore your project database and media files
Python
959
star
34

geojson

Python bindings and utilities for GeoJSON
Python
913
star
35

django-nose

Django test runner using nose
Python
882
star
36

django-newsletter

An email newsletter application for the Django web application framework, including an extended admin interface, web (un)subscription, dynamic e-mail templates, an archive and HTML email support.
Python
845
star
37

django-floppyforms

Full control of form rendering in the templates.
Python
841
star
38

django-avatar

A Django app for handling user avatars.
Python
806
star
39

django-formtools

A set of high-level abstractions for Django forms
Python
790
star
40

django-user-sessions

Extend Django sessions with a foreign key back to the user, allowing enumerating all user's sessions.
Python
616
star
41

django-admin-sortable

Generic drag-and-drop ordering for objects and tabular inlines in Django Admin
Python
564
star
42

django-invitations

Generic invitations app for Django
Python
557
star
43

django-sortedm2m

A transparent sorted ManyToMany field for django.
Python
511
star
44

django-recurrence

Utility for working with recurring dates in Django.
Python
475
star
45

django-categories

This app attempts to provide a generic category system that multiple apps could use. It uses MPTT for the tree storage and provides a custom admin for better visualization (copied and modified from feinCMS).
Python
458
star
46

django-robots

A Django app for managing robots.txt files following the robots exclusion protocol
Python
457
star
47

wagtailmenus

An app to help you manage and render menus in your Wagtail projects more effectively
Python
394
star
48

django-embed-video

Django app for easy embedding YouTube and Vimeo videos and music from SoundCloud.
Python
383
star
49

django-downloadview

Serve files with Django.
Python
378
star
50

django-eav2

Django EAV 2 - EAV storage for modern Django
Python
343
star
51

jsonmodels

jsonmodels is library to make it easier for you to deal with structures that are converted to, or read from JSON.
Python
335
star
52

django-queued-storage

Provides a proxy for Django storage backends that allows you to upload files locally and eventually serve them remotely
Python
316
star
53

django-permission

[Not maintained] An enhanced permission system which support object permission in Django
Python
302
star
54

django-revproxy

Reverse Proxy view that supports all HTTP methods, Diazo transformations and Single Sign-On.
Python
300
star
55

django-authority

A Django app that provides generic per-object-permissions for Django's auth app and helpers to create custom permission checks.
Python
292
star
56

django-simple-menu

Simple, yet powerful, code-based menus for Django applications
Python
264
star
57

django-dbtemplates

Django template loader for database stored templates with extensible cache backend
JavaScript
252
star
58

django-fsm-log

Automatic logging for Django FSM
Python
242
star
59

django-mongonaut

Built from scratch to replicate some of the Django admin functionality and add some more, to serve as an introspective interface for Django and Mongo.
Python
240
star
60

django-cookie-consent

Reusable application for managing various cookies and visitors consent for their use in Django project.
Python
224
star
61

django-celery-monitor

Celery Monitoring for Django
Python
197
star
62

docopt-ng

Humane command line arguments parser. Now with maintenance, typehints, and complete test coverage.
Python
178
star
63

icalevents

Python module for iCal URL/file parsing and querying.
Python
156
star
64

django-voting

A generic voting application for Django
Python
99
star
65

django-ical

iCal feeds for Django based on Django's syndication feed framework.
Python
92
star
66

django-redshift-backend

Redshift database backend for Django
Python
83
star
67

django-flatblocks

django-chunks + headerfield + variable chunknames + "inclusion tag" == django-flatblocks
Python
82
star
68

pathlib2

Backport of pathlib aiming to support the full stdlib Python API.
Python
81
star
69

website

Code for the Jazzband website
Python
66
star
70

django-sorter

A helper app for sorting objects in Django templates.
Python
54
star
71

django-discover-jenkins

A streamlined fork of django-jenkins designed to work with the default test command and the discover runner
Python
49
star
72

django-fernet-encrypted-fields

Python
47
star
73

contextlib2

contextlib2 is a backport of the standard library's contextlib module to earlier Python versions.
Python
38
star
74

imaplib2

Fork of Piers Lauder's imaplib2 library for Python.
Python
33
star
75

help

Use this repo to get help from the roadies
27
star
76

django-postgres-utils

Django app providing additional lookups and functions for PostgreSQL
Python
9
star
77

.github

Community health and config files for Jazzband
7
star
78

admin

Some admin files for Jazzband
3
star
79

actions

Various GitHub actions for Jazzband projects
1
star