Permalink
Browse files

[multi-db] Merged trunk to [3890]

  • Loading branch information...
1 parent 261fb45 commit e07dae7b77abc39d3e5d99dece5d43a5b99890f4 @jpellerin jpellerin committed Dec 4, 2006
View
@@ -75,6 +75,7 @@ answer newbie questions, and generally made Django that much better:
Jeremy Dunck <http://dunck.us/>
Andy Dustman <farcepest@gmail.com>
Clint Ecker
+ Enrico <rico.bl@gmail.com>
favo@exoweb.net
gandalf@owca.info
Baishampayan Ghose
@@ -226,10 +226,6 @@
# http://www.djangoproject.com/documentation/templates/#now
MONTH_DAY_FORMAT = 'F j'
-# Whether to enable Psyco, which optimizes Python code. Requires Psyco.
-# http://psyco.sourceforge.net/
-ENABLE_PSYCO = False
-
# Do you want to manage transactions manually?
# Hint: you really don't!
TRANSACTIONS_MANAGED = False
@@ -87,7 +87,7 @@ def _checklogin(request, *args, **kwargs):
# The user data is correct; log in the user in and continue.
else:
- if user.is_staff:
+ if user.is_active and user.is_staff:
login(request, user)
# TODO: set last_login with an event.
user.last_login = datetime.datetime.now()
@@ -216,6 +216,8 @@ def has_perms(self, perm_list):
def has_module_perms(self, app_label):
"Returns True if the user has any permissions in the given app label."
+ if not self.is_active:
+ return False
if self.is_superuser:
return True
return bool(len([p for p in self.get_all_permissions() if p[:p.index('.')] == app_label]))
@@ -89,7 +89,8 @@ def get_response(self, request):
return response
except http.Http404, e:
if settings.DEBUG:
- return self.get_technical_error_response(request, is404=True, exception=e)
+ from django.views import debug
+ return debug.technical_404_response(request, e)
else:
callback, param_dict = resolver.resolve404()
return callback(request, **param_dict)
@@ -99,7 +100,8 @@ def get_response(self, request):
pass # See http://code.djangoproject.com/ticket/1023
except: # Handle everything else, including SuspiciousOperation, etc.
if settings.DEBUG:
- return self.get_technical_error_response(request)
+ from django.views import debug
+ return debug.technical_500_response(request, *sys.exc_info())
else:
# Get the exception info now, in case another exception is thrown later.
exc_info = sys.exc_info()
@@ -112,26 +114,9 @@ def get_response(self, request):
request_repr = "Request repr() unavailable"
message = "%s\n\n%s" % (self._get_traceback(exc_info), request_repr)
mail_admins(subject, message, fail_silently=True)
- return self.get_friendly_error_response(request, resolver)
-
- def get_friendly_error_response(self, request, resolver):
- """
- Returns an HttpResponse that displays a PUBLIC error message for a
- fundamental error.
- """
- callback, param_dict = resolver.resolve500()
- return callback(request, **param_dict)
-
- def get_technical_error_response(self, request, is404=False, exception=None):
- """
- Returns an HttpResponse that displays a TECHNICAL error message for a
- fundamental error.
- """
- from django.views import debug
- if is404:
- return debug.technical_404_response(request, exception)
- else:
- return debug.technical_500_response(request, *sys.exc_info())
+ # Return an HttpResponse that displays a friendly error message.
+ callback, param_dict = resolver.resolve500()
+ return callback(request, **param_dict)
def _get_traceback(self, exc_info=None):
"Helper function to return the traceback as a string"
@@ -139,10 +139,6 @@ def __call__(self, req):
# that use settings now can work
from django.conf import settings
- if settings.ENABLE_PSYCO:
- import psyco
- psyco.profile()
-
# if we need to set up middleware, now that settings works we can do it now.
if self._request_middleware is None:
self.load_middleware()
@@ -160,23 +156,20 @@ def __call__(self, req):
dispatcher.send(signal=signals.request_finished)
# Convert our custom HttpResponse object back into the mod_python req.
- populate_apache_request(response, req)
- return 0 # mod_python.apache.OK
+ req.content_type = response['Content-Type']
+ for key, value in response.headers.items():
+ if key != 'Content-Type':
+ req.headers_out[key] = value
+ for c in response.cookies.values():
+ req.headers_out.add('Set-Cookie', c.output(header=''))
+ req.status = response.status_code
+ try:
+ for chunk in response:
+ req.write(chunk)
+ finally:
+ response.close()
-def populate_apache_request(http_response, mod_python_req):
- "Populates the mod_python request object with an HttpResponse"
- mod_python_req.content_type = http_response['Content-Type']
- for key, value in http_response.headers.items():
- if key != 'Content-Type':
- mod_python_req.headers_out[key] = value
- for c in http_response.cookies.values():
- mod_python_req.headers_out.add('Set-Cookie', c.output(header=''))
- mod_python_req.status = http_response.status_code
- try:
- for chunk in http_response:
- mod_python_req.write(chunk)
- finally:
- http_response.close()
+ return 0 # mod_python.apache.OK
def handler(req):
# mod_python hooks into this function.
@@ -174,10 +174,6 @@ class WSGIHandler(BaseHandler):
def __call__(self, environ, start_response):
from django.conf import settings
- if settings.ENABLE_PSYCO:
- import psyco
- psyco.profile()
-
# Set up middleware if needed. We couldn't do this earlier, because
# settings weren't available.
if self._request_middleware is None:
@@ -230,7 +230,6 @@ def get_sql_indexes(app):
from django.db import model_connection_name
from django.db.models import get_models
connection_output = {}
-
for model in get_models(app):
opts = model._meta
connection_name = model_connection_name(model)
@@ -242,6 +241,23 @@ def get_sql_indexes(app):
get_sql_indexes.help_doc = "Prints the CREATE INDEX SQL statements for the given model module name(s)."
get_sql_indexes.args = APP_ARGS
+def _get_sql_index(model):
+ "Returns the CREATE INDEX SQL statements for a specific model"
+ from django.db import backend
+ output = []
+
+ for f in model._meta.fields:
+ if f.db_index:
+ unique = f.unique and 'UNIQUE ' or ''
+ output.append(
+ style.SQL_KEYWORD('CREATE %sINDEX' % unique) + ' ' + \
+ style.SQL_TABLE('%s_%s' % (model._meta.db_table, f.column)) + ' ' + \
+ style.SQL_KEYWORD('ON') + ' ' + \
+ style.SQL_TABLE(backend.quote_name(model._meta.db_table)) + ' ' + \
+ "(%s);" % style.SQL_FIELD(backend.quote_name(f.column))
+ )
+ return output
+
def get_sql_all(app):
"Returns a list of CREATE TABLE SQL, initial-data inserts, and CREATE INDEX SQL for the given module."
return get_sql_create(app) + get_sql_initial_data(app) + get_sql_indexes(app)
@@ -269,7 +285,7 @@ def _collate(connection_output, reverse=False):
connection_name)
return map(str, final_output)
-def syncdb(verbosity=2, interactive=True):
+def syncdb(verbosity=1, interactive=True):
"Creates the database tables for all apps in INSTALLED_APPS whose tables haven't already been created."
from django.conf import settings
from django.db import models, transaction
@@ -296,8 +312,9 @@ def syncdb(verbosity=2, interactive=True):
for app in models.get_apps():
# Install each application (models already installed will be skipped)
created, pending = _install(app, commit=False, initial_data=False,
- pending_allowed=True, pending=pending)
- if verbosity >= 2:
+ pending_allowed=True, pending=pending,
+ verbosity=verbosity)
+ if verbosity >= 1:
for model in created:
print "Created table %s" % model._meta.db_table
created_models.extend(created)
@@ -311,6 +328,8 @@ def syncdb(verbosity=2, interactive=True):
# Send the post_syncdb signal, so individual apps can do whatever they need
# to do at this point.
for app in models.get_apps():
+ if verbosity >= 2:
+ print "Sending post-syncdb signal for application", app.__name__.split('.')[-2]
dispatcher.send(signal=signals.post_syncdb, sender=app,
app=app, created_models=created_models,
verbosity=verbosity, interactive=interactive)
@@ -322,7 +341,7 @@ def syncdb(verbosity=2, interactive=True):
if model in created_models:
try:
if (model._default_manager.load_initial_data()
- and verbosity >= 2):
+ and verbosity >= 1):
print "Installed initial data for %s model" % model._meta.object_name
except Exception, e:
sys.stderr.write("Failed to install initial SQL data for %s model: %s" % \
@@ -391,7 +410,7 @@ def install(app):
_install(app)
def _install(app, commit=True, initial_data=True, pending_allowed=False,
- pending=None):
+ pending=None, verbosity=1):
from django.db import connection, models, transaction
import sys
@@ -407,6 +426,9 @@ def _install(app, commit=True, initial_data=True, pending_allowed=False,
if pending is None:
pending = {}
for model in models.get_models(app, creation_order=True):
+ if verbosity >= 2:
+ print "Processing %s.%s model" % (app_name,
+ model._meta.object_name)
manager = model._default_manager
tables = manager.get_table_list()
models_installed = manager.get_installed_models(tables)
@@ -445,7 +467,7 @@ def _install(app, commit=True, initial_data=True, pending_allowed=False,
install.help_doc = "Executes ``sqlall`` for the given app(s) in the current database."
install.args = APP_ARGS
-def reset(app):
+def reset(app, interactive=True):
"Executes the equivalent of 'get_sql_reset' in the current database."
from django.db import connection, transaction
app_name = app.__name__.split('.')[-2]
@@ -456,21 +478,25 @@ def reset(app):
_check_for_validation_errors(app)
sql_list = get_sql_reset(app)
- confirm = raw_input("""
+ if interactive:
+ confirm = raw_input("""
You have requested a database reset.
This will IRREVERSIBLY DESTROY any data in your database.
Are you sure you want to do this?
Type 'yes' to continue, or 'no' to cancel: """)
+ else:
+ confirm = 'yes'
+
if confirm == 'yes':
try:
cursor = connection.cursor()
for sql in sql_list:
cursor.execute(sql)
except Exception, e:
- sys.stderr.write(style.ERROR("""Error: %s couldn't be installed. Possible reasons:
+ sys.stderr.write(style.ERROR("""Error: %s couldn't be reset. Possible reasons:
* The database isn't running or isn't configured correctly.
- * At least one of the database tables already exists.
+ * At least one of the database tables doesn't exist.
* The SQL was invalid.
Hint: Look at the output of 'django-admin.py sqlreset %s'. That's the SQL this command wasn't able to run.
The full error: """ % (app_name, app_name)) + style.ERROR_OUTPUT(str(e)) + '\n')
@@ -1031,7 +1057,7 @@ def runfcgi(args):
runfastcgi(args)
runfcgi.args = '[various KEY=val options, use `runfcgi help` for help]'
-def test(verbosity, app_labels):
+def test(app_labels, verbosity=1):
"Runs the test suite for the specified applications"
from django.conf import settings
from django.db.models import get_app, get_apps
@@ -1133,7 +1159,7 @@ def execute_from_command_line(action_mapping=DEFAULT_ACTION_MAPPING, argv=None):
help='Tells Django to NOT prompt the user for input of any kind.')
parser.add_option('--noreload', action='store_false', dest='use_reloader', default=True,
help='Tells Django to NOT use the auto-reloader when running the development server.')
- parser.add_option('--verbosity', action='store', dest='verbosity', default='2',
+ parser.add_option('--verbosity', action='store', dest='verbosity', default='1',
type='choice', choices=['0', '1', '2'],
help='Verbosity level; 0=minimal output, 1=normal output, 2=all output'),
parser.add_option('--adminmedia', dest='admin_media_path', default='', help='Specifies the directory from which to serve admin media for runserver.'),
@@ -1182,7 +1208,7 @@ def execute_from_command_line(action_mapping=DEFAULT_ACTION_MAPPING, argv=None):
parser.print_usage_and_exit()
elif action == 'test':
try:
- action_mapping[action](int(options.verbosity), args[1:])
+ action_mapping[action](args[1:], int(options.verbosity))
except IndexError:
parser.print_usage_and_exit()
elif action in ('startapp', 'startproject'):
@@ -1216,7 +1242,10 @@ def execute_from_command_line(action_mapping=DEFAULT_ACTION_MAPPING, argv=None):
if action not in NO_SQL_TRANSACTION:
print style.SQL_KEYWORD("BEGIN;")
for mod in mod_list:
- output = action_mapping[action](mod)
+ if action == 'reset':
+ output = action_mapping[action](mod, options.interactive)
+ else:
+ output = action_mapping[action](mod)
if output:
print '\n'.join(output)
if action not in NO_SQL_TRANSACTION:
View
@@ -82,7 +82,7 @@ There are also a few styles for styling text.
.help
This is a custom class for blocks of inline help text explaining the
function of form elements. It makes text smaller and gray, and when applied
- to ``p`` elements withing ``.form-row`` elements (see Form Styles below),
+ to ``p`` elements within ``.form-row`` elements (see Form Styles below),
it will offset the text to align with the form field. Use this for help
text, instead of ``small quiet``. It works on other elements, but try to
put the class on a ``p`` whenever you can.
@@ -170,4 +170,4 @@ Labels
Form labels should always precede the field, except in the case
of checkboxes and radio buttons, where the ``input`` should come first. Any
explanation or help text should follow the ``label`` in a ``p`` with class
-``.help``.
+``.help``.
@@ -82,7 +82,7 @@ that 90% of Django can be considered forwards-compatible at this point.
That said, these APIs should *not* be considered stable, and are likely to
change:
- - `Forms and validation`_ will most likely be compeltely rewritten to
+ - `Forms and validation`_ will most likely be completely rewritten to
deemphasize Manipulators in favor of validation-aware models.
- `Serialization`_ is under heavy development; changes are likely.
@@ -91,7 +91,7 @@ change:
API changes may be necessary.
- Generic relations will most likely be moved out of core and into the
- content-types contrib package to avoid core dependacies on optional
+ content-types contrib package to avoid core dependancies on optional
components.
- The comments framework, which is yet undocumented, will likely get a complete
Oops, something went wrong.

0 comments on commit e07dae7

Please sign in to comment.