Django

Code

Changeset 6637

Show
Ignore:
Timestamp:
11/02/07 21:15:27 (1 year ago)
Author:
mtredinnick
Message:

queryset-refactor: Merged from trunk up to [6623].

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/branches/queryset-refactor/django/conf/locale/es/LC_MESSAGES/django.po

    r6597 r6637  
    10171017#: contrib/admin/views/main.py:780 
    10181018msgid "Database error" 
    1019 msgstr "Erorr en la base de datos" 
     1019msgstr "Error en la base de datos" 
    10201020 
    10211021#: contrib/auth/forms.py:17 
  • django/branches/queryset-refactor/django/contrib/auth/forms.py

    r5803 r6637  
    105105                'user': user, 
    106106                } 
    107             send_mail('Password reset on %s' % site_name, t.render(Context(c)), None, [user.email]) 
     107            send_mail(_('Password reset on %s') % site_name, t.render(Context(c)), None, [user.email]) 
    108108 
    109109class PasswordChangeForm(oldforms.Manipulator): 
  • django/branches/queryset-refactor/django/core/management/commands/startapp.py

    r6466 r6637  
    1 from django.core.management.base import copy_helper, CommandError, LabelCommand 
    21import os 
    32 
     3from django.core.management.base import copy_helper, CommandError, LabelCommand 
     4 
    45class Command(LabelCommand): 
    5     help = "Creates a Django app directory structure for the given app name in the current directory." 
     6    help = ("Creates a Django app directory structure for the given app name" 
     7            " in the current directory.") 
    68    args = "[appname]" 
    79    label = 'application name' 
     
    1517        if directory is None: 
    1618            directory = os.getcwd() 
    17         # Determine the project_name a bit naively -- by looking at the name of 
    18         # the parent directory. 
    19         project_dir = os.path.normpath(os.path.join(directory, os.pardir)) 
    20         parent_dir = os.path.basename(project_dir) 
     19        # Determine the project_name by using the basename of directory, 
     20        # which should be the full path of the project directory (or the 
     21        # current directory if no directory was passed). 
    2122        project_name = os.path.basename(directory) 
    2223        if app_name == project_name: 
    23             raise CommandError("You cannot create an app with the same name (%r) as your project." % app_name) 
    24         copy_helper(self.style, 'app', app_name, directory, parent_dir) 
     24            raise CommandError("You cannot create an app with the same name" 
     25                               " (%r) as your project." % app_name) 
     26        copy_helper(self.style, 'app', app_name, directory, project_name) 
    2527 
    2628class ProjectCommand(Command): 
    27     help = "Creates a Django app directory structure for the given app name in this project's directory." 
     29    help = ("Creates a Django app directory structure for the given app name" 
     30            " in this project's directory.") 
    2831 
    2932    def __init__(self, project_directory): 
  • django/branches/queryset-refactor/django/core/management/__init__.py

    r6597 r6637  
    243243    Configures the runtime environment. This can also be used by external 
    244244    scripts wanting to set up a similar environment to manage.py. 
     245    Returns the project directory (assuming the passed settings module is 
     246    directly in the project directory). 
    245247    """ 
    246248    # Add this project to sys.path so that it's importable in the conventional 
  • django/branches/queryset-refactor/django/db/backends/__init__.py

    r6335 r6637  
    128128        raise NotImplementedError('Full-text search is not implemented for this database backend') 
    129129 
     130    def last_executed_query(self, cursor, sql, params): 
     131        """ 
     132        Returns a string of the query last executed by the given cursor, with 
     133        placeholders replaced with actual values. 
     134 
     135        `sql` is the raw query containing placeholders, and `params` is the 
     136        sequence of parameters. These are used by default, but this method 
     137        exists for database backends to provide a better implementation 
     138        according to their own quoting schemes. 
     139        """ 
     140        from django.utils.encoding import smart_unicode, force_unicode 
     141 
     142        # Convert params to contain Unicode values. 
     143        to_unicode = lambda s: force_unicode(s, strings_only=True) 
     144        if isinstance(params, (list, tuple)): 
     145            u_params = tuple([to_unicode(val) for val in params]) 
     146        else: 
     147            u_params = dict([(to_unicode(k), to_unicode(v)) for k, v in params.items()]) 
     148 
     149        return smart_unicode(sql) % u_params 
     150 
    130151    def last_insert_id(self, cursor, table_name, pk_name): 
    131152        """ 
  • django/branches/queryset-refactor/django/db/backends/postgresql_psycopg2/base.py

    r6012 r6637  
    66 
    77from django.db.backends import BaseDatabaseWrapper, BaseDatabaseFeatures 
    8 from django.db.backends.postgresql.operations import DatabaseOperations 
     8from django.db.backends.postgresql.operations import DatabaseOperations as PostgresqlDatabaseOperations 
    99try: 
    1010    import psycopg2 as Database 
     
    2121class DatabaseFeatures(BaseDatabaseFeatures): 
    2222    needs_datetime_string_cast = False 
     23 
     24class DatabaseOperations(PostgresqlDatabaseOperations): 
     25    def last_executed_query(self, cursor, sql, params): 
     26        # With psycopg2, cursor objects have a "query" attribute that is the 
     27        # exact query sent to the database. See docs here: 
     28        # http://www.initd.org/tracker/psycopg/wiki/psycopg2_documentation#postgresql-status-message-and-executed-query 
     29        return cursor.query 
    2330 
    2431class DatabaseWrapper(BaseDatabaseWrapper): 
  • django/branches/queryset-refactor/django/db/backends/util.py

    r5971 r6637  
    22import md5 
    33from time import time 
    4 from django.utils.encoding import smart_unicode, force_unicode 
    54 
    65try: 
     
    1211    def __init__(self, cursor, db): 
    1312        self.cursor = cursor 
    14         self.db = db 
     13        self.db = db # Instance of a BaseDatabaseWrapper subclass 
    1514 
    1615    def execute(self, sql, params=()): 
     
    2019        finally: 
    2120            stop = time() 
     21            sql = self.db.ops.last_executed_query(self.cursor, sql, params) 
    2222            self.db.queries.append({ 
    23                 'sql': smart_unicode(sql) % convert_args(params)
     23                'sql': sql
    2424                'time': "%.3f" % (stop - start), 
    2525            }) 
     
    3232            stop = time() 
    3333            self.db.queries.append({ 
    34                 'sql': 'MANY: ' + sql + ' ' + smart_unicode(tuple(param_list)), 
     34                'sql': '%s times: %s' % (len(param_list), sql), 
    3535                'time': "%.3f" % (stop - start), 
    3636            }) 
     
    4141        else: 
    4242            return getattr(self.cursor, attr) 
    43  
    44 def convert_args(args): 
    45     """ 
    46     Convert sequence or dictionary to contain unicode values. 
    47     """ 
    48     to_unicode = lambda s: force_unicode(s, strings_only=True) 
    49     if isinstance(args, (list, tuple)): 
    50         return tuple([to_unicode(val) for val in args]) 
    51     else: 
    52         return dict([(to_unicode(k), to_unicode(v)) for k, v in args.items()]) 
    5343 
    5444############################################### 
  • django/branches/queryset-refactor/django/newforms/fields.py

    r6597 r6637  
    11""" 
    2 Field classes 
     2Field classes. 
    33""" 
    44 
     
    77import re 
    88import time 
    9  
    10 from django.utils.translation import ugettext 
    11 from django.utils.encoding import StrAndUnicode, smart_unicode 
    12  
    13 from util import ErrorList, ValidationError 
    14 from widgets import TextInput, PasswordInput, HiddenInput, MultipleHiddenInput, FileInput, CheckboxInput, Select, NullBooleanSelect, SelectMultiple, DateTimeInput 
    15  
     9# Python 2.3 fallbacks 
    1610try: 
    1711    from decimal import Decimal, DecimalException 
    1812except ImportError: 
    1913    from django.utils._decimal import Decimal, DecimalException 
     14try: 
     15    set 
     16except NameError: 
     17    from sets import Set as set 
     18 
     19from django.utils.translation import ugettext 
     20from django.utils.encoding import StrAndUnicode, smart_unicode 
     21 
     22from util import ErrorList, ValidationError 
     23from widgets import TextInput, PasswordInput, HiddenInput, MultipleHiddenInput, FileInput, CheckboxInput, Select, NullBooleanSelect, SelectMultiple, DateTimeInput 
     24 
    2025 
    2126__all__ = ( 
     
    2429    'DEFAULT_TIME_INPUT_FORMATS', 'TimeField', 
    2530    'DEFAULT_DATETIME_INPUT_FORMATS', 'DateTimeField', 
    26     'RegexField', 'EmailField', 'FileField', 'ImageField', 'URLField', 'BooleanField', 
    27     'ChoiceField', 'NullBooleanField', 'MultipleChoiceField', 
     31    'RegexField', 'EmailField', 'FileField', 'ImageField', 'URLField', 
     32    'BooleanField', 'NullBooleanField', 'ChoiceField', 'MultipleChoiceField', 
    2833    'ComboField', 'MultiValueField', 'FloatField', 'DecimalField', 
    2934    'SplitDateTimeField', 'IPAddressField', 
     
    3338EMPTY_VALUES = (None, '') 
    3439 
    35 try: 
    36     set 
    37 except NameError: 
    38     from sets import Set as set   # Python 2.3 fallback 
    39  
    40 try: 
    41     from decimal import Decimal 
    42 except ImportError: 
    43     from django.utils._decimal import Decimal   # Python 2.3 fallback 
    4440 
    4541class Field(object): 
  • django/branches/queryset-refactor/django/utils/translation/trans_real.py

    r6597 r6637  
    11"Translation helper functions" 
    22 
    3 import os, re, sys 
     3import locale 
     4import os 
     5import re 
     6import sys 
    47import gettext as gettext_module 
    58from cStringIO import StringIO 
     9 
    610from django.utils.encoding import force_unicode 
    711 
     
    2630_default = None 
    2731 
    28 # This is a cache for accept-header to translation object mappings to prevent 
    29 # the accept parser to run multiple times for one user
     32# This is a cache for normalised accept-header languages to prevent multiple 
     33# file lookups when checking the same locale on repeated requests
    3034_accepted = {} 
    3135 
    32 def to_locale(language): 
     36# Format of Accept-Language header values. From RFC 2616, section 14.4 and 3.9. 
     37accept_language_re = re.compile(r''' 
     38        ([A-Za-z]{1,8}(?:-[A-Za-z]{1,8})*|\*)   # "en", "en-au", "x-y-z", "*" 
     39        (?:;q=(0(?:\.\d{,3})?|1(?:.0{,3})?))?   # Optional "q=1.00", "q=0.8" 
     40        (?:\s*,\s*|$)                            # Multiple accepts per header. 
     41        ''', re.VERBOSE) 
     42 
     43def to_locale(language, to_lower=False): 
    3344    "Turns a language name (en-us) into a locale name (en_US)." 
    3445    p = language.find('-') 
    3546    if p >= 0: 
    36         return language[:p].lower()+'_'+language[p+1:].upper() 
     47        if to_lower: 
     48            return language[:p].lower()+'_'+language[p+1:].lower() 
     49        else: 
     50            return language[:p].lower()+'_'+language[p+1:].upper() 
    3751    else: 
    3852        return language.lower() 
     
    335349            return lang_code 
    336350 
    337     lang_code = request.COOKIES.get('django_language', None
    338     if lang_code in supported and lang_code is not None and check_for_language(lang_code): 
     351    lang_code = request.COOKIES.get('django_language'
     352    if lang_code and lang_code in supported and check_for_language(lang_code): 
    339353        return lang_code 
    340354 
    341     accept = request.META.get('HTTP_ACCEPT_LANGUAGE', None) 
    342     if accept is not None: 
    343  
    344         t = _accepted.get(accept, None) 
    345         if t is not None: 
    346             return t 
    347  
    348         def _parsed(el): 
    349             p = el.find(';q=') 
    350             if p >= 0: 
    351                 lang = el[:p].strip() 
    352                 order = int(float(el[p+3:].strip())*100) 
    353             else: 
    354                 lang = el 
    355                 order = 100 
    356             p = lang.find('-') 
    357             if p >= 0: 
    358                 mainlang = lang[:p] 
    359             else: 
    360                 mainlang = lang 
    361             return (lang, mainlang, order) 
    362  
    363         langs = [_parsed(el) for el in accept.split(',')] 
    364         langs.sort(lambda a,b: -1*cmp(a[2], b[2])) 
    365  
    366         for lang, mainlang, order in langs: 
    367             if lang in supported or mainlang in supported: 
    368                 langfile = gettext_module.find('django', globalpath, [to_locale(lang)]) 
    369                 if langfile: 
    370                     # reconstruct the actual language from the language 
    371                     # filename, because otherwise we might incorrectly 
    372                     # report de_DE if we only have de available, but 
    373                     # did find de_DE because of language normalization 
    374                     lang = langfile[len(globalpath):].split(os.path.sep)[1] 
    375                     _accepted[accept] = lang 
    376                     return lang 
     355    accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '') 
     356    for lang, unused in parse_accept_lang_header(accept): 
     357        if lang == '*': 
     358            break 
     359 
     360        # We have a very restricted form for our language files (no encoding 
     361        # specifier, since they all must be UTF-8 and only one possible 
     362        # language each time. So we avoid the overhead of gettext.find() and 
     363        # look up the MO file manually. 
     364 
     365        normalized = locale.locale_alias.get(to_locale(lang, True)) 
     366        if not normalized: 
     367            continue 
     368 
     369        # Remove the default encoding from locale_alias 
     370        normalized = normalized.split('.')[0] 
     371 
     372        if normalized in _accepted: 
     373            # We've seen this locale before and have an MO file for it, so no 
     374            # need to check again. 
     375            return _accepted[normalized] 
     376 
     377        for lang in (normalized, normalized.split('_')[0]): 
     378            if lang not in supported: 
     379                continue 
     380            langfile = os.path.join(globalpath, lang, 'LC_MESSAGES', 
     381                    'django.mo') 
     382            if os.path.exists(langfile): 
     383                _accepted[normalized] = lang 
     384            return lang 
    377385 
    378386    return settings.LANGUAGE_CODE 
     
    506514    return out.getvalue() 
    507515 
     516def parse_accept_lang_header(lang_string): 
     517    """ 
     518    Parses the lang_string, which is the body of an HTTP Accept-Language 
     519    header, and returns a list of (lang, q-value), ordered by 'q' values. 
     520 
     521    Any format errors in lang_string results in an empty list being returned. 
     522    """ 
     523    result = [] 
     524    pieces = accept_language_re.split(lang_string) 
     525    if pieces[-1]: 
     526        return [] 
     527    for i in range(0, len(pieces) - 1, 3): 
     528        first, lang, priority = pieces[i : i + 3] 
     529        if first: 
     530            return [] 
     531        priority = priority and float(priority) or 1.0 
     532        result.append((lang, priority)) 
     533    result.sort(lambda x, y: -cmp(x[1], y[1])) 
     534    return result 
     535 
  • django/branches/queryset-refactor/docs/django-admin.txt

    r6466 r6637  
    742742**New in Django development version** 
    743743 
    744 If you want to add an action of your own to ``manage.py``, you can. 
    745 Simply add a ``management/commands`` directory to your application. 
    746 Each python module in that directory will be discovered and registered as 
     744Applications can register their own actions with ``manage.py``. For example, 
     745you might want to add a ``manage.py`` action for a Django app that you're 
     746distributing. 
     747 
     748To do this, just add a ``management/commands`` directory to your application. 
     749Each Python module in that directory will be auto-discovered and registered as 
    747750a command that can be executed as an action when you run ``manage.py``:: 
    748751 
    749     /fancy_blog 
     752    blog/ 
    750753        __init__.py 
    751754        models.py 
    752         /management 
     755        management/ 
    753756            __init__.py 
    754             /commands 
     757            commands/ 
    755758                __init__.py 
    756759                explode.py 
    757760        views.py 
    758761         
    759 In this example, ``explode`` command will be made available to any project 
     762In this example, the ``explode`` command will be made available to any project 
    760763that includes the ``fancy_blog`` application in ``settings.INSTALLED_APPS``. 
    761764 
  • django/branches/queryset-refactor/tests/regressiontests/forms/regressions.py

    r6382 r6637  
    2727early and still send back the right translation. 
    2828 
    29 # XFAIL 
    3029>>> activate('de') 
    3130>>> print f.as_p() 
  • django/branches/queryset-refactor/tests/regressiontests/i18n/tests.py

    r6466 r6637  
    11# coding: utf-8 
     2import misc 
    23 
    3 ur""" 
     4regressions = ur""" 
    45Format string interpolation should work with *_lazy objects. 
    56 
     
    4041u'django' 
    4142""" 
     43 
     44__test__ = { 
     45    'regressions': regressions, 
     46    'misc': misc.tests, 
     47} 
  • django/branches/queryset-refactor/tests/regressiontests/templates/urls.py

    r5876 r6637  
    88    (r'^$', views.index), 
    99    (r'^client/(\d+)/$', views.client), 
    10     (r'^client/(\d+)/(?P<action>[^/]+)/$', views.client_action), 
     10    (r'^client/(?P<id>\d+)/(?P<action>[^/]+)/$', views.client_action), 
    1111    url(r'^named-client/(\d+)/$', views.client, name="named.client"), 
    1212