Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

We can remove appengine_django now.

  • Loading branch information...
commit 272988e40b0c6b42a9c0e3a1d853b9c6467f518e 1 parent 45a43b6
Xin Wang authored September 14, 2012

Showing 46 changed files with 0 additions and 3,689 deletions. Show diff stats Hide diff stats

  1. 1  jaikuengine/app.yaml
  2. 621  jaikuengine/appengine_django/__init__.py
  3. 25  jaikuengine/appengine_django/auth/__init__.py
  4. 31  jaikuengine/appengine_django/auth/decorators.py
  5. 36  jaikuengine/appengine_django/auth/middleware.py
  6. 188  jaikuengine/appengine_django/auth/models.py
  7. 62  jaikuengine/appengine_django/auth/templatetags.py
  8. 58  jaikuengine/appengine_django/auth/tests.py
  9. 0  jaikuengine/appengine_django/conf/app_template/__init__.py
  10. 4  jaikuengine/appengine_django/conf/app_template/models.py
  11. 1  jaikuengine/appengine_django/conf/app_template/views.py
  12. 20  jaikuengine/appengine_django/db/__init__.py
  13. 150  jaikuengine/appengine_django/db/base.py
  14. 41  jaikuengine/appengine_django/db/creation.py
  15. 95  jaikuengine/appengine_django/mail.py
  16. 0  jaikuengine/appengine_django/management/__init__.py
  17. 0  jaikuengine/appengine_django/management/commands/__init__.py
  18. 49  jaikuengine/appengine_django/management/commands/console.py
  19. 36  jaikuengine/appengine_django/management/commands/flush.py
  20. 32  jaikuengine/appengine_django/management/commands/reset.py
  21. 52  jaikuengine/appengine_django/management/commands/rollback.py
  22. 82  jaikuengine/appengine_django/management/commands/runserver.py
  23. 43  jaikuengine/appengine_django/management/commands/startapp.py
  24. 74  jaikuengine/appengine_django/management/commands/testserver.py
  25. 51  jaikuengine/appengine_django/management/commands/update.py
  26. 52  jaikuengine/appengine_django/management/commands/vacuum_indexes.py
  27. 214  jaikuengine/appengine_django/models.py
  28. 26  jaikuengine/appengine_django/replacement_imp.py
  29. 0  jaikuengine/appengine_django/serializer/__init__.py
  30. 48  jaikuengine/appengine_django/serializer/json.py
  31. 170  jaikuengine/appengine_django/serializer/python.py
  32. 46  jaikuengine/appengine_django/serializer/pyyaml.py
  33. 157  jaikuengine/appengine_django/serializer/xml.py
  34. 0  jaikuengine/appengine_django/sessions/__init__.py
  35. 0  jaikuengine/appengine_django/sessions/backends/__init__.py
  36. 82  jaikuengine/appengine_django/sessions/backends/db.py
  37. 22  jaikuengine/appengine_django/sessions/models.py
  38. 56  jaikuengine/appengine_django/tests/__init__.py
  39. 186  jaikuengine/appengine_django/tests/commands_test.py
  40. 47  jaikuengine/appengine_django/tests/core_test.py
  41. 62  jaikuengine/appengine_django/tests/db_test.py
  42. 188  jaikuengine/appengine_django/tests/integration_test.py
  43. 43  jaikuengine/appengine_django/tests/memcache_test.py
  44. 110  jaikuengine/appengine_django/tests/model_test.py
  45. 326  jaikuengine/appengine_django/tests/serialization_test.py
  46. 102  jaikuengine/main.py
1  jaikuengine/app.yaml
@@ -17,7 +17,6 @@ skip_files: |
17 17
  (\..*)|
18 18
  (manage.py)|
19 19
  (docutils/.*)|
20  
- (appengine_django/management/commands/.*)|
21 20
  (README)|
22 21
  (CHANGELOG)|
23 22
  (Makefile)|
621  jaikuengine/appengine_django/__init__.py
... ...
@@ -1,621 +0,0 @@
1  
-#!/usr/bin/python2.4
2  
-#
3  
-# Copyright 2008 Google Inc.
4  
-#
5  
-# Licensed under the Apache License, Version 2.0 (the "License");
6  
-# you may not use this file except in compliance with the License.
7  
-# You may obtain a copy of the License at
8  
-#
9  
-#     http://www.apache.org/licenses/LICENSE-2.0
10  
-#
11  
-# Unless required by applicable law or agreed to in writing, software
12  
-# distributed under the License is distributed on an "AS IS" BASIS,
13  
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  
-# See the License for the specific language governing permissions and
15  
-# limitations under the License.
16  
-
17  
-"""Support for integrating a Django project with the appengine infrastructure.
18  
-
19  
-This requires Django 1.0beta1 or greater.
20  
-
21  
-This module enables you to use the Django manage.py utility and *some* of it's
22  
-subcommands. View the help of manage.py for exact details.
23  
-
24  
-Additionally this module takes care of initialising the datastore (and a test
25  
-datastore) so that the Django test infrastructure can be used for your
26  
-appengine project.
27  
-
28  
-To use this module add the following two lines to your main.py and manage.py
29  
-scripts at the end of your imports:
30  
-  from appengine_django import InstallAppengineHelperForDjango
31  
-  InstallAppengineHelperForDjango()
32  
-
33  
-If you would like to use a version of Django other than that provided by the
34  
-system all you need to do is include it in a directory just above this helper,
35  
-eg:
36  
-  appengine_django/__init__.py        -  This file
37  
-  django/...                          - your private copy of Django.
38  
-"""
39  
-
40  
-import logging
41  
-import os
42  
-import re
43  
-import sys
44  
-import unittest
45  
-import zipfile
46  
-
47  
-
48  
-INSTALLED = False
49  
-DIR_PATH = os.path.abspath(os.path.dirname(__file__))
50  
-PARENT_DIR = os.path.dirname(DIR_PATH)
51  
-if PARENT_DIR.endswith(".zip"):
52  
-  # Check for appengine_django itself being in a zipfile.
53  
-  PARENT_DIR = os.path.dirname(PARENT_DIR)
54  
-
55  
-# Add this project to the start of sys path to enable direct imports.
56  
-sys.path = [PARENT_DIR,] + sys.path
57  
-
58  
-# Look for a zipped copy of Django.
59  
-have_django_zip = False
60  
-django_zip_path = os.path.join(PARENT_DIR, 'django.zip')
61  
-
62  
-
63  
-# Flags made available this module
64  
-appid = None
65  
-have_appserver = False
66  
-
67  
-# Hide everything other than the flags above and the install function.
68  
-__all__ = ("appid", "have_appserver", "have_django_zip",
69  
-           "django_zip_path", "InstallAppengineHelperForDjango")
70  
-
71  
-
72  
-INCOMPATIBLE_COMMANDS = ["adminindex", "createcachetable", "dbshell",
73  
-                         "inspectdb", "runfcgi", "syncdb", "validate"]
74  
-
75  
-
76  
-def FixPython26Logging():
77  
-  import logging
78  
-  logging.logMultiprocessing = 0
79  
-
80  
-
81  
-def LoadSdk():
82  
-  # Try to import the appengine code from the system path.
83  
-  try:
84  
-    from google.appengine.api import apiproxy_stub_map
85  
-  except ImportError, e:
86  
-    # Hack to fix reports of import errors on Ubuntu 9.10.
87  
-    if 'google' in sys.modules:
88  
-      del sys.modules['google']
89  
-    # Not on the system path. Build a list of alternative paths where it may be.
90  
-    # First look within the project for a local copy, then look for where the Mac
91  
-    # OS SDK installs it.
92  
-    paths = [os.path.join(PARENT_DIR, '.google_appengine'),
93  
-             os.path.join(PARENT_DIR, 'google_appengine'),
94  
-             '/usr/local/google_appengine']
95  
-    # Then if on windows, look for where the Windows SDK installed it.
96  
-    for path in os.environ.get('PATH', '').split(';'):
97  
-      path = path.rstrip('\\')
98  
-      if path.endswith('google_appengine'):
99  
-        paths.append(path)
100  
-    try:
101  
-      from win32com.shell import shell
102  
-      from win32com.shell import shellcon
103  
-      id_list = shell.SHGetSpecialFolderLocation(
104  
-          0, shellcon.CSIDL_PROGRAM_FILES)
105  
-      program_files = shell.SHGetPathFromIDList(id_list)
106  
-      paths.append(os.path.join(program_files, 'Google',
107  
-                                'google_appengine'))
108  
-    except ImportError, e:
109  
-      # Not windows.
110  
-      pass
111  
-    # Loop through all possible paths and look for the SDK dir.
112  
-    SDK_PATH = None
113  
-    for sdk_path in paths:
114  
-      if os.path.exists(sdk_path):
115  
-        SDK_PATH = os.path.realpath(sdk_path)
116  
-        break
117  
-    if SDK_PATH is None:
118  
-      # The SDK could not be found in any known location.
119  
-      sys.stderr.write("The Google App Engine SDK could not be found!\n")
120  
-      sys.stderr.write("See README for installation instructions.\n")
121  
-      sys.exit(1)
122  
-    if SDK_PATH == os.path.join(PARENT_DIR, 'google_appengine'):
123  
-      logging.warn('Loading the SDK from the \'google_appengine\' subdirectory '
124  
-                   'is now deprecated!')
125  
-      logging.warn('Please move the SDK to a subdirectory named '
126  
-                   '\'.google_appengine\' instead.')
127  
-      logging.warn('See README for further details.')
128  
-    # Add the SDK and the libraries within it to the system path.
129  
-    EXTRA_PATHS = [
130  
-        SDK_PATH,
131  
-        os.path.join(SDK_PATH, 'lib', 'antlr3'),
132  
-        os.path.join(SDK_PATH, 'lib', 'django'),
133  
-        os.path.join(SDK_PATH, 'lib', 'ipaddr'),
134  
-        os.path.join(SDK_PATH, 'lib', 'webob'),
135  
-        os.path.join(SDK_PATH, 'lib', 'yaml', 'lib'),
136  
-        os.path.join(SDK_PATH, 'lib', 'fancy_urllib'),
137  
-        os.path.join(SDK_PATH, 'lib', 'simplejson'),
138  
-        os.path.join(SDK_PATH, 'lib', 'whoosh'),
139  
-        os.path.join(SDK_PATH, 'lib', 'protorpc'),
140  
-        os.path.join(SDK_PATH, 'lib', 'graphy'),
141  
-    ]
142  
-    # Add SDK paths at the start of sys.path, but after the local directory which
143  
-    # was added to the start of sys.path on line 50 above. The local directory
144  
-    # must come first to allow the local imports to override the SDK and
145  
-    # site-packages directories.
146  
-    sys.path = sys.path[0:1] + EXTRA_PATHS + sys.path[1:]
147  
-
148  
-
149  
-def LoadDjango(version=None):
150  
-  global have_django_zip
151  
-
152  
-  from google.appengine.dist import use_library
153  
-  from google.appengine.dist._library import UnacceptableVersionError
154  
-
155  
-  # Must set this env var *before* importing any more of Django.
156  
-  os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
157  
-
158  
-  # If we have set a version explicitly, force that
159  
-  if version:
160  
-    use_library('django', version)
161  
-    return
162  
-
163  
-  if os.path.exists(django_zip_path):
164  
-    have_django_zip = True
165  
-    sys.path.insert(1, django_zip_path)
166  
-
167  
-  # Remove the standard version of Django if a local copy has been provided.
168  
-  if have_django_zip or os.path.exists(os.path.join(PARENT_DIR, 'django')):
169  
-    for k in [k for k in sys.modules if k.startswith('django')]:
170  
-      del sys.modules[k]
171  
-    return
172  
-
173  
-  # If we aren't loading from a zip or local copy then try for whichever
174  
-  # supported version is highest and installed
175  
-  for check_version in ('1.2', '1.1', '1.0'):
176  
-    try:
177  
-      use_library('django', check_version)
178  
-      return
179  
-    except UnacceptableVersionError:
180  
-      pass
181  
-
182  
-  raise UnacceptableVersionError()
183  
-
184  
-
185  
-def LoadAppengineEnvironment():
186  
-  """Loads the appengine environment.
187  
-
188  
-  Returns:
189  
-    This function has no return value, but it sets the following parameters on
190  
-    this package:
191  
-    - appid: The name of the application.
192  
-    - have_appserver: Boolean parameter which is True if the code is being run
193  
-        from within the appserver environment.
194  
-  """
195  
-  global appid, have_appserver
196  
-  from google.appengine.api import yaml_errors
197  
-  from google.appengine.api import apiproxy_stub_map
198  
-
199  
-  # Detect if we are running under an appserver.
200  
-  have_appserver = False
201  
-  stub = apiproxy_stub_map.apiproxy.GetStub("datastore_v3")
202  
-  if stub:
203  
-    have_appserver = True
204  
-
205  
-  # Load the application identifier.
206  
-  if have_appserver:
207  
-    appid = os.environ.get("APPLICATION_ID", "unknown")
208  
-  else:
209  
-    # Running as manage.py script, read from config file.
210  
-    try:
211  
-      from google.appengine.tools import dev_appserver
212  
-      appconfig, unused_matcher, from_cache = dev_appserver.LoadAppConfig(PARENT_DIR, {})
213  
-      appid = appconfig.application
214  
-    except (ImportError, yaml_errors.EventListenerYAMLError), e:
215  
-      logging.warn("Could not read the Application ID from app.yaml. "
216  
-                   "This may break things in unusual ways!")
217  
-      # Something went wrong.
218  
-      appid = "unknown"
219  
-
220  
-  logging.debug("Loading application '%s' %s an appserver" %
221  
-                (appid, have_appserver and "with" or "without"))
222  
-
223  
-
224  
-def InstallAppengineDatabaseBackend():
225  
-  """Installs the appengine database backend into Django.
226  
-
227  
-  The appengine database lives in the db/ subdirectory of this package, but is
228  
-  known as "appengine" to Django. This function installs the module where
229  
-  Django expects to find its database backends.
230  
-  """
231  
-  from appengine_django import db
232  
-  sys.modules['django.db.backends.appengine'] = db
233  
-  logging.debug("Installed appengine database backend")
234  
-
235  
-
236  
-def InstallGoogleMemcache():
237  
-  """Installs the Google memcache into Django.
238  
-
239  
-  By default django tries to import standard memcache module.
240  
-  Because appengine memcache is API compatible with Python memcache module,
241  
-  we can trick Django to think it is installed and to use it.
242  
-
243  
-  Now you can use CACHE_BACKEND = 'memcached://' in settings.py. IP address
244  
-  and port number are not required.
245  
-  """
246  
-  from google.appengine.api import memcache
247  
-  sys.modules['memcache'] = memcache
248  
-  logging.debug("Installed App Engine memcache backend")
249  
-
250  
-
251  
-def InstallDjangoModuleReplacements():
252  
-  """Replaces internal Django modules with App Engine compatible versions."""
253  
-
254  
-  # Replace the session module with a partial replacement overlay using
255  
-  # __path__ so that portions not replaced will fall through to the original
256  
-  # implementation.
257  
-  try:
258  
-    from django.contrib import sessions
259  
-    orig_path = sessions.__path__[0]
260  
-    sessions.__path__.insert(0, os.path.join(DIR_PATH, 'sessions'))
261  
-    from django.contrib.sessions import backends
262  
-    backends.__path__.append(os.path.join(orig_path, 'backends'))
263  
-  except ImportError:
264  
-    logging.debug("No Django session support available")
265  
-
266  
-  # Replace incompatible dispatchers.
267  
-  import django.core.signals
268  
-  import django.db
269  
-  import django.dispatch.dispatcher
270  
-
271  
-  # Rollback occurs automatically on Google App Engine. Disable the Django
272  
-  # rollback handler.
273  
-  try:
274  
-    # pre 1.0
275  
-    from django.dispatch import errors
276  
-    CheckedException = errors.DispatcherKeyError
277  
-    def _disconnectSignal():
278  
-      django.dispatch.dispatcher.disconnect(
279  
-          django.db._rollback_on_exception,
280  
-          django.core.signals.got_request_exception)
281  
-  except ImportError:
282  
-    CheckedException = KeyError
283  
-    def _disconnectSignal():
284  
-      django.core.signals.got_request_exception.disconnect(
285  
-          django.db._rollback_on_exception)
286  
-
287  
-  try:
288  
-    _disconnectSignal()
289  
-  except CheckedException, e:
290  
-    logging.debug("Django rollback handler appears to be already disabled.")
291  
-
292  
-
293  
-def PatchDjangoSerializationModules(settings):
294  
-  """Monkey patches the Django serialization modules.
295  
-
296  
-  The standard Django serialization modules to not correctly handle the
297  
-  datastore models provided by this package. This method installs replacements
298  
-  for selected modules and methods to give Django the capability to correctly
299  
-  serialize and deserialize datastore models.
300  
-  """
301  
-  # These can't be imported until InstallAppengineDatabaseBackend has run.
302  
-  from django.core.serializers import python
303  
-  from appengine_django.serializer.python import Deserializer
304  
-  if not hasattr(settings, "SERIALIZATION_MODULES"):
305  
-    settings.SERIALIZATION_MODULES = {}
306  
-  base_module = "appengine_django"
307  
-  settings.SERIALIZATION_MODULES["xml"] = "%s.serializer.xml" % base_module
308  
-  python.Deserializer = Deserializer
309  
-  # This must be imported after the Deserializer has been mokey patched above.
310  
-  from django.core.serializers import json
311  
-  from appengine_django.serializer.json import DjangoJSONEncoder
312  
-  json.DjangoJSONEncoder = DjangoJSONEncoder
313  
-  from django.core.serializers import pyyaml
314  
-  from appengine_django.serializer.pyyaml import DjangoSafeDumper
315  
-  pyyaml.DjangoSafeDumper = DjangoSafeDumper
316  
-  PatchDeserializedObjectClass()
317  
-  DisableModelValidation()
318  
-  logging.debug("Installed appengine json and python serialization modules")
319  
-
320  
-
321  
-def PatchDeserializedObjectClass():
322  
-  """Patches the DeserializedObject class.
323  
-
324  
-  The default implementation calls save directly on the django Model base
325  
-  class to avoid pre-save handlers. The model class provided by this package
326  
-  is not derived from the Django Model class and therefore must be called
327  
-  directly.
328  
-
329  
-  Additionally we need to clear the internal _parent attribute as it may
330  
-  contain a FakeParent class that is used to deserialize instances without
331  
-  needing to load the parent instance itself. See the PythonDeserializer for
332  
-  more details.
333  
-  """
334  
-  # This can't be imported until InstallAppengineDatabaseBackend has run.
335  
-  from django.core.serializers import base
336  
-  class NewDeserializedObject(base.DeserializedObject):
337  
-    def save(self, save_m2m=True, using=None):
338  
-      self.object.save()
339  
-      self.object._parent = None
340  
-  base.DeserializedObject = NewDeserializedObject
341  
-  logging.debug("Replacement DeserializedObject class installed")
342  
-
343  
-
344  
-def DisableModelValidation():
345  
-  """Disables Django's model validation routines.
346  
-
347  
-  The model validation is primarily concerned with validating foreign key
348  
-  references. There is no equivalent checking code for datastore References at
349  
-  this time.
350  
-
351  
-  Validation needs to be disabled or serialization/deserialization will fail.
352  
-  """
353  
-  from django.core.management import validation
354  
-  validation.get_validation_errors = lambda x, y=0: 0
355  
-  logging.debug("Django SQL model validation disabled")
356  
-
357  
-
358  
-def CleanupDjangoSettings(settings):
359  
-  """Removes incompatible entries from the django settings module."""
360  
-
361  
-  # Ensure this module is installed as an application.
362  
-  apps = getattr(settings, "INSTALLED_APPS", ())
363  
-  found = False
364  
-  for app in apps:
365  
-    if app.endswith("appengine_django"):
366  
-      found = True
367  
-      break
368  
-  if not found:
369  
-    logging.warn("appengine_django module is not listed as an application!")
370  
-    apps += ("appengine_django",)
371  
-    setattr(settings, "INSTALLED_APPS", apps)
372  
-    logging.info("Added 'appengine_django' as an application")
373  
-
374  
-  # Ensure the database backend is appropriately configured.
375  
-  dbe = getattr(settings, "DATABASE_ENGINE", "")
376  
-  if dbe != "appengine":
377  
-    settings.DATABASE_ENGINE = "appengine"
378  
-    logging.warn("DATABASE_ENGINE is not configured as 'appengine'. "
379  
-                 "Value overriden!")
380  
-  for var in ["NAME", "USER", "PASSWORD", "HOST", "PORT"]:
381  
-    val = getattr(settings, "DATABASE_%s" % var, "")
382  
-    if val:
383  
-      setattr(settings, "DATABASE_%s" % var, "")
384  
-      logging.warn("DATABASE_%s should be blank. Value overriden!")
385  
-
386  
-  # Remove incompatible middleware modules.
387  
-  mw_mods = list(getattr(settings, "MIDDLEWARE_CLASSES", ()))
388  
-  disallowed_middleware_mods = (
389  
-    'django.middleware.doc.XViewMiddleware',)
390  
-  for modname in mw_mods[:]:
391  
-    if modname in disallowed_middleware_mods:
392  
-      # Currently only the CommonMiddleware has been ported.  As other base
393  
-      # modules are converted, remove from the disallowed_middleware_mods
394  
-      # tuple.
395  
-      mw_mods.remove(modname)
396  
-      logging.warn("Middleware module '%s' is not compatible. Removed!" %
397  
-                   modname)
398  
-  setattr(settings, "MIDDLEWARE_CLASSES", tuple(mw_mods))
399  
-
400  
-  # Remove incompatible application modules
401  
-  app_mods = list(getattr(settings, "INSTALLED_APPS", ()))
402  
-  disallowed_apps = (
403  
-    'django.contrib.contenttypes',
404  
-    'django.contrib.sites',)
405  
-  for app in app_mods[:]:
406  
-    if app in disallowed_apps:
407  
-      app_mods.remove(app)
408  
-      logging.warn("Application module '%s' is not compatible. Removed!" % app)
409  
-  setattr(settings, "INSTALLED_APPS", tuple(app_mods))
410  
-
411  
-  # Remove incompatible session backends.
412  
-  session_backend = getattr(settings, "SESSION_ENGINE", "")
413  
-  if session_backend.endswith("file"):
414  
-    logging.warn("File session backend is not compatible. Overriden "
415  
-                 "to use db backend!")
416  
-    setattr(settings, "SESSION_ENGINE", "django.contrib.sessions.backends.db")
417  
-
418  
-
419  
-def ModifyAvailableCommands():
420  
-  """Removes incompatible commands and installs replacements where possible."""
421  
-  if have_appserver:
422  
-    # Commands are not used when running from an appserver.
423  
-    return
424  
-  from django.core import management
425  
-  project_directory = os.path.join(__path__[0], "../")
426  
-  if have_django_zip:
427  
-    FindCommandsInZipfile.orig = management.find_commands
428  
-    management.find_commands = FindCommandsInZipfile
429  
-  management.get_commands()
430  
-  # Replace startapp command which is set by previous call to get_commands().
431  
-  from appengine_django.management.commands.startapp import ProjectCommand
432  
-  management._commands['startapp'] = ProjectCommand(project_directory) 
433  
-  RemoveCommands(management._commands)
434  
-  logging.debug("Removed incompatible Django manage.py commands")
435  
-
436  
-
437  
-def FindCommandsInZipfile(management_dir):
438  
-    """
439  
-    Given a path to a management directory, returns a list of all the command
440  
-    names that are available.
441  
-
442  
-    This implementation also works when Django is loaded from a zip.
443  
-
444  
-    Returns an empty list if no commands are defined.
445  
-    """
446  
-    zip_marker = ".zip%s" % os.sep
447  
-    if zip_marker not in management_dir:
448  
-      return FindCommandsInZipfile.orig(management_dir)
449  
-
450  
-    # Django is sourced from a zipfile, ask zip module for a list of files.
451  
-    filename, path = management_dir.split(zip_marker)
452  
-    zipinfo = zipfile.ZipFile("%s.zip" % filename)
453  
-
454  
-    # Add commands directory to management path.
455  
-    path = os.path.join(path, "commands")
456  
-
457  
-    # The zipfile module returns paths in the format of the operating system
458  
-    # that created the zipfile! This may not match the path to the zipfile
459  
-    # itself. Convert operating system specific characters to a standard
460  
-    # character (#) to compare paths to work around this.
461  
-    path_normalise = re.compile(r"[/\\]")
462  
-    path = path_normalise.sub("#", path)
463  
-    def _IsCmd(t):
464  
-      """Returns true if t matches the criteria for a command module."""
465  
-      filename = os.path.basename(t)
466  
-      t = path_normalise.sub("#", t)
467  
-      if not t.startswith(path):
468  
-        return False
469  
-      if filename.startswith("_") or not t.endswith(".py"):
470  
-        return False
471  
-      return True
472  
-
473  
-    return [os.path.basename(f)[:-3] for f in zipinfo.namelist() if _IsCmd(f)]
474  
-
475  
-
476  
-def RemoveCommands(command_dict):
477  
-  """Removes incompatible commands from the specified command dictionary."""
478  
-  for cmd in command_dict.keys():
479  
-    if cmd.startswith("sql"):
480  
-      del command_dict[cmd]
481  
-    elif cmd in INCOMPATIBLE_COMMANDS:
482  
-      del command_dict[cmd]
483  
-
484  
-
485  
-def InstallReplacementImpModule():
486  
-  """Install a replacement for the imp module removed by the appserver.
487  
-
488  
-  This is only to find mangement modules provided by applications.
489  
-  """
490  
-  if not have_appserver:
491  
-    return
492  
-  modname = 'appengine_django.replacement_imp'
493  
-  imp_mod = __import__(modname, {}, [], [''])
494  
-  sys.modules['imp'] = imp_mod
495  
-  logging.debug("Installed replacement imp module")
496  
-
497  
-
498  
-def InstallReplacementThreadingModule():
499  
-  """Install a replacement for the python threading module.
500  
-
501  
-  This is only to deal with a bug in Django 1.1+
502  
-  """
503  
-  try:
504  
-    from django.utils._threading_local import local
505  
-    import threading
506  
-    threading.local = local
507  
-  except ImportError:
508  
-    # We are in Django 1.0
509  
-    pass
510  
-  logging.debug("Installed replacement threading module")
511  
-
512  
-
513  
-def InstallAppengineHelperForDjango(version=None):
514  
-  """Installs and Patches all of the classes/methods required for integration.
515  
-
516  
-  If the variable DEBUG_APPENGINE_DJANGO is set in the environment verbose
517  
-  logging of the actions taken will be enabled.
518  
-  """
519  
-  global INSTALLED
520  
-  if INSTALLED:
521  
-    logging.warning("App Engine Helper has already been installed for this "
522  
-                    "process (not going to reinstall)")
523  
-    return
524  
-
525  
-  FixPython26Logging()
526  
-  LoadSdk()
527  
-  LoadDjango(version)
528  
-
529  
-  from django import VERSION
530  
-  from django.conf import settings
531  
-
532  
-  # Adding this again here to solve a problem that happens when context
533  
-  # switching from webapp.template to django.template.
534  
-  # TODO(elsigh): Maybe there is a deeper, fixable problem somewhere?
535  
-  os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
536  
-
537  
-  if VERSION < (1, 0, None):
538  
-    logging.error("Django 1.0 or greater is required!")
539  
-    sys.exit(1)
540  
-
541  
-  if os.getenv("DEBUG_APPENGINE_DJANGO"):
542  
-    logging.getLogger().setLevel(logging.DEBUG)
543  
-  else:
544  
-    logging.getLogger().setLevel(logging.INFO)
545  
-  logging.debug("Loading the Google App Engine Helper for Django...")
546  
-
547  
-  # Force Django to reload its settings.
548  
-  settings._target = None
549  
-
550  
-  LoadAppengineEnvironment()
551  
-  InstallReplacementImpModule()
552  
-  InstallReplacementThreadingModule()
553  
-  InstallAppengineDatabaseBackend()
554  
-  InstallModelForm()
555  
-  InstallGoogleMemcache()
556  
-  InstallDjangoModuleReplacements()
557  
-  PatchDjangoSerializationModules(settings)
558  
-  CleanupDjangoSettings(settings)
559  
-  ModifyAvailableCommands()
560  
-  InstallGoogleSMTPConnection()
561  
-  InstallAuthentication(settings)
562  
-
563  
-  logging.debug("Successfully loaded the Google App Engine Helper for Django.")
564  
-  INSTALLED = True
565  
-
566  
-
567  
-def InstallGoogleSMTPConnection():
568  
-  from appengine_django import mail as gmail
569  
-  from django.core import mail
570  
-  logging.debug("Installing Google Email Adapter for Django")
571  
-  mail.SMTPConnection = gmail.GoogleSMTPConnection
572  
-  mail.mail_admins = gmail.mail_admins
573  
-  mail.mail_managers = gmail.mail_managers
574  
-
575  
-
576  
-def InstallAuthentication(settings):
577  
-  if "django.contrib.auth" not in settings.INSTALLED_APPS:
578  
-    return
579  
-  try:
580  
-    from appengine_django.auth import models as helper_models
581  
-    from django.contrib.auth import models
582  
-    models.User = helper_models.User
583  
-    models.Group = helper_models.Group
584  
-    models.Permission = helper_models.Permission
585  
-    models.Message = helper_models.Message
586  
-    from django.contrib.auth import middleware as django_middleware
587  
-    from appengine_django.auth.middleware import AuthenticationMiddleware
588  
-    django_middleware.AuthenticationMiddleware = AuthenticationMiddleware
589  
-    from django.contrib.auth import decorators as django_decorators
590  
-    from appengine_django.auth.decorators import login_required
591  
-    django_decorators.login_required = login_required
592  
-    from django.contrib import auth as django_auth
593  
-    from django.contrib.auth import tests as django_tests
594  
-    django_auth.suite = unittest.TestSuite
595  
-    django_tests.suite = unittest.TestSuite
596  
-    logging.debug("Installing authentication framework")
597  
-  except ImportError:
598  
-    logging.debug("No Django authentication support available")
599  
-
600  
-
601  
-def InstallModelForm():
602  
-  """Replace Django ModelForm with the AppEngine ModelForm."""
603  
-  # This MUST happen as early as possible, but after any auth model patching.
604  
-  from google.appengine.ext.db import djangoforms as aeforms
605  
-  try:
606  
-    # pre 1.0
607  
-    from django import newforms as forms
608  
-  except ImportError:
609  
-    from django import forms
610  
-
611  
-  forms.ModelForm = aeforms.ModelForm
612  
-
613  
-  # Extend ModelForm with support for EmailProperty
614  
-  # TODO: This should be submitted to the main App Engine SDK.
615  
-  from google.appengine.ext.db import EmailProperty
616  
-  def get_form_field(self, **kwargs):
617  
-    """Return a Django form field appropriate for an email property."""
618  
-    defaults = {'form_class': forms.EmailField}
619  
-    defaults.update(kwargs)
620  
-    return super(EmailProperty, self).get_form_field(**defaults)
621  
-  EmailProperty.get_form_field = get_form_field
25  jaikuengine/appengine_django/auth/__init__.py
... ...
@@ -1,25 +0,0 @@
1  
-# Copyright 2008 Google Inc.
2  
-#
3  
-# Licensed under the Apache License, Version 2.0 (the "License");
4  
-# you may not use this file except in compliance with the License.
5  
-# You may obtain a copy of the License at
6  
-#
7  
-#     http://www.apache.org/licenses/LICENSE-2.0
8  
-#
9  
-# Unless required by applicable law or agreed to in writing, software
10  
-# distributed under the License is distributed on an "AS IS" BASIS,
11  
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  
-# See the License for the specific language governing permissions and
13  
-# limitations under the License.
14  
-
15  
-"""
16  
-Authentication module that mimics the behavior of Django's authentication
17  
-implementation.
18  
-
19  
-Limitations:
20  
- - all user permissions methods are not available (requires contenttypes)
21  
-"""
22  
-
23  
-from django.template import add_to_builtins
24  
-
25  
-add_to_builtins('appengine_django.auth.templatetags')
31  jaikuengine/appengine_django/auth/decorators.py
... ...
@@ -1,31 +0,0 @@
1  
-# Copyright 2008 Google Inc.
2  
-#
3  
-# Licensed under the Apache License, Version 2.0 (the "License");
4  
-# you may not use this file except in compliance with the License.
5  
-# You may obtain a copy of the License at
6  
-#
7  
-#     http://www.apache.org/licenses/LICENSE-2.0
8  
-#
9  
-# Unless required by applicable law or agreed to in writing, software
10  
-# distributed under the License is distributed on an "AS IS" BASIS,
11  
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  
-# See the License for the specific language governing permissions and
13  
-# limitations under the License.
14  
-
15  
-"""Decorators for the authentication framework."""
16  
-
17  
-from django.http import HttpResponseRedirect
18  
-
19  
-from google.appengine.api import users
20  
-
21  
-
22  
-def login_required(function):
23  
-  """Implementation of Django's login_required decorator.
24  
-  
25  
-  The login redirect URL is always set to request.path
26  
-  """
27  
-  def login_required_wrapper(request, *args, **kw):
28  
-    if request.user.is_authenticated():
29  
-      return function(request, *args, **kw)
30  
-    return HttpResponseRedirect(users.create_login_url(request.path))
31  
-  return login_required_wrapper
36  jaikuengine/appengine_django/auth/middleware.py
... ...
@@ -1,36 +0,0 @@
1  
-# Copyright 2008 Google Inc.
2  
-#
3  
-# Licensed under the Apache License, Version 2.0 (the "License");
4  
-# you may not use this file except in compliance with the License.
5  
-# You may obtain a copy of the License at
6  
-#
7  
-#     http://www.apache.org/licenses/LICENSE-2.0
8  
-#
9  
-# Unless required by applicable law or agreed to in writing, software
10  
-# distributed under the License is distributed on an "AS IS" BASIS,
11  
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  
-# See the License for the specific language governing permissions and
13  
-# limitations under the License.
14  
-
15  
-from django.contrib.auth.models import AnonymousUser
16  
-
17  
-from google.appengine.api import users
18  
-
19  
-from appengine_django.auth.models import User
20  
-
21  
-
22  
-class LazyUser(object):
23  
-  def __get__(self, request, obj_type=None):
24  
-    if not hasattr(request, '_cached_user'):
25  
-      user = users.get_current_user()
26  
-      if user:
27  
-        request._cached_user = User.get_djangouser_for_user(user)
28  
-      else:
29  
-        request._cached_user = AnonymousUser()
30  
-    return request._cached_user
31  
-
32  
-
33  
-class AuthenticationMiddleware(object):
34  
-  def process_request(self, request):
35  
-    request.__class__.user = LazyUser()
36  
-    return None
188  jaikuengine/appengine_django/auth/models.py
... ...
@@ -1,188 +0,0 @@
1  
-# Copyright 2008 Google Inc.
2  
-#
3  
-# Licensed under the Apache License, Version 2.0 (the "License");
4  
-# you may not use this file except in compliance with the License.
5  
-# You may obtain a copy of the License at
6  
-#
7  
-#     http://www.apache.org/licenses/LICENSE-2.0
8  
-#
9  
-# Unless required by applicable law or agreed to in writing, software
10  
-# distributed under the License is distributed on an "AS IS" BASIS,
11  
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  
-# See the License for the specific language governing permissions and
13  
-# limitations under the License.
14  
-
15  
-"""
16  
-App Engine compatible models for the Django authentication framework.
17  
-"""
18  
-
19  
-from django.core import mail
20  
-from django.core.exceptions import ImproperlyConfigured
21  
-from django.db import models
22  
-from django.utils.encoding import smart_str
23  
-import urllib
24  
-
25  
-from django.db.models.manager import EmptyManager
26  
-
27  
-from google.appengine.api import users
28  
-from google.appengine.ext import db
29  
-
30  
-from appengine_django.models import BaseModel
31  
-
32  
-
33  
-class User(BaseModel):
34  
-  """A model with the same attributes and methods as a Django user model.
35  
-
36  
-  The model has two additions. The first addition is a 'user' attribute which
37  
-  references a App Engine user. The second is the 'get_djangouser_for_user'
38  
-  classmethod that should be used to retrieve a DjangoUser instance from a App
39  
-  Engine user object.
40  
-  """
41  
-  user = db.UserProperty(required=True)
42  
-  username = db.StringProperty(required=True)
43  
-  first_name = db.StringProperty()
44  
-  last_name = db.StringProperty()
45  
-  email = db.EmailProperty()
46  
-  password = db.StringProperty()
47  
-  is_staff = db.BooleanProperty(default=False, required=True)
48  
-  is_active = db.BooleanProperty(default=True, required=True)
49  
-  is_superuser = db.BooleanProperty(default=False, required=True)
50  
-  last_login = db.DateTimeProperty(auto_now_add=True, required=True)
51  
-  date_joined = db.DateTimeProperty(auto_now_add=True, required=True)
52  
-  groups = EmptyManager()
53  
-  user_permissions = EmptyManager()
54  
-
55  
-  def __unicode__(self):
56  
-    return self.username
57  
-
58  
-  def __str__(self):
59  
-    return unicode(self).encode('utf-8')
60  
-
61  
-  @classmethod
62  
-  def get_djangouser_for_user(cls, user):
63  
-    django_user = cls.get_by_key_name(user.user_id())
64  
-    if django_user:
65  
-      return cls._refresh_djangouser_state(django_user, user)
66  
-
67  
-    # Check to make sure there's no legacy User object before creating a new
68  
-    # one (new style User objects use a key_name based on the user_id).
69  
-    django_user = cls.all().filter('user =', user).get()
70  
-    if django_user:
71  
-      return cls._refresh_djangouser_state(django_user, user)
72  
-
73  
-    return cls.get_or_insert(
74  
-        key_name=user.user_id(), user=user, email=user.email(),
75  
-        username=user.nickname())
76  
-
77  
-  @classmethod
78  
-  def _refresh_djangouser_state(cls, django_user, user):
79  
-    """Updates Django User attributes to match current App Engine User data."""
80  
-    if django_user.email != user.email():
81  
-      django_user.email = user.email()
82  
-      django_user.username = user.nickname()
83  
-      django_user.user = user
84  
-      django_user.save()
85  
-    return django_user
86  
-
87  
-  def set_password(self, raw_password):
88  
-    raise NotImplementedError
89  
-
90  
-  def check_password(self, raw_password):
91  
-    raise NotImplementedError
92  
-
93  
-  def set_unusable_password(self):
94  
-    raise NotImplementedError
95  
-
96  
-  def has_usable_password(self):
97  
-    raise NotImplementedError
98  
-
99  
-  def get_group_permissions(self):
100  
-    return self.user_permissions
101  
-
102  
-  def get_all_permissions(self):
103  
-    return self.user_permissions
104  
-
105  
-  def has_perm(self, perm):
106  
-    return False
107  
-
108  
-  def has_perms(self, perm_list):
109  
-    return False
110  
-
111  
-  def has_module_perms(self, module):
112  
-    return False
113  
-
114  
-  def get_and_delete_messages(self):
115  
-    """Gets and deletes messages for this user"""
116  
-    msgs = []
117  
-    for msg in self.message_set:
118  
-      msgs.append(msg)
119  
-      msg.delete()
120  
-    return msgs
121  
-
122  
-  def is_anonymous(self):
123  
-    """Always return False"""
124  
-    return False
125  
-
126  
-  def is_authenticated(self):
127  
-    """Always return True"""
128  
-    return True
129  
-
130  
-  def get_absolute_url(self):
131  
-    return "/users/%s/" % urllib.quote(smart_str(self.username))
132  
-
133  
-  def get_full_name(self):
134  
-    full_name = u'%s %s' % (self.first_name, self.last_name)
135  
-    return full_name.strip()
136  
-
137  
-  def email_user(self, subject, message, from_email):
138  
-    """Sends an email to this user.
139  
-
140  
-    According to the App Engine email API the from_email must be the
141  
-    email address of a registered administrator for the application.
142  
-    """
143  
-    mail.send_mail(subject,
144  
-                   message,
145  
-                   from_email,
146  
-                   [self.email])
147  
-
148  
-  def get_profile(self):
149  
-    """
150  
-    Returns site-specific profile for this user. Raises
151  
-    SiteProfileNotAvailable if this site does not allow profiles.
152  
-
153  
-    When using the App Engine authentication framework, users are created
154  
-    automatically.
155  
-    """
156  
-    from django.contrib.auth.models import SiteProfileNotAvailable
157  
-    if not hasattr(self, '_profile_cache'):
158  
-      from django.conf import settings
159  
-      if not hasattr(settings, "AUTH_PROFILE_MODULE"):
160  
-        raise SiteProfileNotAvailable
161  
-      try:
162  
-        app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
163  
-        model = models.get_model(app_label, model_name)
164  
-        self._profile_cache = model.all().filter("user =", self).get()
165  
-        if not self._profile_cache:
166  
-          raise model.DoesNotExist
167  
-      except (ImportError, ImproperlyConfigured):
168  
-        raise SiteProfileNotAvailable
169  
-    return self._profile_cache
170  
-
171  
-
172  
-class Group(BaseModel):
173  
-  """Group model not fully implemented yet."""
174  
-  # TODO: Implement this model, requires contenttypes
175  
-  name = db.StringProperty()
176  
-  permissions = EmptyManager()
177  
-
178  
-
179  
-class Message(BaseModel):
180  
-  """User message model"""
181  
-  user = db.ReferenceProperty(User)
182  
-  message = db.TextProperty()
183  
-
184  
-
185  
-class Permission(BaseModel):
186  
-  """Permission model not fully implemented yet."""
187  
-  # TODO: Implement this model, requires contenttypes
188  
-  name = db.StringProperty()
62  jaikuengine/appengine_django/auth/templatetags.py
... ...
@@ -1,62 +0,0 @@
1  
-# Copyright 2008 Google Inc.
2  
-#
3  
-# Licensed under the Apache License, Version 2.0 (the "License");
4  
-# you may not use this file except in compliance with the License.
5  
-# You may obtain a copy of the License at
6  
-#
7  
-#     http://www.apache.org/licenses/LICENSE-2.0
8  
-#
9  
-# Unless required by applicable law or agreed to in writing, software
10  
-# distributed under the License is distributed on an "AS IS" BASIS,
11  
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  
-# See the License for the specific language governing permissions and
13  
-# limitations under the License.
14  
-
15  
-"""
16  
-Template tags for the auth module. These are inserted into Django as "built-in"
17  
-tags so you do not need to use the load statement in your template to get
18  
-access to them.
19  
-"""
20  
-
21  
-from django.template import Library
22  
-from django.template import Node
23  
-
24  
-from google.appengine.api import users
25  
-
26  
-
27  
-class AuthLoginUrlsNode(Node):
28  
-  """Template node that creates an App Engine login or logout URL.
29  
-
30  
-  If create_login_url is True the App Engine's login URL is rendered into
31  
-  the template, otherwise the logout URL.
32  
-  """
33  
-  def __init__(self, create_login_url, redirect):
34  
-    self.redirect = redirect
35  
-    self.create_login_url = create_login_url
36  
-
37  
-  def render(self, context):
38  
-    if self.create_login_url:
39  
-      return users.create_login_url(self.redirect)
40  
-    else:
41  
-      return users.create_logout_url(self.redirect)
42  
-
43  
-
44  
-def auth_login_urls(parser, token):
45  
-  """Template tag registered as 'auth_login_url' and 'auth_logout_url'
46  
-  when the module is imported.
47  
-
48  
-  Both tags take an optional argument that specifies the redirect URL and
49  
-  defaults to '/'.
50  
-  """
51  
-  bits = list(token.split_contents())
52  
-  if len(bits) == 2:
53  
-    redirect = bits[1]
54  
-  else:
55  
-    redirect = "/"
56  
-  login = bits[0] == "auth_login_url"
57  
-  return AuthLoginUrlsNode(login, redirect)
58  
-
59  
-
60  
-register = Library()
61  
-register.tag("auth_login_url", auth_login_urls)
62  
-register.tag("auth_logout_url", auth_login_urls)
58  jaikuengine/appengine_django/auth/tests.py
... ...
@@ -1,58 +0,0 @@
1  
-# Copyright 2008 Google Inc.
2  
-#
3  
-# Licensed under the Apache License, Version 2.0 (the "License");
4  
-# you may not use this file except in compliance with the License.
5  
-# You may obtain a copy of the License at
6  
-#
7  
-#     http://www.apache.org/licenses/LICENSE-2.0
8  
-#
9  
-# Unless required by applicable law or agreed to in writing, software
10  
-# distributed under the License is distributed on an "AS IS" BASIS,
11  
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  
-# See the License for the specific language governing permissions and
13  
-# limitations under the License.
14  
-
15  
-BASIC_TESTS = """
16  
->>> from google.appengine.api import users
17  
->>> from models import User, AnonymousUser
18  
->>> appengine_user = users.User("test@example.com")
19  
->>> django_user = User.get_djangouser_for_user(appengine_user)
20  
->>> django_user.email == appengine_user.email()
21  
-True
22  
->>> django_user.username == appengine_user.nickname()
23  
-True
24  
->>> django_user.user == appengine_user
25  
-True
26  
-
27  
->>> django_user.username = 'test2'
28  
->>> key = django_user.save()
29  
->>> django_user.username == 'test2'
30  
-True
31  
-
32  
->>> django_user2 = User.get_djangouser_for_user(appengine_user)
33  
->>> django_user2 == django_user
34  
-True
35  
-
36  
->>> django_user.is_authenticated()
37  
-True
38  
->>> django_user.is_staff
39  
-False
40  
->>> django_user.is_active
41  
-True
42  
-
43  
->>> a = AnonymousUser()
44  
->>> a.is_authenticated()
45  
-False
46  
->>> a.is_staff
47  
-False
48  
->>> a.is_active
49  
-False
50  
->>> a.groups.all()
51  
-[]
52  
->>> a.user_permissions.all()
53  
-[]
54  
-
55  
-
56  
-"""
57  
-
58  
-__test__ = {'BASIC_TESTS': BASIC_TESTS}
0  jaikuengine/appengine_django/conf/app_template/__init__.py
No changes.
4  jaikuengine/appengine_django/conf/app_template/models.py
... ...
@@ -1,4 +0,0 @@
1  
-from appengine_django.models import BaseModel
2  
-from google.appengine.ext import db
3  
-
4  
-# Create your models here.
1  jaikuengine/appengine_django/conf/app_template/views.py
... ...
@@ -1 +0,0 @@
1  
-# Create your views here.
20  jaikuengine/appengine_django/db/__init__.py
... ...
@@ -1,20 +0,0 @@
1  
-# Copyright 2008 Google Inc.
2  
-#
3  
-# Licensed under the Apache License, Version 2.0 (the "License");
4  
-# you may not use this file except in compliance with the License.
5  
-# You may obtain a copy of the License at
6  
-#
7  
-#     http://www.apache.org/licenses/LICENSE-2.0
8  
-#
9  
-# Unless required by applicable law or agreed to in writing, software
10  
-# distributed under the License is distributed on an "AS IS" BASIS,
11  
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  
-# See the License for the specific language governing permissions and
13  
-# limitations under the License.
14  
-
15  
-# Explicitly set the name of this package to "appengine".
16  
-#
17  
-# The rationale for this is so that Django can refer to the database as
18  
-# "appengine" even though at a filesystem level it appears as the "db" package
19  
-# within the appengine_django package.
20  
-__name__ = "appengine"
150  jaikuengine/appengine_django/db/base.py
... ...
@@ -1,150 +0,0 @@
1  
-#!/usr/bin/python2.4
2  
-#
3  
-# Copyright 2008 Google Inc.
4  
-#
5  
-# Licensed under the Apache License, Version 2.0 (the "License");
6  
-# you may not use this file except in compliance with the License.
7  
-# You may obtain a copy of the License at