Full Code of appliedsec/djangular for AI

master 8d6bc26cd70b cached
45 files
48.1 KB
12.1k tokens
55 symbols
1 requests
Download .txt
Repository: appliedsec/djangular
Branch: master
Commit: 8d6bc26cd70b
Files: 45
Total size: 48.1 KB

Directory structure:
gitextract_gczgbp39/

├── .coveragerc
├── .gitignore
├── .travis.yml
├── LICENSE
├── MANIFEST.in
├── README.md
├── djangular/
│   ├── __init__.py
│   ├── config/
│   │   └── angularseed_template/
│   │       └── angular/
│   │           ├── app.css
│   │           ├── app.js
│   │           ├── components/
│   │           │   └── version/
│   │           │       ├── interpolate-filter.js
│   │           │       ├── interpolate-filter_test.js
│   │           │       ├── version-directive.js
│   │           │       ├── version-directive_test.js
│   │           │       ├── version.js
│   │           │       └── version_test.js
│   │           ├── index.html
│   │           ├── view1/
│   │           │   ├── view1.html
│   │           │   ├── view1.js
│   │           │   └── view1_test.js
│   │           └── view2/
│   │               ├── view2.html
│   │               ├── view2.js
│   │               └── view2_test.js
│   ├── finders.py
│   ├── management/
│   │   ├── __init__.py
│   │   └── commands/
│   │       ├── __init__.py
│   │       └── startangularapp.py
│   ├── middleware.py
│   ├── models.py
│   ├── static/
│   │   └── js/
│   │       └── resource_patch.js
│   ├── storage.py
│   ├── templates/
│   │   └── djangular_module.js
│   ├── tests/
│   │   ├── __init__.py
│   │   ├── test_base.py
│   │   ├── test_commands.py
│   │   ├── test_finders.py
│   │   ├── test_middleware.py
│   │   ├── test_storage.py
│   │   ├── test_urls.py
│   │   ├── test_utils.py
│   │   └── unit/
│   │       └── filterSpec.js
│   ├── urls.py
│   ├── utils.py
│   └── views.py
├── runtests.py
└── setup.py

================================================
FILE CONTENTS
================================================

================================================
FILE: .coveragerc
================================================
[report]
# Regexes for lines to exclude from consideration
exclude_lines =
    # Have to re-enable the standard pragma
    pragma: no cover

    # Don't complain about missing debug-only code:
    def __repr__
    if self\.debug
    def __unicode__
    def __repr__
    if settings.DEBUG
    raise NotImplementedError
    from django\.

    # Don't complain if tests don't hit defensive assertion code:
    raise AssertionError
    raise NotImplementedError

    # Don't complain if non-runnable code isn't run:
    if 0:
    if __name__ == .__main__.:

[run]
omit =
    *tests*
    *migrations*
    *site-packages*
    *src*
    *settings*


================================================
FILE: .gitignore
================================================
*.log
*.pot
*.pyc
local_settings.py

.DS_Store
.idea
.hg
.hgignore

dist
djangular.egg-info

.coverage



================================================
FILE: .travis.yml
================================================
language: python
python:
  - "2.7"
install:
  - pip install coverage
  - pip install $DJANGO
script:
  - coverage run runtests.py
  - coverage report -m
env:
  - DJANGO="Django==1.5.12"
  - DJANGO="Django==1.6.11"
  - DJANGO="Django==1.7.11"
  - DJANGO="Django==1.8.12"
  - DJANGO="Django==1.9.5"


================================================
FILE: LICENSE
================================================
Copyright 2013 Applied Security

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

================================================
FILE: MANIFEST.in
================================================
recursive-include djangular *
include LICENSE
include README.md


================================================
FILE: README.md
================================================
djangular
=========

A reusable app that provides better app integration with AngularJS. Djangular
allows you to create AngularJS content per app, instead of creating a single
massive AngularJS application inside of Django. This allows you to selectively
use apps per site, as well as create a consistent structure across all of your
Django apps.

This is intended to be a Django version of the angular-seed project
(https://github.com/angular/angular-seed). The current mindset is to limit the
amount of changes introduced by Djangular.


Features
--------

+ Allows namespacing AngularJS content per Django app.  This allows the
  AngularJS apps and modules to be included (or not) based on Django's settings,
  and enforces a consistent structure to your Django/AngularJS apps.
+ Includes an AngularJS module that includes a subset of features similar to
  what Django provides in its templates.
+ Adds a patch to AngularJS's $resource module, to enable end of URL slashes
  that Django requires.
+ Improves security by enabling of CSRF protection and JSON Vulnerability
  between Django and AngularJS.
+ ~~Scripts to allow running JS Unit and E2E tests, similar to the Django test
  command.~~ This was removed for the time being and will be (re-)included in a
  future release.
+ Does not dictate how you use AngularJS inside your Django app.


Requirements
------------

+ Currently requires Python 2.7.
+ Supports Django >= 1.5, <= 1.9
+ Supports AngularJS 1.2+ (including 1.3.x).
+ ~~Local installs of Node.js and Karma for testing.~~


Installation
------------

+ You may install directly from pypi:

        pip install djangular

+ Or download the source and install it in a terminal/console:

        python setup.py install

+ Or download the source and move the djangular directory inside your django
  project as an app (this is the least recommended approach).

+ Djangular needs to be placed as an app inside a Django project and added to
  the INSTALLED_APPS setting.

        INSTALLED_APPS = (
            ...
            'djangular',
            ...
        )

+ You will need to obtain a version of AngularJS and place it in the `static`
  folder of one of your Django apps.  Djangular no longer includes a version of
  AngularJS, since it updates too frequently.


Including AngularJS content in your Django Apps
-----------------------------------------------

The most popular feature of Djangular, this will both include and namespace your
AngularJS content inside your Django apps.  Each Django app has its own
"angular" folder, with a layout matching the angular-seed project. As a result,
the URLs for these get grouped into the `STATIC_URL` structure of Django.

+ The staticfiles contrib library will need to be included in the INSTALLED_APPS
  setting.

        INSTALLED_APPS = (
            ...
            'django.contrib.staticfiles',
            'djangular',
            ...
        )

+ The STATICFILES_FINDERS needs to be updated to include
  `djangular.finders.NamespacedAngularAppDirectoriesFinder`.

        STATICFILES_FINDERS = (
            'django.contrib.staticfiles.finders.FileSystemFinder',
            'django.contrib.staticfiles.finders.AppDirectoriesFinder',
            'djangular.finders.NamespacedAngularAppDirectoriesFinder'
        )

+ Because of this new finder, the `findstatic` and `collectstatic` commands will
  place the angular files in each app in an associated an `<app_name>/` folder.
  You will not need to namespace each of your static directories with the name
  of your Django application (unless you really want to).
    * Example: If you have a Django app named `foo` and you are using the
      default `STATIC_URL` in your settings, the main AngularJS module named
      `foo` would be found at `foo/angular/app.js` on the file system and at
      `static/foo/app.js` from the browser.
    * This namespacing is done automatically.  This a `foo` app and a `bar` app
      can both have an `app.js` inside their `angular` directories, and they
      will not collide.
    * Note: Because of these URLs, referring to AngularJS content in a separate
      app should use a `../<separate_app>/` URL. This will help significantly
      during testing to make sure paths are correct.
    * Note: It is recommended to namespace the AngularJS code the same name as
      the Django app. The created JS files do this already.

+ To create an app that is already setup with the djangular (or angular-seed)
  structure, run `python manage.py startangularapp <app_name>` from the command
  line. This will create the files and directory structures needed for you to
  get started.


Including some Django template-like features in your AngularJS templates
------------------------------------------------------------------------

One of the challenges in using AngularJS inside of Django is that you may not
have access to some needed variables that are always included in Django
templates.  Djangular includes an AngularJS module to help with that.

+ To use the AngularJS module that Djangular provides you, you'll need to add
  the djangular app to your projects URLs.

        urlpatterns = patterns('',
            ...
            url(r'^djangular/', include('djangular.urls')),
            ...
        )

+ Alternatively, you may specify the DjangularModuleTemplateView specifically,
  and customize the url.

        from djangular.views import DjangularModuleTemplateView
        ...

        urlpatterns = patterns('',
            ...
            url(r'<custom_path>/djangular.js',
                DjangularModuleTemplateView.as_view()),
            ...
        )

This will add a `djangular` AngularJS module to your front end code.  This
module includes a `DjangoProperties` constant that includes whether the current
user is authenticated, the username, groups and roles of the current user and
the static and media urls from Django settings.  It also includes a `django`
filter, which does some basic substitution based on the properties constant.


Enforcing the end slashes of your AngularJS Resources
-----------------------------------------------------

$resource is a convenient way to create REST-like services in AngularJS.
However, there currently
[is a bug](https://github.com/angular/angular.js/issues/992) in $resource that
will strip the ending slash, which means that $resource is unusable unless
`settings.APPEND_SLASHES` is set to `FALSE`.

Djangular used to patch this automatically, but it now includes a separate file
(`djangular/static/js/resource_patch.js`) to handle this issue.  Simply include
that javascript file in your page after you have loaded `angular-resource.js`
and ending slashes will be preserved in $resource.


Enabling CSRF protection in AngularJS Templates
-----------------------------------------------

Djangular includes a JSON Vulnerability middleware that AngularJS knows how to
process. To include this protection, add
`djangular.middleware.AngularJsonVulnerabilityMiddleware` to the
`MIDDLEWARE_CLASSES` setting. This only affects JSON requests (based on
Content-Type), so this can be located fairly low in the middleware stack.

        MIDDLEWARE_CLASSES = (
            ...
            'djangular.middleware.AngularJsonVulnerabilityMiddleware'
        )

Once you have enabled CSRF protection in Django by adding the middleware
`django.middleware.csrf.CsrfViewMiddleware` to the `MIDDLEWARE_CLASSES` setting,
you may use the same protection in AngularJS templates in addition to Django
template.  There are two different ways to enable this protection via djangular:

+ Make your main app dependent on the `djangular` module and use the included
  `csrf-token` directive (that wraps the Django `csrf_token` template tag)
  inside the appropriate `form` tags in your HTML.

        // Inside your JavaScript
        angular.module('myApp', ['djangular', ...]);
        ...
        <!-- In your AngularJS Template -->
        <div ng-app="my-app">
            ...
            <form ...>
                <csrf-token></csrf-token>
            </form>
        </div>

+ Make your main app dependent on the `djangular.csrf`, which will add the
  appropriate CSRF Token Header in all POSTs, PUTs and DELETEs.  Note that this
  way is vulnerable to cross-site scripting if you make a post to a domain
  outside your control.

        angular.module('myApp', ['djangular.csrf', ...]);

If you allow a user to login (or logout) and don't redirect or reload the page,
the tags and cookies provided by both methods above will be stale.  The second
option (using the `djangular.csrf` module) provides a `UpdateCSRFToken` function
that can be invoked with the new CSRF Token value.


Using Djangular in your Django Project
--------------------------------------

This section describes some best practices in using Djangular. Please note that
these are guidelines and recommendations, but not the only way to use this
project.

#### AngularJS as purely static content ####

The first way to use djangular is to have all of your static content live inside
an angular app. This is perhaps the "most correct" way from an AngularJS
standpoint and perhaps the "least correct" way from a traditional Django
perspective.

In doing this, you are only (or almost only) serving content from your static
domain and your Django development becomes strictly back-end focused for REST
and/or service calls. Few to none of your Django views will produce HTML. You
can provide a redirect from a Django view to your static pages (if you like),
although this can seem strange when your static content is served from a
completely different domain. You may need to configure your web servers to
allow remote Ajax calls from your static domain.

This approach allows you to use AngularJS with any number of back-ends, as
(again) your Django app becomes an API for your AngularJS code to call. This
approach can be very different from how your application is currently
architected.

From our experience, if you decide to do this, we would recommend using local,
relative URLs to navigate between the apps instead of specifying the full URL.
However, there are times when you will need to specify the full URL.

There is an AngularJS module called `djangular` that is rendered via the Django
templating engine to obtain common template variables like the `STATIC_URL`,
`MEDIA_URL`, the User object, etc.  This app includes a service called
`DjangoProperties`, which will enable you to get access to those variables, and
a `django` filter, which follows the standard AngularJS filtering rules. The URL
for this JavaScript is `/djangular/app.js` (note that is not static).

The following is a sample route config that uses the aforementioned djangular
angular app. Because AngularJS has not set up the $filter directive during the
route configuration, the DjangoProperties constant is the only way to obtain the
STATIC_URL. Using 'sample' as the name of the Django/AngularJS app:

```javascript
angular.module('sample', [
    'djangular', 'sample.filters', 'sample.services', 'sample.directives',
    'sample.controllers'
    ]).config([
        '$routeProvider','DjangoProperties',
        function($routeProvider, DjangoProperties) {
            $routeProvider.when('/view1', {
                templateUrl: DjangoProperties.STATIC_URL +
                    'sample/view1/view1.html', controller: 'View1Ctrl'});
            $routeProvider.when('/view2', {
                templateUrl: DjangoProperties.STATIC_URL +
                    'sample/view2/view2.html', controller: 'View2Ctrl'});
            $routeProvider.otherwise({redirectTo: '/view1'});
        }
    ]);
```

#### Django Templates as AngularJS Templates ####

Another way to integrate is to use your Django templates as your AngularJS
templates. To do this, we highly recommend using Django 1.5 and heavy use of
the `{% verbatim %}` tag, since the Django and AngularJS templating syntaxes are
identical.

The big advantage of this is that it allows you to use all of the existing
template tags and ways of thinking that you are accustomed to using. If you are
integrating AngularJS into an existing Django project, this will seem the most
appealing.

The downsides to this method are the following:
+ The AngularJS developers recommend not doing this, because it is very easy
  to get confused about which part of the template is being rendered on the
  server side and which is being rendered on the client side. Almost every
  developer on our team has tripped on this once or twice.
+ The vast majority of HTML that your app is producing is the same on every
  load... and should be static. However, without some cache configuration, the
  server will have to render the content on every single request, resulting in
  poorer performance.

#### Using Django Templates to render the skeleton of the app ####

What our team currently does is use a Django Template to render the skeleton of
every page, but the rest of the page (the partials, CSS and JS) are all included
in the AngularJS app. This way, none of the CSS/JS dependencies are duplicated
in multiple places.

When our app renders the content, we pass in two variables to the RequestContext
(and thus, to the template). The `app_name`, which is the name of the app, and
`app_dependencies`, which is a list of app names whom the AngularJS app is
dependent on. We make heavy use of Django Rest Framework
(http://django-rest-framework.org/) to produce our views/REST Services and
Django Pipeline (https://github.com/cyberdelia/django-pipeline) to do our app
packaging and JS/CSS Compression.

The template (more or less) looks like the following:
```html
{% load compressed %}  <!-- We use django-pipeline to do our packaging -->

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>App Title</title>
	<link rel="shortcut icon" href="{{ STATIC_URL }}images/app.ico" />

    <!--CSS imports-->
    {% for dependency in app_dependencies %}
        {% compressed_css dependency %}
    {% endfor %}
    {% compressed_css app_name %}

    <!--AngularJS library imports-->
    <script src="{{ STATIC_URL }}angular/angular-min.js"></script>

    <!--AngularJS app imports-->
    <script src="/djangular/app.js"></script>  <!-- The djangular app. -->
    {% for dependency in app_dependencies %}
        {% compressed_js dependency %}
    {% endfor %}
    {% compressed_js app_name %}

</head>
<body ng-app="{{app_name}}">
    <div class="app" ng-view>
    </div>
</body>
</html>
```

================================================
FILE: djangular/__init__.py
================================================


================================================
FILE: djangular/config/angularseed_template/angular/app.css
================================================
/* app css stylesheet */

.menu {
  list-style: none;
  border-bottom: 0.1em solid black;
  margin-bottom: 2em;
  padding: 0 0 0.5em;
}

.menu:before {
  content: "[";
}

.menu:after {
  content: "]";
}

.menu > li {
  display: inline;
}

.menu > li:before {
  content: "|";
  padding-right: 0.3em;
}

.menu > li:nth-child(1):before {
  content: "";
  padding: 0;
}


================================================
FILE: djangular/config/angularseed_template/angular/app.js
================================================
'use strict';

// Declare app level module which depends on views, and components
angular.module('{{ app_name }}', [
  'ngRoute',
  '{{ app_name }}.view1',
  '{{ app_name }}.view2',
  '{{ app_name }}.version'
]).
config(['$routeProvider', function($routeProvider) {
  $routeProvider.otherwise({redirectTo: '/view1'});
}]);


================================================
FILE: djangular/config/angularseed_template/angular/components/version/interpolate-filter.js
================================================
'use strict';

angular.module('{{ app_name }}.version.interpolate-filter', [])

.filter('interpolate', ['version', function(version) {
  return function(text) {
    return String(text).replace(/\%VERSION\%/mg, version);
  };
}]);


================================================
FILE: djangular/config/angularseed_template/angular/components/version/interpolate-filter_test.js
================================================
'use strict';

describe('{{ app_name }}.version module', function() {
  beforeEach(module('{{ app_name }}.version'));

  describe('interpolate filter', function() {
    beforeEach(module(function($provide) {
      $provide.value('version', 'TEST_VER');
    }));

    it('should replace VERSION', inject(function(interpolateFilter) {
      expect(interpolateFilter('before %VERSION% after')).toEqual('before TEST_VER after');
    }));
  });
});


================================================
FILE: djangular/config/angularseed_template/angular/components/version/version-directive.js
================================================
'use strict';

angular.module('{{ app_name }}.version.version-directive', [])

.directive('appVersion', ['version', function(version) {
  return function(scope, elm, attrs) {
    elm.text(version);
  };
}]);


================================================
FILE: djangular/config/angularseed_template/angular/components/version/version-directive_test.js
================================================
'use strict';

describe('{{ app_name }}.version module', function() {
  beforeEach(module('{{ app_name }}.version'));

  describe('app-version directive', function() {
    it('should print current version', function() {
      module(function($provide) {
        $provide.value('version', 'TEST_VER');
      });
      inject(function($compile, $rootScope) {
        var element = $compile('<span app-version></span>')($rootScope);
        expect(element.text()).toEqual('TEST_VER');
      });
    });
  });
});


================================================
FILE: djangular/config/angularseed_template/angular/components/version/version.js
================================================
'use strict';

angular.module('{{ app_name }}.version', [
  '{{ app_name }}.version.interpolate-filter',
  '{{ app_name }}.version.version-directive'
])

.value('version', '0.1');


================================================
FILE: djangular/config/angularseed_template/angular/components/version/version_test.js
================================================
'use strict';

describe('{{ app_name }}.version module', function() {
  beforeEach(module('{{ app_name }}.version'));

  describe('version service', function() {
    it('should return current version', inject(function(version) {
      expect(version).toEqual('0.1');
    }));
  });
});


================================================
FILE: djangular/config/angularseed_template/angular/index.html
================================================
<!DOCTYPE html>
<!--[if lt IE 7]>      <html lang="en" ng-app="{{ app_name }}" class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html lang="en" ng-app="{{ app_name }}" class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html lang="en" ng-app="{{ app_name }}" class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html lang="en" ng-app="{{ app_name }}" class="no-js"> <!--<![endif]-->
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>My AngularJS App</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="bower_components/html5-boilerplate/css/normalize.css">
  <link rel="stylesheet" href="bower_components/html5-boilerplate/css/main.css">
  <link rel="stylesheet" href="app.css">
  <script src="bower_components/html5-boilerplate/js/vendor/modernizr-2.6.2.min.js"></script>
</head>
<body>
  <ul class="menu">
    <li><a href="#/view1">view1</a></li>
    <li><a href="#/view2">view2</a></li>
  </ul>

  <!--[if lt IE 7]>
      <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
  <![endif]-->

  <div ng-view></div>

  <div>Angular seed app: v<span app-version></span></div>

  <!-- In production use:
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/x.x.x/angular.min.js"></script>
  -->
  <script src="bower_components/angular/angular.js"></script>
  <script src="bower_components/angular-route/angular-route.js"></script>
  <script src="app.js"></script>
  <script src="view1/view1.js"></script>
  <script src="view2/view2.js"></script>
  <script src="components/version/version.js"></script>
  <script src="components/version/version-directive.js"></script>
  <script src="components/version/interpolate-filter.js"></script>
</body>
</html>


================================================
FILE: djangular/config/angularseed_template/angular/view1/view1.html
================================================
<p>This is the partial for view 1.</p>


================================================
FILE: djangular/config/angularseed_template/angular/view1/view1.js
================================================
'use strict';

angular.module('{{ app_name }}.view1', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view1', {
    templateUrl: 'view1/view1.html',
    controller: 'View1Ctrl'
  });
}])

.controller('View1Ctrl', [function() {

}]);

================================================
FILE: djangular/config/angularseed_template/angular/view1/view1_test.js
================================================
'use strict';

describe('{{ app_name }}.view1 module', function() {

  beforeEach(module('{{ app_name }}.view1'));

  describe('view1 controller', function(){

    it('should ....', inject(function($controller) {
      //spec body
      var view1Ctrl = $controller('View1Ctrl');
      expect(view1Ctrl).toBeDefined();
    }));

  });
});

================================================
FILE: djangular/config/angularseed_template/angular/view2/view2.html
================================================
{% verbatim %}
<p>This is the partial for view 2.</p>
<p>
  Showing of 'interpolate' filter:
  {{ 'Current version is v%VERSION%.' | interpolate }}
</p>
{% endverbatim %}


================================================
FILE: djangular/config/angularseed_template/angular/view2/view2.js
================================================
'use strict';

angular.module('{{ app_name }}.view2', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view2', {
    templateUrl: 'view2/view2.html',
    controller: 'View2Ctrl'
  });
}])

.controller('View2Ctrl', [function() {

}]);

================================================
FILE: djangular/config/angularseed_template/angular/view2/view2_test.js
================================================
'use strict';

describe('{{ app_name }}.view2 module', function() {

  beforeEach(module('{{ app_name }}.view2'));

  describe('view2 controller', function(){

    it('should ....', inject(function($controller) {
      //spec body
      var view2Ctrl = $controller('View2Ctrl');
      expect(view2Ctrl).toBeDefined();
    }));

  });
});

================================================
FILE: djangular/finders.py
================================================
import django
from django.contrib.staticfiles import finders as s_finders

# Django rewrote the staticfiles storage internals in 1.7, so...
if django.get_version() >= '1.7':
    import os
    import re

    class NamespacedAppDirectoriesFinder(s_finders.AppDirectoriesFinder):
        """
        A namedspace static files finder that looks in the angular directory of
        each app as specified in the source_dir attribute.
        """
        prepend_source_dir = False

        def __init__(self, app_names=None, *args, **kwargs):
            super(NamespacedAppDirectoriesFinder, self).__init__(
                app_names, *args, **kwargs)

            for app_name, storage in self.storages.items():
                storage.prefix = os.path.join(*(app_name.split('.')))

        def find_in_app(self, app, path):
            if self.prepend_source_dir:
                prefixed_path = os.path.join(self.source_dir, *(app.split('.')))
            else:
                prefixed_path = os.path.join(*(app.split('.')))

            app_re = '^{}{}'.format(prefixed_path, os.sep)
            if re.match(app_re, path):
                return super(NamespacedAppDirectoriesFinder, self).find_in_app(
                    app, re.sub(app_re, '', path)
                )

    class NamespacedAngularAppDirectoriesFinder(NamespacedAppDirectoriesFinder):
        """
        A static files finder that looks in the angular directory of each app.
        """
        source_dir = 'angular'

    class NamespacedE2ETestAppDirectoriesFinder(NamespacedAppDirectoriesFinder):
        """
        A static files finder that looks in the tests/e2e directory of each app.
        """
        source_dir = os.path.join('tests', 'e2e')
        prepend_source_dir = True

else:
    from . import storage

    class NamespacedAngularAppDirectoriesFinder(s_finders.AppDirectoriesFinder):
        """
        A static files finder that looks in the angular directory of each app.
        """
        storage_class = storage.NamespacedAngularAppStorage

    class NamespacedE2ETestAppDirectoriesFinder(s_finders.AppDirectoriesFinder):
        """
        A static files finder that looks in the tests/e2e directory of each app.
        """
        storage_class = storage.NamespacedE2ETestAppStorage

    class NamespacedLibTestAppDirectoriesFinder(s_finders.AppDirectoriesFinder):
        """
        A static files finder that looks in the tests/lib directory of each app.
        """
        storage_class = storage.NamespacedLibTestAppStorage

================================================
FILE: djangular/management/__init__.py
================================================


================================================
FILE: djangular/management/commands/__init__.py
================================================


================================================
FILE: djangular/management/commands/startangularapp.py
================================================
import django
import os

from django.core import management as mgmt
from django.core.management.templates import TemplateCommand
from djangular import utils


class Command(utils.SiteAndPathUtils, TemplateCommand):
    help = ("Creates a Djangular app directory structure for the given app "
            "name in the current directory or optionally in the given "
            "directory.")

    if django.get_version() >= "1.7":
        requires_system_checks = False
    else:
        requires_model_validation = False

    def handle(self, name, target=None, **options):
        mgmt.call_command('startapp', name, target, **options)

        # Override the options to setup the template command.
        options.update({
            'template': os.path.join(
                self.get_djangular_root(), 'config', 'angularseed_template'),
            'extensions': ['.html', '.js'],  # Parse HTML And JS files
            'files': ['app.css']
        })

        super(Command, self).handle(
            'app', name, target or name, **options)


================================================
FILE: djangular/middleware.py
================================================

class AngularJsonVulnerabilityMiddleware(object):
    """
    A middleware that inserts the AngularJS JSON Vulnerability request on JSON responses.
    """
    # The AngularJS JSON Vulnerability content prefix. See http://docs.angularjs.org/api/ng.$http
    CONTENT_PREFIX = b")]}',\n"

    # Make this class easy to extend by allowing class level access.
    VALID_STATUS_CODES = [200, 201, 202]
    VALID_CONTENT_TYPES = ['application/json']

    def process_response(self, request, response):
        if response.status_code in self.VALID_STATUS_CODES and response['Content-Type'] in self.VALID_CONTENT_TYPES:
            response.content = self.CONTENT_PREFIX + response.content

        return response

================================================
FILE: djangular/models.py
================================================
# No models needed.

================================================
FILE: djangular/static/js/resource_patch.js
================================================
try {
    if (angular.version.full > "1.3") {
        angular.module('ngResource').config([
            '$resourceProvider', function($resourceProvider) {
                $resourceProvider.defaults.stripTrailingSlashes = false;
            }
        ]);
    } else {
        angular.module('ngResource').config([
            '$provide', '$httpProvider',
            function($provide, $httpProvider) {
                $provide.decorator('$resource', function($delegate) {
                    return function() {
                        if (arguments.length > 0) {  // URL
                            arguments[0] = arguments[0].replace(/\/$/, '\\/');
                        }

                        if (arguments.length > 2) {  // Actions
                            angular.forEach(arguments[2], function(action) {
                                if (action && action.url) {
                                    action.url = action.url.replace(/\/$/, '\\/');
                                }
                            });
                        }

                        return $delegate.apply($delegate, arguments);
                    };
                });

                $provide.factory('djangularEnforceSlashInterceptor', function() {
                    return {
                        request: function(config) {
                            config.url = config.url.replace(/[\/\\]+$/, '/');
                            return config;
                        }
                    };
                });

                $httpProvider.interceptors.push('djangularEnforceSlashInterceptor');
            }
        ]);
    }
} catch (err) {
    console.log('The ngResource module could not be found.');
}

================================================
FILE: djangular/storage.py
================================================
import django

if django.get_version() < '1.7':
    import os
    from re import sub

    from django.contrib.staticfiles.storage import AppStaticStorage

    class NamespacedAngularAppStorage(AppStaticStorage):
        """
        A file system storage backend that takes an app module and works
        for the ``app`` directory of it.  The app module will be included
        in the url for the content.
        """
        source_dir = 'angular'

        def __init__(self, app, *args, **kwargs):
            """
            Returns a static file storage if available in the given app.
            """
            # app is the actual app module
            self.prefix = os.path.join(*(app.split('.')))
            super(NamespacedAngularAppStorage, self).__init__(app, *args, **kwargs)

        def path(self, name):
            name = sub('^' + self.prefix + os.sep.encode('string-escape'), '', name)
            return super(NamespacedAngularAppStorage, self).path(name)


    class NamespacedE2ETestAppStorage(AppStaticStorage):
        """
        A file system storage backend that takes an app module and works
        for the ``tests/e2e`` directory of it.  The app module will be included
        in the url for the content.  NOTE: This should only be used for
        end-to-end testing.
        """
        source_dir = os.path.join('tests', 'e2e')

        def __init__(self, app, *args, **kwargs):
            """
            Returns a static file storage if available in the given app.
            """
            # app is the actual app module
            prefix_args = [self.source_dir] + app.split('.')
            self.prefix = os.path.join(*prefix_args)
            super(NamespacedE2ETestAppStorage, self).__init__(app, *args, **kwargs)


    class NamespacedLibTestAppStorage(AppStaticStorage):
        """
        A file system storage backend that takes an app module and works
        for the ``tests/lib`` directory of it.  The app module will be included
        in the url for the content.  NOTE: This should only be used for
        end-to-end testing.
        """
        source_dir = os.path.join('tests', 'lib')

        def __init__(self, app, *args, **kwargs):
            """
            Returns a static file storage if available in the given app.
            """
            # app is the actual app module
            prefix_args = app.split('.') + ['lib']
            self.prefix = os.path.join(*prefix_args)
            super(NamespacedLibTestAppStorage, self).__init__(app, *args, **kwargs)


================================================
FILE: djangular/templates/djangular_module.js
================================================
// All template syntax is commented so this can be loaded as a normal JS file.
// {% load static %}
var djangular = angular.module('djangular', []).
    constant('DjangoProperties', {
        'STATIC_URL': '{% get_static_prefix %}',
        'MEDIA_URL': '{% get_media_prefix %}',
        'USER_NAME': '{{ user.username|escapejs }}',
        'GROUP_NAMES': [ // {% for group in user.groups.all %}
            '{{ group.name|escapejs }}', // {% endfor %}
        ],
        'IS_AUTHENTICATED': 'True' === '{{ user.is_authenticated|escapejs }}',
        'IS_STAFF': 'True' === '{{ user.is_staff }}',
        'IS_SUPERUSER': 'True' === '{{ user.is_superuser }}'
    }).
    filter('django', ['DjangoProperties', function(DjangoProperties) {
        return function(text) {
            for (var constant in DjangoProperties) {
                text = text.replace('%' + constant + '%', DjangoProperties[constant]);
                text = text.replace(constant, DjangoProperties[constant]);
            }
            return text;
        }
    }]).
    directive('djangoHref', ['$filter', function($filter) {
        return {
            restrict: 'A',
            priority: 99, // same as ng-href
            link: function(scope, elem, attrs) {
                attrs.$observe('djangoHref', function(value) {
                    if (!value) return;
                    attrs.$set('href', $filter('django')(value));
                });
            }
        };
    }]).
    directive('djangoSrc', ['$filter', function($filter) {
        return {
            restrict: 'A',
            priority: 99, // same as ng-src
            link: function(scope, elem, attrs) {
                attrs.$observe('djangoSrc', function(value) {
                    if (!value) return;
                    attrs.$set('src', $filter('django')(value));
                });
            }
        };
    }]).
    directive('csrfToken', function() {
        return {
            restrict: 'E',
            template: "{% csrf_token %}" || "<span></span>",
            replace: true
        };
    });

// {% if not disable_csrf_headers %}
// Assign the CSRF Token as needed, until Angular provides a way to do this properly (https://github.com/angular/angular.js/issues/735)
var djangularCsrf = angular.module('djangular.csrf', ['ngCookies']).
    config(['$httpProvider', function($httpProvider) {
        // cache $httpProvider, as it's only available during config...
        djangularCsrf.$httpProvider = $httpProvider;
    }]).
    factory('UpdateCsrfToken', function() {
        return function(csrfToken) {
            djangularCsrf.$httpProvider.defaults.headers.post['X-CSRFToken'] = csrfToken;
            djangularCsrf.$httpProvider.defaults.headers.put['X-CSRFToken'] = csrfToken;
            if (!djangularCsrf.$httpProvider.defaults.headers.delete)
                djangularCsrf.$httpProvider.defaults.headers.delete = {};
            djangularCsrf.$httpProvider.defaults.headers.delete['X-CSRFToken'] = csrfToken;
        };
    }).
    run(['$cookies', 'UpdateCsrfToken', function($cookies, UpdateCsrfToken) {
        UpdateCsrfToken($cookies['csrftoken']);
    }]);
// {% endif %}


================================================
FILE: djangular/tests/__init__.py
================================================
import django

if django.VERSION < (1, 6):
    from djangular.tests.test_base import *
    from djangular.tests.test_finders import *
    from djangular.tests.test_middleware import *
    from djangular.tests.test_storage import *
    from djangular.tests.test_utils import *
    from djangular.tests.test_commands import *
    from djangular.tests.test_urls import *


================================================
FILE: djangular/tests/test_base.py
================================================
import django
import os

from django.test import SimpleTestCase

BASE_DIR = os.path.abspath(os.path.dirname(__file__))


def _call_test_func(self, test_fn):
    apps = None
    need_to_call_unset = False

    if django.get_version() >= '1.7':
        from django.apps import apps

        if not apps.is_installed('djangular.config.angularseed_template'):
            apps.set_installed_apps(tuple([
                'djangular.config.angularseed_template']))
            need_to_call_unset = True

    try:
        test_fn(self)
    finally:
        if apps and need_to_call_unset:
            apps.unset_installed_apps()


def test_with_angularseed_template_as_django_app(test_fn):
    def fn(self):
        extra_init_py_files = []
        try:
            # Temporarily make the template dirs into python modules by adding
            # the __init__.py files.
            for directory in [
                    'config', os.path.join('config', 'angularseed_template')]:
                current_file_name = os.path.join(
                    BASE_DIR, '..', directory, '__init__.py')
                current_file = open(current_file_name, 'w')
                extra_init_py_files.append(current_file)
                current_file.close()

        except Exception as e:
            self.fail('Could not create files due to {0}'.format(e.message))

        else:
            _call_test_func(self, test_fn)

        finally:
            for py_file in extra_init_py_files:
                if os.path.exists(py_file.name):
                    os.remove(py_file.name)

                compiled_file_name = '{0}c'.format(py_file.name)
                if os.path.exists(compiled_file_name):
                    os.remove(compiled_file_name)

    return fn


class TestAngularSeedAsPythonModuleTest(SimpleTestCase):

    @test_with_angularseed_template_as_django_app
    def test_init_py_created(self):
        self.assertTrue(os.path.exists('{0}/../config/__init__.py'.format(BASE_DIR)))

================================================
FILE: djangular/tests/test_commands.py
================================================
import os
import shutil

from django.test import TestCase
from django.utils._os import upath

from djangular.management.commands.startangularapp import Command as StartAngularAppCommand


class StartAngularAppCommandTests(TestCase):
    def setUp(self):
        # Clean up app directory that is created
        test_dir = os.path.abspath(os.path.dirname(upath(__file__)))
        demo_app_path = os.path.join(test_dir, '../../demo')
        self.addCleanup(shutil.rmtree, demo_app_path)

    def test_runs(self):
        StartAngularAppCommand().handle('demo', verbosity=1)


================================================
FILE: djangular/tests/test_finders.py
================================================
import django
import os

from djangular.tests.test_base import test_with_angularseed_template_as_django_app
from djangular import finders
from django.test import SimpleTestCase

APP_BASE_DIR = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))


class NamespacedAngularAppDirectoriesFinderTest(SimpleTestCase):
    @test_with_angularseed_template_as_django_app
    def test_find(self):
        if django.get_version() >= '1.7':
            finder = finders.NamespacedAngularAppDirectoriesFinder(
                app_names=['djangular.config.angularseed_template'])
        else:
            finder = finders.NamespacedAngularAppDirectoriesFinder(
                apps=['djangular.config.angularseed_template'])

        self.assertEqual(
            finder.find('djangular/config/angularseed_template/index.html'),
            '{0}/config/angularseed_template/angular/index.html'.format(
                APP_BASE_DIR)
        )


class NamespacedE2ETestAppDirectoriesFinderTest(SimpleTestCase):

    @test_with_angularseed_template_as_django_app
    def test_find(self):
        self.skipTest('E2E Testing is not implemented yet...')

        if django.get_version() >= '1.7':
            finder = finders.NamespacedE2ETestAppDirectoriesFinder(
                app_names=['djangular.config.angularseed_template'])
        else:
            finder = finders.NamespacedE2ETestAppDirectoriesFinder(
                apps=['djangular.config.angularseed_template'])

        self.assertEqual(
            finder.find(
                'tests/e2e/djangular/config/angularseed_template/runner.html'),
            '{0}/config/angularseed_template/tests/e2e/runner.html'.format(
                APP_BASE_DIR)
        )


================================================
FILE: djangular/tests/test_middleware.py
================================================
from djangular import middleware

from django.test import SimpleTestCase
from django.http import HttpRequest, HttpResponse


class AngularJsonVulnerabilityMiddlewareTest(SimpleTestCase):

    def test_that_middleware_does_nothing_to_html_requests(self):
        resp = HttpResponse(content_type='text/html', content='<html></html>')
        mware = middleware.AngularJsonVulnerabilityMiddleware()
        mware.process_response(HttpRequest(), resp)

        self.assertEqual(resp.content, '<html></html>')

    def test_that_middleware_does_nothing_to_js_requests(self):
        resp = HttpResponse(content_type='text/javascript', content='var blah = [];')
        mware = middleware.AngularJsonVulnerabilityMiddleware()
        mware.process_response(HttpRequest(), resp)

        self.assertEqual(resp.content, 'var blah = [];')

    def test_that_middleware_does_nothing_to_invalid_json_requests(self):
        resp = HttpResponse(content_type='application/json', content='[1, 2, 3]', status=400)
        mware = middleware.AngularJsonVulnerabilityMiddleware()
        mware.process_response(HttpRequest(), resp)

        self.assertEqual(resp.content, '[1, 2, 3]')

    def test_that_middleware_adds_prefix_to_valid_json_requests(self):
        resp = HttpResponse(content_type='application/json', content='[1, 2, 3]')
        mware = middleware.AngularJsonVulnerabilityMiddleware()
        mware.process_response(HttpRequest(), resp)

        self.assertEqual(resp.content, mware.CONTENT_PREFIX + '[1, 2, 3]')


================================================
FILE: djangular/tests/test_storage.py
================================================
import django

if django.get_version() < '1.7':
    from djangular import storage
    from django.test import SimpleTestCase

    from djangular.tests.test_base import test_with_angularseed_template_as_django_app

    class NamespacedAppAngularStorageTest(SimpleTestCase):
        def test_source_dir_is_angular(self):
            self.assertEqual(
                storage.NamespacedAngularAppStorage.source_dir, 'angular')

        def test_prefix_is_given_app_name(self):
            app_storage = storage.NamespacedAngularAppStorage('djangular')
            self.assertEqual(app_storage.prefix, 'djangular')

        @test_with_angularseed_template_as_django_app
        def test_prefix_is_given_app_name_for_more_complicated_scenario(self):
            app_storage = storage.NamespacedAngularAppStorage(
                'djangular.config.angularseed_template')
            self.assertEqual(app_storage.prefix,
                             'djangular/config/angularseed_template')


    class NamespacedE2ETestAppStorageTest(SimpleTestCase):
        def test_source_dir_is_tests(self):
            self.assertEqual(
                storage.NamespacedE2ETestAppStorage.source_dir, 'tests/e2e')

        def test_prefix_is_given_app_name(self):
            app_storage = storage.NamespacedE2ETestAppStorage('djangular')
            self.assertEqual(app_storage.prefix, 'tests/e2e/djangular')

        @test_with_angularseed_template_as_django_app
        def test_prefix_is_given_app_name_for_more_complicated_scenario(self):
            app_storage = storage.NamespacedE2ETestAppStorage(
                'djangular.config.angularseed_template')
            self.assertEqual(app_storage.prefix,
                             'tests/e2e/djangular/config/angularseed_template')

================================================
FILE: djangular/tests/test_urls.py
================================================
from django.core.urlresolvers import reverse
from django.test import TestCase


class UrlsTests(TestCase):
    def test_urls_import(self):
        """Smoke test to make sure urls imports are valid."""
        self.assertEqual('/app.js', reverse('djangular-module'))


================================================
FILE: djangular/tests/test_utils.py
================================================
import os

from djangular import utils
from django.test import SimpleTestCase


class SiteAndPathUtilsTest(SimpleTestCase):

    site_utils = utils.SiteAndPathUtils()

    def test_djangular_root(self):
        current_dir = os.path.dirname(os.path.abspath(__file__))
        djangular_dir = os.path.dirname(current_dir)
        self.assertEqual(djangular_dir, self.site_utils.get_djangular_root())


================================================
FILE: djangular/tests/unit/filterSpec.js
================================================
'use strict';

/* jasmine specs for filters go here */

describe('filter', function() {
    beforeEach(module('djangular'));

    describe('django', function() {
        it('should replace STATIC_URL inside of percent signs', inject(function(djangoFilter) {
            expect(djangoFilter('before %STATIC_URL% after')).
                toEqual('before {% get_static_prefix %} after');
        }));

        it('should replace STATIC_URL without percent signs', inject(function(djangoFilter) {
            expect(djangoFilter('before STATIC_URL after')).
                toEqual('before {% get_static_prefix %} after');
        }));

        it('should replace MEDIA_URL inside of percent signs', inject(function(djangoFilter) {
            expect(djangoFilter('before %MEDIA_URL% after')).
                toEqual('before {% get_media_prefix %} after');
        }));

        it('should replace MEDIA_URL without percent signs', inject(function(djangoFilter) {
            expect(djangoFilter('before MEDIA_URL after')).
                toEqual('before {% get_media_prefix %} after');
        }));

        it('should replace USER_NAME inside of percent signs', inject(function(djangoFilter) {
            expect(djangoFilter('before %USER_NAME% after')).
                toEqual('before {{ user.username|escapejs }} after');
        }));

        it('should replace USER_NAME without percent signs', inject(function(djangoFilter) {
            expect(djangoFilter('before USER_NAME after')).
                toEqual('before {{ user.username|escapejs }} after');
        }));

        it('should replace IS_AUTHENTICATED inside of percent signs', inject(function(djangoFilter) {
            expect(djangoFilter('before %IS_AUTHENTICATED% after')).
                toEqual('before false after');
        }));

        it('should replace IS_AUTHENTICATED without percent signs', inject(function(djangoFilter) {
            expect(djangoFilter('before IS_AUTHENTICATED after')).
                toEqual('before false after');
        }));
    });
});


================================================
FILE: djangular/urls.py
================================================
from django.conf.urls import patterns, url
from .views import DjangularModuleTemplateView

urlpatterns = patterns('',
    url(r'^app.js$', DjangularModuleTemplateView.as_view(), name='djangular-module')
)


================================================
FILE: djangular/utils.py
================================================
import os

CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))


class SiteAndPathUtils(object):
    """
    Mixin to get commonly used directories in Djangular Commands
    """
    def get_default_site_app(self):
        """
        Retrieves the name of the django app that contains the site config.
        """
        return os.environ["DJANGO_SETTINGS_MODULE"].replace('.settings', '')

    def get_default_site_path(self):
        """
        Retrieves the name of the django app that contains the site config.
        """
        settings_module = __import__(self.get_default_site_app())
        return settings_module.__path__[0]

    def get_djangular_root(self):
        """
        Returns the absolute path of the djangular app.
        """
        return CURRENT_DIR

    def get_project_root(self):
        """
        Retrieves the root of the project directory without having to have a entry in the settings.
        """
        default_site = self.get_default_site_app()
        path = self.get_default_site_path()
        # Move up one directory per '.' in site path.  Most sites are at the top level, so this is just a precaution.
        for _ in range(len(default_site.split('.'))):
            path = os.path.dirname(path)
        return path


================================================
FILE: djangular/views.py
================================================
from django.views.generic.base import TemplateView


class DjangularModuleTemplateView(TemplateView):
    content_type = 'text/javascript'
    template_name = 'djangular_module.js'
    disable_csrf_headers = False

    def get_context_data(self, **kwargs):
        context = super(DjangularModuleTemplateView, self).get_context_data(**kwargs)
        context['disable_csrf_headers'] = self.disable_csrf_headers
        return context


================================================
FILE: runtests.py
================================================
#!/usr/bin/env python
import sys

import django

from django.conf import settings
from django.core.management import execute_from_command_line


if not settings.configured:
    settings.configure(
        DATABASES={
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
            }
        },
        INSTALLED_APPS=[
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'django.contrib.sessions',
            'django.contrib.messages',
            'django.contrib.sites',
            'djangular',
        ],
        MIDDLEWARE_CLASSES=[
            'django.middleware.common.CommonMiddleware',
            'django.contrib.sessions.middleware.SessionMiddleware',
            'django.middleware.csrf.CsrfViewMiddleware',
            'django.contrib.auth.middleware.AuthenticationMiddleware',
            'django.contrib.messages.middleware.MessageMiddleware',  
        ],
        ROOT_URLCONF='djangular.urls'
    )


import logging
logging.basicConfig(
    level = logging.DEBUG,
    format = '%(asctime)s %(levelname)s %(message)s',
)
logging.disable(logging.CRITICAL)


def runtests():
    argv = sys.argv[:1] + ['test', 'djangular']
    execute_from_command_line(argv)


if __name__ == '__main__':
    runtests()


================================================
FILE: setup.py
================================================
try:
    from setuptools import setup, find_packages
except ImportError:
    from distribute_setup import use_setuptools
    use_setuptools()
    from setuptools import setup, find_packages

setup(
    name='djangular',
    version='0.3.0b1',
    description="A reusable app that provides better app integration with AngularJS.",
    long_description="""
A reusable app that provides better app integration with AngularJS.  Djangular
allows you to create AngularJS content per app, instead of creating a single
massive AngularJS application inside of Django.  This allows you to selectively
use apps per site, as well as create a consistent structure across all of your
Django apps.

This is intended to be a Django version of the angular-seed project
(https://github.com/angular/angular-seed).  The current mindset is to limit the
amount of changes introduced by Djangular.
""",
    keywords='djangular django angular angularjs',
    license='Apache',
    packages=['djangular'],
    include_package_data=True,
    author='Brian Montgomery',
    author_email='brianm@appliedsec.com',
    url='http://github.com/appliedsec/djangular',
    classifiers=[
        "Intended Audience :: Developers",
        "License :: OSI Approved :: Apache Software License",
        "Programming Language :: Python :: 2.7",
        "Operating System :: OS Independent",
        "Topic :: Internet :: WWW/HTTP",
        "Topic :: Internet :: WWW/HTTP :: Dynamic Content",
        "Topic :: Software Development :: Libraries :: Python Modules",
        ],
    )
Download .txt
gitextract_gczgbp39/

├── .coveragerc
├── .gitignore
├── .travis.yml
├── LICENSE
├── MANIFEST.in
├── README.md
├── djangular/
│   ├── __init__.py
│   ├── config/
│   │   └── angularseed_template/
│   │       └── angular/
│   │           ├── app.css
│   │           ├── app.js
│   │           ├── components/
│   │           │   └── version/
│   │           │       ├── interpolate-filter.js
│   │           │       ├── interpolate-filter_test.js
│   │           │       ├── version-directive.js
│   │           │       ├── version-directive_test.js
│   │           │       ├── version.js
│   │           │       └── version_test.js
│   │           ├── index.html
│   │           ├── view1/
│   │           │   ├── view1.html
│   │           │   ├── view1.js
│   │           │   └── view1_test.js
│   │           └── view2/
│   │               ├── view2.html
│   │               ├── view2.js
│   │               └── view2_test.js
│   ├── finders.py
│   ├── management/
│   │   ├── __init__.py
│   │   └── commands/
│   │       ├── __init__.py
│   │       └── startangularapp.py
│   ├── middleware.py
│   ├── models.py
│   ├── static/
│   │   └── js/
│   │       └── resource_patch.js
│   ├── storage.py
│   ├── templates/
│   │   └── djangular_module.js
│   ├── tests/
│   │   ├── __init__.py
│   │   ├── test_base.py
│   │   ├── test_commands.py
│   │   ├── test_finders.py
│   │   ├── test_middleware.py
│   │   ├── test_storage.py
│   │   ├── test_urls.py
│   │   ├── test_utils.py
│   │   └── unit/
│   │       └── filterSpec.js
│   ├── urls.py
│   ├── utils.py
│   └── views.py
├── runtests.py
└── setup.py
Download .txt
SYMBOL INDEX (55 symbols across 14 files)

FILE: djangular/finders.py
  class NamespacedAppDirectoriesFinder (line 9) | class NamespacedAppDirectoriesFinder(s_finders.AppDirectoriesFinder):
    method __init__ (line 16) | def __init__(self, app_names=None, *args, **kwargs):
    method find_in_app (line 23) | def find_in_app(self, app, path):
  class NamespacedAngularAppDirectoriesFinder (line 35) | class NamespacedAngularAppDirectoriesFinder(NamespacedAppDirectoriesFind...
  class NamespacedE2ETestAppDirectoriesFinder (line 41) | class NamespacedE2ETestAppDirectoriesFinder(NamespacedAppDirectoriesFind...
  class NamespacedAngularAppDirectoriesFinder (line 51) | class NamespacedAngularAppDirectoriesFinder(s_finders.AppDirectoriesFind...
  class NamespacedE2ETestAppDirectoriesFinder (line 57) | class NamespacedE2ETestAppDirectoriesFinder(s_finders.AppDirectoriesFind...
  class NamespacedLibTestAppDirectoriesFinder (line 63) | class NamespacedLibTestAppDirectoriesFinder(s_finders.AppDirectoriesFind...

FILE: djangular/management/commands/startangularapp.py
  class Command (line 9) | class Command(utils.SiteAndPathUtils, TemplateCommand):
    method handle (line 19) | def handle(self, name, target=None, **options):

FILE: djangular/middleware.py
  class AngularJsonVulnerabilityMiddleware (line 2) | class AngularJsonVulnerabilityMiddleware(object):
    method process_response (line 13) | def process_response(self, request, response):

FILE: djangular/storage.py
  class NamespacedAngularAppStorage (line 9) | class NamespacedAngularAppStorage(AppStaticStorage):
    method __init__ (line 17) | def __init__(self, app, *args, **kwargs):
    method path (line 25) | def path(self, name):
  class NamespacedE2ETestAppStorage (line 30) | class NamespacedE2ETestAppStorage(AppStaticStorage):
    method __init__ (line 39) | def __init__(self, app, *args, **kwargs):
  class NamespacedLibTestAppStorage (line 49) | class NamespacedLibTestAppStorage(AppStaticStorage):
    method __init__ (line 58) | def __init__(self, app, *args, **kwargs):

FILE: djangular/tests/test_base.py
  function _call_test_func (line 9) | def _call_test_func(self, test_fn):
  function test_with_angularseed_template_as_django_app (line 28) | def test_with_angularseed_template_as_django_app(test_fn):
  class TestAngularSeedAsPythonModuleTest (line 60) | class TestAngularSeedAsPythonModuleTest(SimpleTestCase):
    method test_init_py_created (line 63) | def test_init_py_created(self):

FILE: djangular/tests/test_commands.py
  class StartAngularAppCommandTests (line 10) | class StartAngularAppCommandTests(TestCase):
    method setUp (line 11) | def setUp(self):
    method test_runs (line 17) | def test_runs(self):

FILE: djangular/tests/test_finders.py
  class NamespacedAngularAppDirectoriesFinderTest (line 11) | class NamespacedAngularAppDirectoriesFinderTest(SimpleTestCase):
    method test_find (line 13) | def test_find(self):
  class NamespacedE2ETestAppDirectoriesFinderTest (line 28) | class NamespacedE2ETestAppDirectoriesFinderTest(SimpleTestCase):
    method test_find (line 31) | def test_find(self):

FILE: djangular/tests/test_middleware.py
  class AngularJsonVulnerabilityMiddlewareTest (line 7) | class AngularJsonVulnerabilityMiddlewareTest(SimpleTestCase):
    method test_that_middleware_does_nothing_to_html_requests (line 9) | def test_that_middleware_does_nothing_to_html_requests(self):
    method test_that_middleware_does_nothing_to_js_requests (line 16) | def test_that_middleware_does_nothing_to_js_requests(self):
    method test_that_middleware_does_nothing_to_invalid_json_requests (line 23) | def test_that_middleware_does_nothing_to_invalid_json_requests(self):
    method test_that_middleware_adds_prefix_to_valid_json_requests (line 30) | def test_that_middleware_adds_prefix_to_valid_json_requests(self):

FILE: djangular/tests/test_storage.py
  class NamespacedAppAngularStorageTest (line 9) | class NamespacedAppAngularStorageTest(SimpleTestCase):
    method test_source_dir_is_angular (line 10) | def test_source_dir_is_angular(self):
    method test_prefix_is_given_app_name (line 14) | def test_prefix_is_given_app_name(self):
    method test_prefix_is_given_app_name_for_more_complicated_scenario (line 19) | def test_prefix_is_given_app_name_for_more_complicated_scenario(self):
  class NamespacedE2ETestAppStorageTest (line 26) | class NamespacedE2ETestAppStorageTest(SimpleTestCase):
    method test_source_dir_is_tests (line 27) | def test_source_dir_is_tests(self):
    method test_prefix_is_given_app_name (line 31) | def test_prefix_is_given_app_name(self):
    method test_prefix_is_given_app_name_for_more_complicated_scenario (line 36) | def test_prefix_is_given_app_name_for_more_complicated_scenario(self):

FILE: djangular/tests/test_urls.py
  class UrlsTests (line 5) | class UrlsTests(TestCase):
    method test_urls_import (line 6) | def test_urls_import(self):

FILE: djangular/tests/test_utils.py
  class SiteAndPathUtilsTest (line 7) | class SiteAndPathUtilsTest(SimpleTestCase):
    method test_djangular_root (line 11) | def test_djangular_root(self):

FILE: djangular/utils.py
  class SiteAndPathUtils (line 6) | class SiteAndPathUtils(object):
    method get_default_site_app (line 10) | def get_default_site_app(self):
    method get_default_site_path (line 16) | def get_default_site_path(self):
    method get_djangular_root (line 23) | def get_djangular_root(self):
    method get_project_root (line 29) | def get_project_root(self):

FILE: djangular/views.py
  class DjangularModuleTemplateView (line 4) | class DjangularModuleTemplateView(TemplateView):
    method get_context_data (line 9) | def get_context_data(self, **kwargs):

FILE: runtests.py
  function runtests (line 44) | def runtests():
Condensed preview — 45 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (54K chars).
[
  {
    "path": ".coveragerc",
    "chars": 641,
    "preview": "[report]\n# Regexes for lines to exclude from consideration\nexclude_lines =\n    # Have to re-enable the standard pragma\n "
  },
  {
    "path": ".gitignore",
    "chars": 104,
    "preview": "*.log\n*.pot\n*.pyc\nlocal_settings.py\n\n.DS_Store\n.idea\n.hg\n.hgignore\n\ndist\ndjangular.egg-info\n\n.coverage\n\n"
  },
  {
    "path": ".travis.yml",
    "chars": 297,
    "preview": "language: python\npython:\n  - \"2.7\"\ninstall:\n  - pip install coverage\n  - pip install $DJANGO\nscript:\n  - coverage run ru"
  },
  {
    "path": "LICENSE",
    "chars": 583,
    "preview": "Copyright 2013 Applied Security\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use t"
  },
  {
    "path": "MANIFEST.in",
    "chars": 64,
    "preview": "recursive-include djangular *\ninclude LICENSE\ninclude README.md\n"
  },
  {
    "path": "README.md",
    "chars": 14506,
    "preview": "djangular\n=========\n\nA reusable app that provides better app integration with AngularJS. Djangular\nallows you to create "
  },
  {
    "path": "djangular/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "djangular/config/angularseed_template/angular/app.css",
    "chars": 366,
    "preview": "/* app css stylesheet */\n\n.menu {\n  list-style: none;\n  border-bottom: 0.1em solid black;\n  margin-bottom: 2em;\n  paddin"
  },
  {
    "path": "djangular/config/angularseed_template/angular/app.js",
    "chars": 323,
    "preview": "'use strict';\n\n// Declare app level module which depends on views, and components\nangular.module('{{ app_name }}', [\n  '"
  },
  {
    "path": "djangular/config/angularseed_template/angular/components/version/interpolate-filter.js",
    "chars": 230,
    "preview": "'use strict';\n\nangular.module('{{ app_name }}.version.interpolate-filter', [])\n\n.filter('interpolate', ['version', funct"
  },
  {
    "path": "djangular/config/angularseed_template/angular/components/version/interpolate-filter_test.js",
    "chars": 444,
    "preview": "'use strict';\n\ndescribe('{{ app_name }}.version module', function() {\n  beforeEach(module('{{ app_name }}.version'));\n\n "
  },
  {
    "path": "djangular/config/angularseed_template/angular/components/version/version-directive.js",
    "chars": 208,
    "preview": "'use strict';\n\nangular.module('{{ app_name }}.version.version-directive', [])\n\n.directive('appVersion', ['version', func"
  },
  {
    "path": "djangular/config/angularseed_template/angular/components/version/version-directive_test.js",
    "chars": 510,
    "preview": "'use strict';\n\ndescribe('{{ app_name }}.version module', function() {\n  beforeEach(module('{{ app_name }}.version'));\n\n "
  },
  {
    "path": "djangular/config/angularseed_template/angular/components/version/version.js",
    "chars": 180,
    "preview": "'use strict';\n\nangular.module('{{ app_name }}.version', [\n  '{{ app_name }}.version.interpolate-filter',\n  '{{ app_name "
  },
  {
    "path": "djangular/config/angularseed_template/angular/components/version/version_test.js",
    "chars": 286,
    "preview": "'use strict';\n\ndescribe('{{ app_name }}.version module', function() {\n  beforeEach(module('{{ app_name }}.version'));\n\n "
  },
  {
    "path": "djangular/config/angularseed_template/angular/index.html",
    "chars": 1960,
    "preview": "<!DOCTYPE html>\n<!--[if lt IE 7]>      <html lang=\"en\" ng-app=\"{{ app_name }}\" class=\"no-js lt-ie9 lt-ie8 lt-ie7\"> <![en"
  },
  {
    "path": "djangular/config/angularseed_template/angular/view1/view1.html",
    "chars": 39,
    "preview": "<p>This is the partial for view 1.</p>\n"
  },
  {
    "path": "djangular/config/angularseed_template/angular/view1/view1.js",
    "chars": 276,
    "preview": "'use strict';\n\nangular.module('{{ app_name }}.view1', ['ngRoute'])\n\n.config(['$routeProvider', function($routeProvider) "
  },
  {
    "path": "djangular/config/angularseed_template/angular/view1/view1_test.js",
    "chars": 337,
    "preview": "'use strict';\n\ndescribe('{{ app_name }}.view1 module', function() {\n\n  beforeEach(module('{{ app_name }}.view1'));\n\n  de"
  },
  {
    "path": "djangular/config/angularseed_template/angular/view2/view2.html",
    "chars": 171,
    "preview": "{% verbatim %}\n<p>This is the partial for view 2.</p>\n<p>\n  Showing of 'interpolate' filter:\n  {{ 'Current version is v%"
  },
  {
    "path": "djangular/config/angularseed_template/angular/view2/view2.js",
    "chars": 276,
    "preview": "'use strict';\n\nangular.module('{{ app_name }}.view2', ['ngRoute'])\n\n.config(['$routeProvider', function($routeProvider) "
  },
  {
    "path": "djangular/config/angularseed_template/angular/view2/view2_test.js",
    "chars": 337,
    "preview": "'use strict';\n\ndescribe('{{ app_name }}.view2 module', function() {\n\n  beforeEach(module('{{ app_name }}.view2'));\n\n  de"
  },
  {
    "path": "djangular/finders.py",
    "chars": 2529,
    "preview": "import django\nfrom django.contrib.staticfiles import finders as s_finders\n\n# Django rewrote the staticfiles storage inte"
  },
  {
    "path": "djangular/management/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "djangular/management/commands/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "djangular/management/commands/startangularapp.py",
    "chars": 1045,
    "preview": "import django\nimport os\n\nfrom django.core import management as mgmt\nfrom django.core.management.templates import Templat"
  },
  {
    "path": "djangular/middleware.py",
    "chars": 708,
    "preview": "\nclass AngularJsonVulnerabilityMiddleware(object):\n    \"\"\"\n    A middleware that inserts the AngularJS JSON Vulnerabilit"
  },
  {
    "path": "djangular/models.py",
    "chars": 19,
    "preview": "# No models needed."
  },
  {
    "path": "djangular/static/js/resource_patch.js",
    "chars": 1719,
    "preview": "try {\n    if (angular.version.full > \"1.3\") {\n        angular.module('ngResource').config([\n            '$resourceProvid"
  },
  {
    "path": "djangular/storage.py",
    "chars": 2534,
    "preview": "import django\n\nif django.get_version() < '1.7':\n    import os\n    from re import sub\n\n    from django.contrib.staticfile"
  },
  {
    "path": "djangular/templates/djangular_module.js",
    "chars": 3167,
    "preview": "// All template syntax is commented so this can be loaded as a normal JS file.\n// {% load static %}\nvar djangular = angu"
  },
  {
    "path": "djangular/tests/__init__.py",
    "chars": 368,
    "preview": "import django\n\nif django.VERSION < (1, 6):\n    from djangular.tests.test_base import *\n    from djangular.tests.test_fin"
  },
  {
    "path": "djangular/tests/test_base.py",
    "chars": 1982,
    "preview": "import django\nimport os\n\nfrom django.test import SimpleTestCase\n\nBASE_DIR = os.path.abspath(os.path.dirname(__file__))\n\n"
  },
  {
    "path": "djangular/tests/test_commands.py",
    "chars": 574,
    "preview": "import os\nimport shutil\n\nfrom django.test import TestCase\nfrom django.utils._os import upath\n\nfrom djangular.management."
  },
  {
    "path": "djangular/tests/test_finders.py",
    "chars": 1717,
    "preview": "import django\nimport os\n\nfrom djangular.tests.test_base import test_with_angularseed_template_as_django_app\nfrom djangul"
  },
  {
    "path": "djangular/tests/test_middleware.py",
    "chars": 1515,
    "preview": "from djangular import middleware\n\nfrom django.test import SimpleTestCase\nfrom django.http import HttpRequest, HttpRespon"
  },
  {
    "path": "djangular/tests/test_storage.py",
    "chars": 1775,
    "preview": "import django\n\nif django.get_version() < '1.7':\n    from djangular import storage\n    from django.test import SimpleTest"
  },
  {
    "path": "djangular/tests/test_urls.py",
    "chars": 266,
    "preview": "from django.core.urlresolvers import reverse\nfrom django.test import TestCase\n\n\nclass UrlsTests(TestCase):\n    def test_"
  },
  {
    "path": "djangular/tests/test_utils.py",
    "chars": 399,
    "preview": "import os\n\nfrom djangular import utils\nfrom django.test import SimpleTestCase\n\n\nclass SiteAndPathUtilsTest(SimpleTestCas"
  },
  {
    "path": "djangular/tests/unit/filterSpec.js",
    "chars": 2049,
    "preview": "'use strict';\n\n/* jasmine specs for filters go here */\n\ndescribe('filter', function() {\n    beforeEach(module('djangular"
  },
  {
    "path": "djangular/urls.py",
    "chars": 205,
    "preview": "from django.conf.urls import patterns, url\nfrom .views import DjangularModuleTemplateView\n\nurlpatterns = patterns('',\n  "
  },
  {
    "path": "djangular/utils.py",
    "chars": 1270,
    "preview": "import os\n\nCURRENT_DIR = os.path.dirname(os.path.abspath(__file__))\n\n\nclass SiteAndPathUtils(object):\n    \"\"\"\n    Mixin "
  },
  {
    "path": "djangular/views.py",
    "chars": 434,
    "preview": "from django.views.generic.base import TemplateView\n\n\nclass DjangularModuleTemplateView(TemplateView):\n    content_type ="
  },
  {
    "path": "runtests.py",
    "chars": 1284,
    "preview": "#!/usr/bin/env python\nimport sys\n\nimport django\n\nfrom django.conf import settings\nfrom django.core.management import exe"
  },
  {
    "path": "setup.py",
    "chars": 1543,
    "preview": "try:\n    from setuptools import setup, find_packages\nexcept ImportError:\n    from distribute_setup import use_setuptools"
  }
]

About this extraction

This page contains the full source code of the appliedsec/djangular GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 45 files (48.1 KB), approximately 12.1k tokens, and a symbol index with 55 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!