id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
2,800
sql.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/sql.py
import os import re from django.conf import settings from django.core.management.base import CommandError from django.db import models from django.db.models import get_models def sql_create(app, style, connection): "Returns a list of the CREATE TABLE SQL statements for the given app." if connection.settings_dict['ENGINE'] == 'django.db.backends.dummy': # This must be the "dummy" database backend, which means the user # hasn't set ENGINE for the databse. raise CommandError("Django doesn't know which syntax to use for your SQL statements,\n" + "because you haven't specified the ENGINE setting for the database.\n" + "Edit your settings file and change DATBASES['default']['ENGINE'] to something like\n" + "'django.db.backends.postgresql' or 'django.db.backends.mysql'.") # Get installed models, so we generate REFERENCES right. # We trim models from the current app so that the sqlreset command does not # generate invalid SQL (leaving models out of known_models is harmless, so # we can be conservative). app_models = models.get_models(app, include_auto_created=True) final_output = [] tables = connection.introspection.table_names() known_models = set([model for model in connection.introspection.installed_models(tables) if model not in app_models]) pending_references = {} for model in app_models: output, references = connection.creation.sql_create_model(model, style, known_models) final_output.extend(output) for refto, refs in references.items(): pending_references.setdefault(refto, []).extend(refs) if refto in known_models: final_output.extend(connection.creation.sql_for_pending_references(refto, style, pending_references)) final_output.extend(connection.creation.sql_for_pending_references(model, style, pending_references)) # Keep track of the fact that we've created the table for this model. known_models.add(model) # Handle references to tables that are from other apps # but don't exist physically. not_installed_models = set(pending_references.keys()) if not_installed_models: alter_sql = [] for model in not_installed_models: alter_sql.extend(['-- ' + sql for sql in connection.creation.sql_for_pending_references(model, style, pending_references)]) if alter_sql: final_output.append('-- The following references should be added but depend on non-existent tables:') final_output.extend(alter_sql) return final_output def sql_delete(app, style, connection): "Returns a list of the DROP TABLE SQL statements for the given app." # This should work even if a connection isn't available try: cursor = connection.cursor() except: cursor = None # Figure out which tables already exist if cursor: table_names = connection.introspection.get_table_list(cursor) else: table_names = [] output = [] # Output DROP TABLE statements for standard application tables. to_delete = set() references_to_delete = {} app_models = models.get_models(app, include_auto_created=True) for model in app_models: if cursor and connection.introspection.table_name_converter(model._meta.db_table) in table_names: # The table exists, so it needs to be dropped opts = model._meta for f in opts.local_fields: if f.rel and f.rel.to not in to_delete: references_to_delete.setdefault(f.rel.to, []).append( (model, f) ) to_delete.add(model) for model in app_models: if connection.introspection.table_name_converter(model._meta.db_table) in table_names: output.extend(connection.creation.sql_destroy_model(model, references_to_delete, style)) # Close database connection explicitly, in case this output is being piped # directly into a database client, to avoid locking issues. if cursor: cursor.close() connection.close() return output[::-1] # Reverse it, to deal with table dependencies. def sql_reset(app, style, connection): "Returns a list of the DROP TABLE SQL, then the CREATE TABLE SQL, for the given module." # This command breaks a lot and should be deprecated import warnings warnings.warn( 'This command has been deprecated. The command ``sqlflush`` can be used to delete everything. You can also use ALTER TABLE or DROP TABLE statements manually.', PendingDeprecationWarning ) return sql_delete(app, style, connection) + sql_all(app, style, connection) def sql_flush(style, connection, only_django=False): """ Returns a list of the SQL statements used to flush the database. If only_django is True, then only table names that have associated Django models and are in INSTALLED_APPS will be included. """ if only_django: tables = connection.introspection.django_table_names(only_existing=True) else: tables = connection.introspection.table_names() statements = connection.ops.sql_flush( style, tables, connection.introspection.sequence_list() ) return statements def sql_custom(app, style, connection): "Returns a list of the custom table modifying SQL statements for the given app." output = [] app_models = get_models(app) app_dir = os.path.normpath(os.path.join(os.path.dirname(app.__file__), 'sql')) for model in app_models: output.extend(custom_sql_for_model(model, style, connection)) return output def sql_indexes(app, style, connection): "Returns a list of the CREATE INDEX SQL statements for all models in the given app." output = [] for model in models.get_models(app): output.extend(connection.creation.sql_indexes_for_model(model, style)) return output def sql_all(app, style, connection): "Returns a list of CREATE TABLE SQL, initial-data inserts, and CREATE INDEX SQL for the given module." return sql_create(app, style, connection) + sql_custom(app, style, connection) + sql_indexes(app, style, connection) def custom_sql_for_model(model, style, connection): opts = model._meta app_dir = os.path.normpath(os.path.join(os.path.dirname(models.get_app(model._meta.app_label).__file__), 'sql')) output = [] # Post-creation SQL should come before any initial SQL data is loaded. # However, this should not be done for models that are unmanaged or # for fields that are part of a parent model (via model inheritance). if opts.managed: post_sql_fields = [f for f in opts.local_fields if hasattr(f, 'post_create_sql')] for f in post_sql_fields: output.extend(f.post_create_sql(style, model._meta.db_table)) # Some backends can't execute more than one SQL statement at a time, # so split into separate statements. statements = re.compile(r";[ \t]*$", re.M) # Find custom SQL, if it's available. backend_name = connection.settings_dict['ENGINE'].split('.')[-1] sql_files = [os.path.join(app_dir, "%s.%s.sql" % (opts.object_name.lower(), backend_name)), os.path.join(app_dir, "%s.sql" % opts.object_name.lower())] for sql_file in sql_files: if os.path.exists(sql_file): fp = open(sql_file, 'U') for statement in statements.split(fp.read().decode(settings.FILE_CHARSET)): # Remove any comments from the file statement = re.sub(ur"--.*([\n\Z]|$)", "", statement) if statement.strip(): output.append(statement + u";") fp.close() return output def emit_post_sync_signal(created_models, verbosity, interactive, db): # Emit the post_sync signal for every application. for app in models.get_apps(): app_name = app.__name__.split('.')[-2] if verbosity >= 2: print "Running post-sync handlers for application", app_name models.signals.post_syncdb.send(sender=app, app=app, created_models=created_models, verbosity=verbosity, interactive=interactive, db=db)
8,259
Python
.py
157
45.171975
167
0.684348
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,801
__init__.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/__init__.py
import os import sys from optparse import OptionParser, NO_DEFAULT import imp import django from django.core.management.base import BaseCommand, CommandError, handle_default_options from django.utils.importlib import import_module # For backwards compatibility: get_version() used to be in this module. get_version = django.get_version # A cache of loaded commands, so that call_command # doesn't have to reload every time it's called. _commands = None def find_commands(management_dir): """ Given a path to a management directory, returns a list of all the command names that are available. Returns an empty list if no commands are defined. """ command_dir = os.path.join(management_dir, 'commands') try: return [f[:-3] for f in os.listdir(command_dir) if not f.startswith('_') and f.endswith('.py')] except OSError: return [] def find_management_module(app_name): """ Determines the path to the management module for the given app_name, without actually importing the application or the management module. Raises ImportError if the management module cannot be found for any reason. """ parts = app_name.split('.') parts.append('management') parts.reverse() part = parts.pop() path = None # When using manage.py, the project module is added to the path, # loaded, then removed from the path. This means that # testproject.testapp.models can be loaded in future, even if # testproject isn't in the path. When looking for the management # module, we need look for the case where the project name is part # of the app_name but the project directory itself isn't on the path. try: f, path, descr = imp.find_module(part,path) except ImportError,e: if os.path.basename(os.getcwd()) != part: raise e while parts: part = parts.pop() f, path, descr = imp.find_module(part, path and [path] or None) return path def load_command_class(app_name, name): """ Given a command name and an application name, returns the Command class instance. All errors raised by the import process (ImportError, AttributeError) are allowed to propagate. """ module = import_module('%s.management.commands.%s' % (app_name, name)) return module.Command() def get_commands(): """ Returns a dictionary mapping command names to their callback applications. This works by looking for a management.commands package in django.core, and in each installed application -- if a commands package exists, all commands in that package are registered. Core commands are always included. If a settings module has been specified, user-defined commands will also be included, the startproject command will be disabled, and the startapp command will be modified to use the directory in which the settings module appears. The dictionary is in the format {command_name: app_name}. Key-value pairs from this dictionary can then be used in calls to load_command_class(app_name, command_name) If a specific version of a command must be loaded (e.g., with the startapp command), the instantiated module can be placed in the dictionary in place of the application name. The dictionary is cached on the first call and reused on subsequent calls. """ global _commands if _commands is None: _commands = dict([(name, 'django.core') for name in find_commands(__path__[0])]) # Find the installed apps try: from django.conf import settings apps = settings.INSTALLED_APPS except (AttributeError, EnvironmentError, ImportError): apps = [] # Find the project directory try: from django.conf import settings module = import_module(settings.SETTINGS_MODULE) project_directory = setup_environ(module, settings.SETTINGS_MODULE) except (AttributeError, EnvironmentError, ImportError, KeyError): project_directory = None # Find and load the management module for each installed app. for app_name in apps: try: path = find_management_module(app_name) _commands.update(dict([(name, app_name) for name in find_commands(path)])) except ImportError: pass # No management module - ignore this app if project_directory: # Remove the "startproject" command from self.commands, because # that's a django-admin.py command, not a manage.py command. del _commands['startproject'] # Override the startapp command so that it always uses the # project_directory, not the current working directory # (which is default). from django.core.management.commands.startapp import ProjectCommand _commands['startapp'] = ProjectCommand(project_directory) return _commands def call_command(name, *args, **options): """ Calls the given command, with the given options and args/kwargs. This is the primary API you should use for calling specific commands. Some examples: call_command('syncdb') call_command('shell', plain=True) call_command('sqlall', 'myapp') """ # Load the command object. try: app_name = get_commands()[name] if isinstance(app_name, BaseCommand): # If the command is already loaded, use it directly. klass = app_name else: klass = load_command_class(app_name, name) except KeyError: raise CommandError("Unknown command: %r" % name) # Grab out a list of defaults from the options. optparse does this for us # when the script runs from the command line, but since call_command can # be called programatically, we need to simulate the loading and handling # of defaults (see #10080 for details). defaults = dict([(o.dest, o.default) for o in klass.option_list if o.default is not NO_DEFAULT]) defaults.update(options) return klass.execute(*args, **defaults) class LaxOptionParser(OptionParser): """ An option parser that doesn't raise any errors on unknown options. This is needed because the --settings and --pythonpath options affect the commands (and thus the options) that are available to the user. """ def error(self, msg): pass def print_help(self): """Output nothing. The lax options are included in the normal option parser, so under normal usage, we don't need to print the lax options. """ pass def print_lax_help(self): """Output the basic options available to every command. This just redirects to the default print_help() behaviour. """ OptionParser.print_help(self) def _process_args(self, largs, rargs, values): """ Overrides OptionParser._process_args to exclusively handle default options and ignore args and other options. This overrides the behavior of the super class, which stop parsing at the first unrecognized option. """ while rargs: arg = rargs[0] try: if arg[0:2] == "--" and len(arg) > 2: # process a single long option (possibly with value(s)) # the superclass code pops the arg off rargs self._process_long_opt(rargs, values) elif arg[:1] == "-" and len(arg) > 1: # process a cluster of short options (possibly with # value(s) for the last one only) # the superclass code pops the arg off rargs self._process_short_opts(rargs, values) else: # it's either a non-default option or an arg # either way, add it to the args list so we can keep # dealing with options del rargs[0] raise Exception except: largs.append(arg) class ManagementUtility(object): """ Encapsulates the logic of the django-admin.py and manage.py utilities. A ManagementUtility has a number of commands, which can be manipulated by editing the self.commands dictionary. """ def __init__(self, argv=None): self.argv = argv or sys.argv[:] self.prog_name = os.path.basename(self.argv[0]) def main_help_text(self): """ Returns the script's main help text, as a string. """ usage = ['',"Type '%s help <subcommand>' for help on a specific subcommand." % self.prog_name,''] usage.append('Available subcommands:') commands = get_commands().keys() commands.sort() for cmd in commands: usage.append(' %s' % cmd) return '\n'.join(usage) def fetch_command(self, subcommand): """ Tries to fetch the given subcommand, printing a message with the appropriate command called from the command line (usually "django-admin.py" or "manage.py") if it can't be found. """ try: app_name = get_commands()[subcommand] except KeyError: sys.stderr.write("Unknown command: %r\nType '%s help' for usage.\n" % \ (subcommand, self.prog_name)) sys.exit(1) if isinstance(app_name, BaseCommand): # If the command is already loaded, use it directly. klass = app_name else: klass = load_command_class(app_name, subcommand) return klass def autocomplete(self): """ Output completion suggestions for BASH. The output of this function is passed to BASH's `COMREPLY` variable and treated as completion suggestions. `COMREPLY` expects a space separated string as the result. The `COMP_WORDS` and `COMP_CWORD` BASH environment variables are used to get information about the cli input. Please refer to the BASH man-page for more information about this variables. Subcommand options are saved as pairs. A pair consists of the long option string (e.g. '--exclude') and a boolean value indicating if the option requires arguments. When printing to stdout, a equal sign is appended to options which require arguments. Note: If debugging this function, it is recommended to write the debug output in a separate file. Otherwise the debug output will be treated and formatted as potential completion suggestions. """ # Don't complete if user hasn't sourced bash_completion file. if not os.environ.has_key('DJANGO_AUTO_COMPLETE'): return cwords = os.environ['COMP_WORDS'].split()[1:] cword = int(os.environ['COMP_CWORD']) try: curr = cwords[cword-1] except IndexError: curr = '' subcommands = get_commands().keys() + ['help'] options = [('--help', None)] # subcommand if cword == 1: print ' '.join(sorted(filter(lambda x: x.startswith(curr), subcommands))) # subcommand options # special case: the 'help' subcommand has no options elif cwords[0] in subcommands and cwords[0] != 'help': subcommand_cls = self.fetch_command(cwords[0]) # special case: 'runfcgi' stores additional options as # 'key=value' pairs if cwords[0] == 'runfcgi': from django.core.servers.fastcgi import FASTCGI_OPTIONS options += [(k, 1) for k in FASTCGI_OPTIONS] # special case: add the names of installed apps to options elif cwords[0] in ('dumpdata', 'reset', 'sql', 'sqlall', 'sqlclear', 'sqlcustom', 'sqlindexes', 'sqlreset', 'sqlsequencereset', 'test'): try: from django.conf import settings # Get the last part of the dotted path as the app name. options += [(a.split('.')[-1], 0) for a in settings.INSTALLED_APPS] except ImportError: # Fail silently if DJANGO_SETTINGS_MODULE isn't set. The # user will find out once they execute the command. pass options += [(s_opt.get_opt_string(), s_opt.nargs) for s_opt in subcommand_cls.option_list] # filter out previously specified options from available options prev_opts = [x.split('=')[0] for x in cwords[1:cword-1]] options = filter(lambda (x, v): x not in prev_opts, options) # filter options by current input options = sorted([(k, v) for k, v in options if k.startswith(curr)]) for option in options: opt_label = option[0] # append '=' to options which require args if option[1]: opt_label += '=' print opt_label sys.exit(1) def execute(self): """ Given the command-line arguments, this figures out which subcommand is being run, creates a parser appropriate to that command, and runs it. """ # Preprocess options to extract --settings and --pythonpath. # These options could affect the commands that are available, so they # must be processed early. parser = LaxOptionParser(usage="%prog subcommand [options] [args]", version=get_version(), option_list=BaseCommand.option_list) self.autocomplete() try: options, args = parser.parse_args(self.argv) handle_default_options(options) except: pass # Ignore any option errors at this point. try: subcommand = self.argv[1] except IndexError: subcommand = 'help' # Display help if no arguments were given. if subcommand == 'help': if len(args) > 2: self.fetch_command(args[2]).print_help(self.prog_name, args[2]) else: parser.print_lax_help() sys.stderr.write(self.main_help_text() + '\n') sys.exit(1) # Special-cases: We want 'django-admin.py --version' and # 'django-admin.py --help' to work, for backwards compatibility. elif self.argv[1:] == ['--version']: # LaxOptionParser already takes care of printing the version. pass elif self.argv[1:] in (['--help'], ['-h']): parser.print_lax_help() sys.stderr.write(self.main_help_text() + '\n') else: self.fetch_command(subcommand).run_from_argv(self.argv) def setup_environ(settings_mod, original_settings_path=None): """ Configures the runtime environment. This can also be used by external scripts wanting to set up a similar environment to manage.py. Returns the project directory (assuming the passed settings module is directly in the project directory). The "original_settings_path" parameter is optional, but recommended, since trying to work out the original path from the module can be problematic. """ # Add this project to sys.path so that it's importable in the conventional # way. For example, if this file (manage.py) lives in a directory # "myproject", this code would add "/path/to/myproject" to sys.path. if '__init__.py' in settings_mod.__file__: p = os.path.dirname(settings_mod.__file__) else: p = settings_mod.__file__ project_directory, settings_filename = os.path.split(p) if project_directory == os.curdir or not project_directory: project_directory = os.getcwd() project_name = os.path.basename(project_directory) # Strip filename suffix to get the module name. settings_name = os.path.splitext(settings_filename)[0] # Strip $py for Jython compiled files (like settings$py.class) if settings_name.endswith("$py"): settings_name = settings_name[:-3] # Set DJANGO_SETTINGS_MODULE appropriately. if original_settings_path: os.environ['DJANGO_SETTINGS_MODULE'] = original_settings_path else: os.environ['DJANGO_SETTINGS_MODULE'] = '%s.%s' % (project_name, settings_name) # Import the project module. We add the parent directory to PYTHONPATH to # avoid some of the path errors new users can have. sys.path.append(os.path.join(project_directory, os.pardir)) project_module = import_module(project_name) sys.path.pop() return project_directory def execute_from_command_line(argv=None): """ A simple method that runs a ManagementUtility. """ utility = ManagementUtility(argv) utility.execute() def execute_manager(settings_mod, argv=None): """ Like execute_from_command_line(), but for use by manage.py, a project-specific django-admin.py utility. """ setup_environ(settings_mod) utility = ManagementUtility(argv) utility.execute()
17,415
Python
.py
377
36.753316
105
0.633386
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,802
validation.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/validation.py
import sys from django.contrib.contenttypes.generic import GenericForeignKey, GenericRelation from django.core.management.color import color_style from django.utils.itercompat import is_iterable try: any except NameError: from django.utils.itercompat import any class ModelErrorCollection: def __init__(self, outfile=sys.stdout): self.errors = [] self.outfile = outfile self.style = color_style() def add(self, context, error): self.errors.append((context, error)) self.outfile.write(self.style.ERROR("%s: %s\n" % (context, error))) def get_validation_errors(outfile, app=None): """ Validates all models that are part of the specified app. If no app name is provided, validates all models of all installed apps. Writes errors, if any, to outfile. Returns number of errors. """ from django.conf import settings from django.db import models, connection from django.db.models.loading import get_app_errors from django.db.models.fields.related import RelatedObject from django.db.models.deletion import SET_NULL, SET_DEFAULT e = ModelErrorCollection(outfile) for (app_name, error) in get_app_errors().items(): e.add(app_name, error) for cls in models.get_models(app): opts = cls._meta # Do field-specific validation. for f in opts.local_fields: if f.name == 'id' and not f.primary_key and opts.pk.name == 'id': e.add(opts, '"%s": You can\'t use "id" as a field name, because each model automatically gets an "id" field if none of the fields have primary_key=True. You need to either remove/rename your "id" field or add primary_key=True to a field.' % f.name) if f.name.endswith('_'): e.add(opts, '"%s": Field names cannot end with underscores, because this would lead to ambiguous queryset filters.' % f.name) if isinstance(f, models.CharField): try: max_length = int(f.max_length) if max_length <= 0: e.add(opts, '"%s": CharFields require a "max_length" attribute that is a positive integer.' % f.name) except (ValueError, TypeError): e.add(opts, '"%s": CharFields require a "max_length" attribute that is a positive integer.' % f.name) if isinstance(f, models.DecimalField): decimalp_ok, mdigits_ok = False, False decimalp_msg ='"%s": DecimalFields require a "decimal_places" attribute that is a non-negative integer.' try: decimal_places = int(f.decimal_places) if decimal_places < 0: e.add(opts, decimalp_msg % f.name) else: decimalp_ok = True except (ValueError, TypeError): e.add(opts, decimalp_msg % f.name) mdigits_msg = '"%s": DecimalFields require a "max_digits" attribute that is a positive integer.' try: max_digits = int(f.max_digits) if max_digits <= 0: e.add(opts, mdigits_msg % f.name) else: mdigits_ok = True except (ValueError, TypeError): e.add(opts, mdigits_msg % f.name) invalid_values_msg = '"%s": DecimalFields require a "max_digits" attribute value that is greater than the value of the "decimal_places" attribute.' if decimalp_ok and mdigits_ok: if decimal_places >= max_digits: e.add(opts, invalid_values_msg % f.name) if isinstance(f, models.FileField) and not f.upload_to: e.add(opts, '"%s": FileFields require an "upload_to" attribute.' % f.name) if isinstance(f, models.ImageField): # Try to import PIL in either of the two ways it can end up installed. try: from PIL import Image except ImportError: try: import Image except ImportError: e.add(opts, '"%s": To use ImageFields, you need to install the Python Imaging Library. Get it at http://www.pythonware.com/products/pil/ .' % f.name) if isinstance(f, models.BooleanField) and getattr(f, 'null', False): e.add(opts, '"%s": BooleanFields do not accept null values. Use a NullBooleanField instead.' % f.name) if f.choices: if isinstance(f.choices, basestring) or not is_iterable(f.choices): e.add(opts, '"%s": "choices" should be iterable (e.g., a tuple or list).' % f.name) else: for c in f.choices: if not isinstance(c, (list, tuple)) or len(c) != 2: e.add(opts, '"%s": "choices" should be a sequence of two-tuples.' % f.name) if f.db_index not in (None, True, False): e.add(opts, '"%s": "db_index" should be either None, True or False.' % f.name) # Perform any backend-specific field validation. connection.validation.validate_field(e, opts, f) # Check if the on_delete behavior is sane if f.rel and hasattr(f.rel, 'on_delete'): if f.rel.on_delete == SET_NULL and not f.null: e.add(opts, "'%s' specifies on_delete=SET_NULL, but cannot be null." % f.name) elif f.rel.on_delete == SET_DEFAULT and not f.has_default(): e.add(opts, "'%s' specifies on_delete=SET_DEFAULT, but has no default value." % f.name) # Check to see if the related field will clash with any existing # fields, m2m fields, m2m related objects or related objects if f.rel: if f.rel.to not in models.get_models(): e.add(opts, "'%s' has a relation with model %s, which has either not been installed or is abstract." % (f.name, f.rel.to)) # it is a string and we could not find the model it refers to # so skip the next section if isinstance(f.rel.to, (str, unicode)): continue # Make sure the related field specified by a ForeignKey is unique if not f.rel.to._meta.get_field(f.rel.field_name).unique: e.add(opts, "Field '%s' under model '%s' must have a unique=True constraint." % (f.rel.field_name, f.rel.to.__name__)) rel_opts = f.rel.to._meta rel_name = RelatedObject(f.rel.to, cls, f).get_accessor_name() rel_query_name = f.related_query_name() if not f.rel.is_hidden(): for r in rel_opts.fields: if r.name == rel_name: e.add(opts, "Accessor for field '%s' clashes with field '%s.%s'. Add a related_name argument to the definition for '%s'." % (f.name, rel_opts.object_name, r.name, f.name)) if r.name == rel_query_name: e.add(opts, "Reverse query name for field '%s' clashes with field '%s.%s'. Add a related_name argument to the definition for '%s'." % (f.name, rel_opts.object_name, r.name, f.name)) for r in rel_opts.local_many_to_many: if r.name == rel_name: e.add(opts, "Accessor for field '%s' clashes with m2m field '%s.%s'. Add a related_name argument to the definition for '%s'." % (f.name, rel_opts.object_name, r.name, f.name)) if r.name == rel_query_name: e.add(opts, "Reverse query name for field '%s' clashes with m2m field '%s.%s'. Add a related_name argument to the definition for '%s'." % (f.name, rel_opts.object_name, r.name, f.name)) for r in rel_opts.get_all_related_many_to_many_objects(): if r.get_accessor_name() == rel_name: e.add(opts, "Accessor for field '%s' clashes with related m2m field '%s.%s'. Add a related_name argument to the definition for '%s'." % (f.name, rel_opts.object_name, r.get_accessor_name(), f.name)) if r.get_accessor_name() == rel_query_name: e.add(opts, "Reverse query name for field '%s' clashes with related m2m field '%s.%s'. Add a related_name argument to the definition for '%s'." % (f.name, rel_opts.object_name, r.get_accessor_name(), f.name)) for r in rel_opts.get_all_related_objects(): if r.field is not f: if r.get_accessor_name() == rel_name: e.add(opts, "Accessor for field '%s' clashes with related field '%s.%s'. Add a related_name argument to the definition for '%s'." % (f.name, rel_opts.object_name, r.get_accessor_name(), f.name)) if r.get_accessor_name() == rel_query_name: e.add(opts, "Reverse query name for field '%s' clashes with related field '%s.%s'. Add a related_name argument to the definition for '%s'." % (f.name, rel_opts.object_name, r.get_accessor_name(), f.name)) seen_intermediary_signatures = [] for i, f in enumerate(opts.local_many_to_many): # Check to see if the related m2m field will clash with any # existing fields, m2m fields, m2m related objects or related # objects if f.rel.to not in models.get_models(): e.add(opts, "'%s' has an m2m relation with model %s, which has either not been installed or is abstract." % (f.name, f.rel.to)) # it is a string and we could not find the model it refers to # so skip the next section if isinstance(f.rel.to, (str, unicode)): continue # Check that the field is not set to unique. ManyToManyFields do not support unique. if f.unique: e.add(opts, "ManyToManyFields cannot be unique. Remove the unique argument on '%s'." % f.name) if f.rel.through is not None and not isinstance(f.rel.through, basestring): from_model, to_model = cls, f.rel.to if from_model == to_model and f.rel.symmetrical and not f.rel.through._meta.auto_created: e.add(opts, "Many-to-many fields with intermediate tables cannot be symmetrical.") seen_from, seen_to, seen_self = False, False, 0 for inter_field in f.rel.through._meta.fields: rel_to = getattr(inter_field.rel, 'to', None) if from_model == to_model: # relation to self if rel_to == from_model: seen_self += 1 if seen_self > 2: e.add(opts, "Intermediary model %s has more than " "two foreign keys to %s, which is ambiguous " "and is not permitted." % ( f.rel.through._meta.object_name, from_model._meta.object_name ) ) else: if rel_to == from_model: if seen_from: e.add(opts, "Intermediary model %s has more " "than one foreign key to %s, which is " "ambiguous and is not permitted." % ( f.rel.through._meta.object_name, from_model._meta.object_name ) ) else: seen_from = True elif rel_to == to_model: if seen_to: e.add(opts, "Intermediary model %s has more " "than one foreign key to %s, which is " "ambiguous and is not permitted." % ( f.rel.through._meta.object_name, rel_to._meta.object_name ) ) else: seen_to = True if f.rel.through not in models.get_models(include_auto_created=True): e.add(opts, "'%s' specifies an m2m relation through model " "%s, which has not been installed." % (f.name, f.rel.through) ) signature = (f.rel.to, cls, f.rel.through) if signature in seen_intermediary_signatures: e.add(opts, "The model %s has two manually-defined m2m " "relations through the model %s, which is not " "permitted. Please consider using an extra field on " "your intermediary model instead." % ( cls._meta.object_name, f.rel.through._meta.object_name ) ) else: seen_intermediary_signatures.append(signature) if not f.rel.through._meta.auto_created: seen_related_fk, seen_this_fk = False, False for field in f.rel.through._meta.fields: if field.rel: if not seen_related_fk and field.rel.to == f.rel.to: seen_related_fk = True elif field.rel.to == cls: seen_this_fk = True if not seen_related_fk or not seen_this_fk: e.add(opts, "'%s' is a manually-defined m2m relation " "through model %s, which does not have foreign keys " "to %s and %s" % (f.name, f.rel.through._meta.object_name, f.rel.to._meta.object_name, cls._meta.object_name) ) elif isinstance(f.rel.through, basestring): e.add(opts, "'%s' specifies an m2m relation through model %s, " "which has not been installed" % (f.name, f.rel.through) ) elif isinstance(f, GenericRelation): if not any([isinstance(vfield, GenericForeignKey) for vfield in f.rel.to._meta.virtual_fields]): e.add(opts, "Model '%s' must have a GenericForeignKey in " "order to create a GenericRelation that points to it." % f.rel.to.__name__ ) rel_opts = f.rel.to._meta rel_name = RelatedObject(f.rel.to, cls, f).get_accessor_name() rel_query_name = f.related_query_name() # If rel_name is none, there is no reverse accessor (this only # occurs for symmetrical m2m relations to self). If this is the # case, there are no clashes to check for this field, as there are # no reverse descriptors for this field. if rel_name is not None: for r in rel_opts.fields: if r.name == rel_name: e.add(opts, "Accessor for m2m field '%s' clashes with field '%s.%s'. Add a related_name argument to the definition for '%s'." % (f.name, rel_opts.object_name, r.name, f.name)) if r.name == rel_query_name: e.add(opts, "Reverse query name for m2m field '%s' clashes with field '%s.%s'. Add a related_name argument to the definition for '%s'." % (f.name, rel_opts.object_name, r.name, f.name)) for r in rel_opts.local_many_to_many: if r.name == rel_name: e.add(opts, "Accessor for m2m field '%s' clashes with m2m field '%s.%s'. Add a related_name argument to the definition for '%s'." % (f.name, rel_opts.object_name, r.name, f.name)) if r.name == rel_query_name: e.add(opts, "Reverse query name for m2m field '%s' clashes with m2m field '%s.%s'. Add a related_name argument to the definition for '%s'." % (f.name, rel_opts.object_name, r.name, f.name)) for r in rel_opts.get_all_related_many_to_many_objects(): if r.field is not f: if r.get_accessor_name() == rel_name: e.add(opts, "Accessor for m2m field '%s' clashes with related m2m field '%s.%s'. Add a related_name argument to the definition for '%s'." % (f.name, rel_opts.object_name, r.get_accessor_name(), f.name)) if r.get_accessor_name() == rel_query_name: e.add(opts, "Reverse query name for m2m field '%s' clashes with related m2m field '%s.%s'. Add a related_name argument to the definition for '%s'." % (f.name, rel_opts.object_name, r.get_accessor_name(), f.name)) for r in rel_opts.get_all_related_objects(): if r.get_accessor_name() == rel_name: e.add(opts, "Accessor for m2m field '%s' clashes with related field '%s.%s'. Add a related_name argument to the definition for '%s'." % (f.name, rel_opts.object_name, r.get_accessor_name(), f.name)) if r.get_accessor_name() == rel_query_name: e.add(opts, "Reverse query name for m2m field '%s' clashes with related field '%s.%s'. Add a related_name argument to the definition for '%s'." % (f.name, rel_opts.object_name, r.get_accessor_name(), f.name)) # Check ordering attribute. if opts.ordering: for field_name in opts.ordering: if field_name == '?': continue if field_name.startswith('-'): field_name = field_name[1:] if opts.order_with_respect_to and field_name == '_order': continue # Skip ordering in the format field1__field2 (FIXME: checking # this format would be nice, but it's a little fiddly). if '__' in field_name: continue try: opts.get_field(field_name, many_to_many=False) except models.FieldDoesNotExist: e.add(opts, '"ordering" refers to "%s", a field that doesn\'t exist.' % field_name) # Check unique_together. for ut in opts.unique_together: for field_name in ut: try: f = opts.get_field(field_name, many_to_many=True) except models.FieldDoesNotExist: e.add(opts, '"unique_together" refers to %s, a field that doesn\'t exist. Check your syntax.' % field_name) else: if isinstance(f.rel, models.ManyToManyRel): e.add(opts, '"unique_together" refers to %s. ManyToManyFields are not supported in unique_together.' % f.name) if f not in opts.local_fields: e.add(opts, '"unique_together" refers to %s. This is not in the same model as the unique_together statement.' % f.name) return len(e.errors)
19,729
Python
.py
289
48.705882
264
0.531335
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,803
color.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/color.py
""" Sets up the terminal color scheme. """ import os import sys from django.utils import termcolors def supports_color(): """ Returns True if the running system's terminal supports color, and False otherwise. """ unsupported_platform = (sys.platform in ('win32', 'Pocket PC')) # isatty is not always implemented, #6223. is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty() if unsupported_platform or not is_a_tty: return False return True def color_style(): """Returns a Style object with the Django color scheme.""" if not supports_color(): style = no_style() else: DJANGO_COLORS = os.environ.get('DJANGO_COLORS', '') color_settings = termcolors.parse_color_setting(DJANGO_COLORS) if color_settings: class dummy: pass style = dummy() # The nocolor palette has all available roles. # Use that pallete as the basis for populating # the palette as defined in the environment. for role in termcolors.PALETTES[termcolors.NOCOLOR_PALETTE]: format = color_settings.get(role,{}) setattr(style, role, termcolors.make_style(**format)) # For backwards compatibility, # set style for ERROR_OUTPUT == ERROR style.ERROR_OUTPUT = style.ERROR else: style = no_style() return style def no_style(): """Returns a Style object that has no colors.""" class dummy: def __getattr__(self, attr): return lambda x: x return dummy()
1,608
Python
.py
45
28.311111
75
0.630295
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,804
base.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/base.py
""" Base classes for writing management commands (named commands which can be executed through ``django-admin.py`` or ``manage.py``). """ import os import sys from optparse import make_option, OptionParser import django from django.core.exceptions import ImproperlyConfigured from django.core.management.color import color_style from django.utils.encoding import smart_str class CommandError(Exception): """ Exception class indicating a problem while executing a management command. If this exception is raised during the execution of a management command, it will be caught and turned into a nicely-printed error message to the appropriate output stream (i.e., stderr); as a result, raising this exception (with a sensible description of the error) is the preferred way to indicate that something has gone wrong in the execution of a command. """ pass def handle_default_options(options): """ Include any default options that all commands should accept here so that ManagementUtility can handle them before searching for user commands. """ if options.settings: os.environ['DJANGO_SETTINGS_MODULE'] = options.settings if options.pythonpath: sys.path.insert(0, options.pythonpath) class BaseCommand(object): """ The base class from which all management commands ultimately derive. Use this class if you want access to all of the mechanisms which parse the command-line arguments and work out what code to call in response; if you don't need to change any of that behavior, consider using one of the subclasses defined in this file. If you are interested in overriding/customizing various aspects of the command-parsing and -execution behavior, the normal flow works as follows: 1. ``django-admin.py`` or ``manage.py`` loads the command class and calls its ``run_from_argv()`` method. 2. The ``run_from_argv()`` method calls ``create_parser()`` to get an ``OptionParser`` for the arguments, parses them, performs any environment changes requested by options like ``pythonpath``, and then calls the ``execute()`` method, passing the parsed arguments. 3. The ``execute()`` method attempts to carry out the command by calling the ``handle()`` method with the parsed arguments; any output produced by ``handle()`` will be printed to standard output and, if the command is intended to produce a block of SQL statements, will be wrapped in ``BEGIN`` and ``COMMIT``. 4. If ``handle()`` raised a ``CommandError``, ``execute()`` will instead print an error message to ``stderr``. Thus, the ``handle()`` method is typically the starting point for subclasses; many built-in commands and command types either place all of their logic in ``handle()``, or perform some additional parsing work in ``handle()`` and then delegate from it to more specialized methods as needed. Several attributes affect behavior at various steps along the way: ``args`` A string listing the arguments accepted by the command, suitable for use in help messages; e.g., a command which takes a list of application names might set this to '<appname appname ...>'. ``can_import_settings`` A boolean indicating whether the command needs to be able to import Django settings; if ``True``, ``execute()`` will verify that this is possible before proceeding. Default value is ``True``. ``help`` A short description of the command, which will be printed in help messages. ``option_list`` This is the list of ``optparse`` options which will be fed into the command's ``OptionParser`` for parsing arguments. ``output_transaction`` A boolean indicating whether the command outputs SQL statements; if ``True``, the output will automatically be wrapped with ``BEGIN;`` and ``COMMIT;``. Default value is ``False``. ``requires_model_validation`` A boolean; if ``True``, validation of installed models will be performed prior to executing the command. Default value is ``True``. To validate an individual application's models rather than all applications' models, call ``self.validate(app)`` from ``handle()``, where ``app`` is the application's Python module. """ # Metadata about this command. option_list = ( make_option('-v', '--verbosity', action='store', dest='verbosity', default='1', type='choice', choices=['0', '1', '2', '3'], help='Verbosity level; 0=minimal output, 1=normal output, 2=all output'), make_option('--settings', help='The Python path to a settings module, e.g. "myproject.settings.main". If this isn\'t provided, the DJANGO_SETTINGS_MODULE environment variable will be used.'), make_option('--pythonpath', help='A directory to add to the Python path, e.g. "/home/djangoprojects/myproject".'), make_option('--traceback', action='store_true', help='Print traceback on exception'), ) help = '' args = '' # Configuration shortcuts that alter various logic. can_import_settings = True requires_model_validation = True output_transaction = False # Whether to wrap the output in a "BEGIN; COMMIT;" def __init__(self): self.style = color_style() def get_version(self): """ Return the Django version, which should be correct for all built-in Django commands. User-supplied commands should override this method. """ return django.get_version() def usage(self, subcommand): """ Return a brief description of how to use this command, by default from the attribute ``self.help``. """ usage = '%%prog %s [options] %s' % (subcommand, self.args) if self.help: return '%s\n\n%s' % (usage, self.help) else: return usage def create_parser(self, prog_name, subcommand): """ Create and return the ``OptionParser`` which will be used to parse the arguments to this command. """ return OptionParser(prog=prog_name, usage=self.usage(subcommand), version=self.get_version(), option_list=self.option_list) def print_help(self, prog_name, subcommand): """ Print the help message for this command, derived from ``self.usage()``. """ parser = self.create_parser(prog_name, subcommand) parser.print_help() def run_from_argv(self, argv): """ Set up any environment changes requested (e.g., Python path and Django settings), then run this command. """ parser = self.create_parser(argv[0], argv[1]) options, args = parser.parse_args(argv[2:]) handle_default_options(options) self.execute(*args, **options.__dict__) def execute(self, *args, **options): """ Try to execute this command, performing model validation if needed (as controlled by the attribute ``self.requires_model_validation``). If the command raises a ``CommandError``, intercept it and print it sensibly to stderr. """ # Switch to English, because django-admin.py creates database content # like permissions, and those shouldn't contain any translations. # But only do this if we can assume we have a working settings file, # because django.utils.translation requires settings. if self.can_import_settings: try: from django.utils import translation translation.activate('en-us') except ImportError, e: # If settings should be available, but aren't, # raise the error and quit. sys.stderr.write(smart_str(self.style.ERROR('Error: %s\n' % e))) sys.exit(1) try: self.stdout = options.get('stdout', sys.stdout) self.stderr = options.get('stderr', sys.stderr) if self.requires_model_validation: self.validate() output = self.handle(*args, **options) if output: if self.output_transaction: # This needs to be imported here, because it relies on # settings. from django.db import connections, DEFAULT_DB_ALIAS connection = connections[options.get('database', DEFAULT_DB_ALIAS)] if connection.ops.start_transaction_sql(): self.stdout.write(self.style.SQL_KEYWORD(connection.ops.start_transaction_sql()) + '\n') self.stdout.write(output) if self.output_transaction: self.stdout.write('\n' + self.style.SQL_KEYWORD("COMMIT;") + '\n') except CommandError, e: self.stderr.write(smart_str(self.style.ERROR('Error: %s\n' % e))) sys.exit(1) def validate(self, app=None, display_num_errors=False): """ Validates the given app, raising CommandError for any errors. If app is None, then this will validate all installed apps. """ from django.core.management.validation import get_validation_errors try: from cStringIO import StringIO except ImportError: from StringIO import StringIO s = StringIO() num_errors = get_validation_errors(s, app) if num_errors: s.seek(0) error_text = s.read() raise CommandError("One or more models did not validate:\n%s" % error_text) if display_num_errors: self.stdout.write("%s error%s found\n" % (num_errors, num_errors != 1 and 's' or '')) def handle(self, *args, **options): """ The actual logic of the command. Subclasses must implement this method. """ raise NotImplementedError() class AppCommand(BaseCommand): """ A management command which takes one or more installed application names as arguments, and does something with each of them. Rather than implementing ``handle()``, subclasses must implement ``handle_app()``, which will be called once for each application. """ args = '<appname appname ...>' def handle(self, *app_labels, **options): from django.db import models if not app_labels: raise CommandError('Enter at least one appname.') try: app_list = [models.get_app(app_label) for app_label in app_labels] except (ImproperlyConfigured, ImportError), e: raise CommandError("%s. Are you sure your INSTALLED_APPS setting is correct?" % e) output = [] for app in app_list: app_output = self.handle_app(app, **options) if app_output: output.append(app_output) return '\n'.join(output) def handle_app(self, app, **options): """ Perform the command's actions for ``app``, which will be the Python module corresponding to an application name given on the command line. """ raise NotImplementedError() class LabelCommand(BaseCommand): """ A management command which takes one or more arbitrary arguments (labels) on the command line, and does something with each of them. Rather than implementing ``handle()``, subclasses must implement ``handle_label()``, which will be called once for each label. If the arguments should be names of installed applications, use ``AppCommand`` instead. """ args = '<label label ...>' label = 'label' def handle(self, *labels, **options): if not labels: raise CommandError('Enter at least one %s.' % self.label) output = [] for label in labels: label_output = self.handle_label(label, **options) if label_output: output.append(label_output) return '\n'.join(output) def handle_label(self, label, **options): """ Perform the command's actions for ``label``, which will be the string as given on the command line. """ raise NotImplementedError() class NoArgsCommand(BaseCommand): """ A command which takes no arguments on the command line. Rather than implementing ``handle()``, subclasses must implement ``handle_noargs()``; ``handle()`` itself is overridden to ensure no arguments are passed to the command. Attempting to pass arguments will raise ``CommandError``. """ args = '' def handle(self, *args, **options): if args: raise CommandError("Command doesn't accept any arguments") return self.handle_noargs(**options) def handle_noargs(self, **options): """ Perform this command's actions. """ raise NotImplementedError() def copy_helper(style, app_or_project, name, directory, other_name=''): """ Copies either a Django application layout template or a Django project layout template into the specified directory. """ # style -- A color style object (see django.core.management.color). # app_or_project -- The string 'app' or 'project'. # name -- The name of the application or project. # directory -- The directory to which the layout template should be copied. # other_name -- When copying an application layout, this should be the name # of the project. import re import shutil other = {'project': 'app', 'app': 'project'}[app_or_project] if not re.search(r'^[_a-zA-Z]\w*$', name): # If it's not a valid directory name. # Provide a smart error message, depending on the error. if not re.search(r'^[_a-zA-Z]', name): message = 'make sure the name begins with a letter or underscore' else: message = 'use only numbers, letters and underscores' raise CommandError("%r is not a valid %s name. Please %s." % (name, app_or_project, message)) top_dir = os.path.join(directory, name) try: os.mkdir(top_dir) except OSError, e: raise CommandError(e) # Determine where the app or project templates are. Use # django.__path__[0] because we don't know into which directory # django has been installed. template_dir = os.path.join(django.__path__[0], 'conf', '%s_template' % app_or_project) for d, subdirs, files in os.walk(template_dir): relative_dir = d[len(template_dir)+1:].replace('%s_name' % app_or_project, name) if relative_dir: os.mkdir(os.path.join(top_dir, relative_dir)) for subdir in subdirs[:]: if subdir.startswith('.'): subdirs.remove(subdir) for f in files: if not f.endswith('.py'): # Ignore .pyc, .pyo, .py.class etc, as they cause various # breakages. continue path_old = os.path.join(d, f) path_new = os.path.join(top_dir, relative_dir, f.replace('%s_name' % app_or_project, name)) fp_old = open(path_old, 'r') fp_new = open(path_new, 'w') fp_new.write(fp_old.read().replace('{{ %s_name }}' % app_or_project, name).replace('{{ %s_name }}' % other, other_name)) fp_old.close() fp_new.close() try: shutil.copymode(path_old, path_new) _make_writeable(path_new) except OSError: sys.stderr.write(style.NOTICE("Notice: Couldn't set permission bits on %s. You're probably using an uncommon filesystem setup. No problem.\n" % path_new)) def _make_writeable(filename): """ Make sure that the file is writeable. Useful if our source is read-only. """ import stat if sys.platform.startswith('java'): # On Jython there is no os.access() return if not os.access(filename, os.W_OK): st = os.stat(filename) new_permissions = stat.S_IMODE(st.st_mode) | stat.S_IWUSR os.chmod(filename, new_permissions)
16,452
Python
.py
361
36.872576
177
0.63398
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,805
reset.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/reset.py
from optparse import make_option from django.conf import settings from django.core.management.base import AppCommand, CommandError from django.core.management.color import no_style from django.core.management.sql import sql_reset from django.db import connections, transaction, DEFAULT_DB_ALIAS class Command(AppCommand): option_list = AppCommand.option_list + ( make_option('--noinput', action='store_false', dest='interactive', default=True, help='Tells Django to NOT prompt the user for input of any kind.'), make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to reset. ' 'Defaults to the "default" database.'), ) help = "Executes ``sqlreset`` for the given app(s) in the current database." args = '[appname ...]' output_transaction = True def handle_app(self, app, **options): # This command breaks a lot and should be deprecated import warnings warnings.warn( 'This command has been deprecated. The command ``flush`` can be used to delete everything. You can also use ALTER TABLE or DROP TABLE statements manually.', PendingDeprecationWarning ) using = options.get('database', DEFAULT_DB_ALIAS) connection = connections[using] app_name = app.__name__.split('.')[-2] self.style = no_style() sql_list = sql_reset(app, self.style, connection) if options.get('interactive'): confirm = raw_input(""" You have requested a database reset. This will IRREVERSIBLY DESTROY any data for the "%s" application in the database "%s". Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: """ % (app_name, connection.settings_dict['NAME'])) else: confirm = 'yes' if confirm == 'yes': try: cursor = connection.cursor() for sql in sql_list: cursor.execute(sql) except Exception, e: transaction.rollback_unless_managed() raise CommandError("""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 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: %s""" % (app_name, app_name, e)) transaction.commit_unless_managed() else: print "Reset cancelled."
2,598
Python
.py
54
40.092593
168
0.654438
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,806
runfcgi.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/runfcgi.py
from django.core.management.base import BaseCommand class Command(BaseCommand): help = "Runs this project as a FastCGI application. Requires flup." args = '[various KEY=val options, use `runfcgi help` for help]' def handle(self, *args, **options): from django.conf import settings from django.utils import translation # Activate the current language, because it won't get activated later. try: translation.activate(settings.LANGUAGE_CODE) except AttributeError: pass from django.core.servers.fastcgi import runfastcgi runfastcgi(args) def usage(self, subcommand): from django.core.servers.fastcgi import FASTCGI_HELP return FASTCGI_HELP
760
Python
.py
17
36.470588
78
0.70082
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,807
inspectdb.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/inspectdb.py
import keyword from optparse import make_option from django.core.management.base import NoArgsCommand, CommandError from django.db import connections, DEFAULT_DB_ALIAS class Command(NoArgsCommand): help = "Introspects the database tables in the given database and outputs a Django model module." option_list = NoArgsCommand.option_list + ( make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to ' 'introspect. Defaults to using the "default" database.'), ) requires_model_validation = False db_module = 'django.db' def handle_noargs(self, **options): try: for line in self.handle_inspection(options): self.stdout.write("%s\n" % line) except NotImplementedError: raise CommandError("Database inspection isn't supported for the currently selected database backend.") def handle_inspection(self, options): connection = connections[options.get('database', DEFAULT_DB_ALIAS)] table2model = lambda table_name: table_name.title().replace('_', '').replace(' ', '').replace('-', '') cursor = connection.cursor() yield "# This is an auto-generated Django model module." yield "# You'll have to do the following manually to clean this up:" yield "# * Rearrange models' order" yield "# * Make sure each model has one field with primary_key=True" yield "# Feel free to rename the models, but don't rename db_table values or field names." yield "#" yield "# Also note: You'll have to insert the output of 'django-admin.py sqlcustom [appname]'" yield "# into your database." yield '' yield 'from %s import models' % self.db_module yield '' for table_name in connection.introspection.get_table_list(cursor): yield 'class %s(models.Model):' % table2model(table_name) try: relations = connection.introspection.get_relations(cursor, table_name) except NotImplementedError: relations = {} try: indexes = connection.introspection.get_indexes(cursor, table_name) except NotImplementedError: indexes = {} for i, row in enumerate(connection.introspection.get_table_description(cursor, table_name)): column_name = row[0] att_name = column_name.lower() comment_notes = [] # Holds Field notes, to be displayed in a Python comment. extra_params = {} # Holds Field parameters such as 'db_column'. # If the column name can't be used verbatim as a Python # attribute, set the "db_column" for this Field. if ' ' in att_name or '-' in att_name or keyword.iskeyword(att_name) or column_name != att_name: extra_params['db_column'] = column_name # Modify the field name to make it Python-compatible. if ' ' in att_name: att_name = att_name.replace(' ', '_') comment_notes.append('Field renamed to remove spaces.') if '-' in att_name: att_name = att_name.replace('-', '_') comment_notes.append('Field renamed to remove dashes.') if column_name != att_name: comment_notes.append('Field name made lowercase.') if i in relations: rel_to = relations[i][1] == table_name and "'self'" or table2model(relations[i][1]) field_type = 'ForeignKey(%s' % rel_to if att_name.endswith('_id'): att_name = att_name[:-3] else: extra_params['db_column'] = column_name else: # Calling `get_field_type` to get the field type string and any # additional paramters and notes. field_type, field_params, field_notes = self.get_field_type(connection, table_name, row) extra_params.update(field_params) comment_notes.extend(field_notes) # Add primary_key and unique, if necessary. if column_name in indexes: if indexes[column_name]['primary_key']: extra_params['primary_key'] = True elif indexes[column_name]['unique']: extra_params['unique'] = True field_type += '(' if keyword.iskeyword(att_name): att_name += '_field' comment_notes.append('Field renamed because it was a Python reserved word.') # Don't output 'id = meta.AutoField(primary_key=True)', because # that's assumed if it doesn't exist. if att_name == 'id' and field_type == 'AutoField(' and extra_params == {'primary_key': True}: continue # Add 'null' and 'blank', if the 'null_ok' flag was present in the # table description. if row[6]: # If it's NULL... extra_params['blank'] = True if not field_type in ('TextField(', 'CharField('): extra_params['null'] = True field_desc = '%s = models.%s' % (att_name, field_type) if extra_params: if not field_desc.endswith('('): field_desc += ', ' field_desc += ', '.join(['%s=%r' % (k, v) for k, v in extra_params.items()]) field_desc += ')' if comment_notes: field_desc += ' # ' + ' '.join(comment_notes) yield ' %s' % field_desc for meta_line in self.get_meta(table_name): yield meta_line def get_field_type(self, connection, table_name, row): """ Given the database connection, the table name, and the cursor row description, this routine will return the given field type name, as well as any additional keyword parameters and notes for the field. """ field_params = {} field_notes = [] try: field_type = connection.introspection.get_field_type(row[1], row) except KeyError: field_type = 'TextField' field_notes.append('This field type is a guess.') # This is a hook for DATA_TYPES_REVERSE to return a tuple of # (field_type, field_params_dict). if type(field_type) is tuple: field_type, new_params = field_type field_params.update(new_params) # Add max_length for all CharFields. if field_type == 'CharField' and row[3]: field_params['max_length'] = row[3] if field_type == 'DecimalField': field_params['max_digits'] = row[4] field_params['decimal_places'] = row[5] return field_type, field_params, field_notes def get_meta(self, table_name): """ Return a sequence comprising the lines of code necessary to construct the inner Meta class for the model corresponding to the given database table name. """ return [' class Meta:', ' db_table = %r' % table_name, '']
7,614
Python
.py
140
39.65
114
0.558007
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,808
compilemessages.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/compilemessages.py
import codecs import os import sys from optparse import make_option from django.core.management.base import BaseCommand, CommandError def has_bom(fn): f = open(fn, 'r') sample = f.read(4) return sample[:3] == '\xef\xbb\xbf' or \ sample.startswith(codecs.BOM_UTF16_LE) or \ sample.startswith(codecs.BOM_UTF16_BE) def compile_messages(stderr, locale=None): basedirs = [os.path.join('conf', 'locale'), 'locale'] if os.environ.get('DJANGO_SETTINGS_MODULE'): from django.conf import settings basedirs.extend(settings.LOCALE_PATHS) # Gather existing directories. basedirs = set(map(os.path.abspath, filter(os.path.isdir, basedirs))) if not basedirs: raise CommandError("This script should be run from the Django SVN tree or your project or app tree, or with the settings module specified.") for basedir in basedirs: if locale: basedir = os.path.join(basedir, locale, 'LC_MESSAGES') for dirpath, dirnames, filenames in os.walk(basedir): for f in filenames: if f.endswith('.po'): stderr.write('processing file %s in %s\n' % (f, dirpath)) fn = os.path.join(dirpath, f) if has_bom(fn): raise CommandError("The %s file has a BOM (Byte Order Mark). Django only supports .po files encoded in UTF-8 and without any BOM." % fn) pf = os.path.splitext(fn)[0] # Store the names of the .mo and .po files in an environment # variable, rather than doing a string replacement into the # command, so that we can take advantage of shell quoting, to # quote any malicious characters/escaping. # See http://cyberelk.net/tim/articles/cmdline/ar01s02.html os.environ['djangocompilemo'] = pf + '.mo' os.environ['djangocompilepo'] = pf + '.po' if sys.platform == 'win32': # Different shell-variable syntax cmd = 'msgfmt --check-format -o "%djangocompilemo%" "%djangocompilepo%"' else: cmd = 'msgfmt --check-format -o "$djangocompilemo" "$djangocompilepo"' os.system(cmd) class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('--locale', '-l', dest='locale', help='The locale to process. Default is to process all.'), ) help = 'Compiles .po files to .mo files for use with builtin gettext support.' requires_model_validation = False can_import_settings = False def handle(self, **options): locale = options.get('locale') compile_messages(self.stderr, locale=locale)
2,824
Python
.py
54
40.907407
160
0.608113
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,809
testserver.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/testserver.py
from django.core.management.base import BaseCommand from optparse import make_option class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('--noinput', action='store_false', dest='interactive', default=True, help='Tells Django to NOT prompt the user for input of any kind.'), make_option('--addrport', action='store', dest='addrport', type='string', default='', help='port number or ipaddr:port to run the server on'), make_option('--ipv6', '-6', action='store_true', dest='use_ipv6', default=False, help='Tells Django to use a IPv6 address.'), ) help = 'Runs a development server with data from the given fixture(s).' args = '[fixture ...]' requires_model_validation = False def handle(self, *fixture_labels, **options): from django.core.management import call_command from django.db import connection verbosity = int(options.get('verbosity', 1)) interactive = options.get('interactive', True) addrport = options.get('addrport') # Create a test database. db_name = connection.creation.create_test_db(verbosity=verbosity, autoclobber=not interactive) # Import the fixture data into the test database. call_command('loaddata', *fixture_labels, **{'verbosity': verbosity}) # Run the development server. Turn off auto-reloading because it causes # a strange error -- it causes this handle() method to be called # multiple times. shutdown_message = '\nServer stopped.\nNote that the test database, %r, has not been deleted. You can explore it on your own.' % db_name call_command('runserver', addrport=addrport, shutdown_message=shutdown_message, use_reloader=False, use_ipv6=options['use_ipv6'])
1,837
Python
.py
30
53.033333
144
0.677599
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,810
test.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/test.py
from django.core.management.base import BaseCommand from optparse import make_option import sys class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('--noinput', action='store_false', dest='interactive', default=True, help='Tells Django to NOT prompt the user for input of any kind.'), make_option('--failfast', action='store_true', dest='failfast', default=False, help='Tells Django to stop running the test suite after first failed test.') ) help = 'Runs the test suite for the specified applications, or the entire site if no apps are specified.' args = '[appname ...]' requires_model_validation = False def handle(self, *test_labels, **options): from django.conf import settings from django.test.utils import get_runner verbosity = int(options.get('verbosity', 1)) interactive = options.get('interactive', True) failfast = options.get('failfast', False) TestRunner = get_runner(settings) if hasattr(TestRunner, 'func_name'): # Pre 1.2 test runners were just functions, # and did not support the 'failfast' option. import warnings warnings.warn( 'Function-based test runners are deprecated. Test runners should be classes with a run_tests() method.', DeprecationWarning ) failures = TestRunner(test_labels, verbosity=verbosity, interactive=interactive) else: test_runner = TestRunner(verbosity=verbosity, interactive=interactive, failfast=failfast) failures = test_runner.run_tests(test_labels) if failures: sys.exit(bool(failures))
1,747
Python
.py
34
42.088235
120
0.663738
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,811
makemessages.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/makemessages.py
import fnmatch import glob import os import re import sys from itertools import dropwhile from optparse import make_option from subprocess import PIPE, Popen from django.core.management.base import CommandError, NoArgsCommand from django.utils.text import get_text_list pythonize_re = re.compile(r'(?:^|\n)\s*//') plural_forms_re = re.compile(r'^(?P<value>"Plural-Forms.+?\\n")\s*$', re.MULTILINE | re.DOTALL) def handle_extensions(extensions=('html',)): """ organizes multiple extensions that are separated with commas or passed by using --extension/-e multiple times. for example: running 'django-admin makemessages -e js,txt -e xhtml -a' would result in a extension list: ['.js', '.txt', '.xhtml'] >>> handle_extensions(['.html', 'html,js,py,py,py,.py', 'py,.py']) ['.html', '.js'] >>> handle_extensions(['.html, txt,.tpl']) ['.html', '.tpl', '.txt'] """ ext_list = [] for ext in extensions: ext_list.extend(ext.replace(' ','').split(',')) for i, ext in enumerate(ext_list): if not ext.startswith('.'): ext_list[i] = '.%s' % ext_list[i] # we don't want *.py files here because of the way non-*.py files # are handled in make_messages() (they are copied to file.ext.py files to # trick xgettext to parse them as Python files) return set([x for x in ext_list if x != '.py']) def _popen(cmd): """ Friendly wrapper around Popen for Windows """ p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE, close_fds=os.name != 'nt', universal_newlines=True) return p.communicate() def walk(root, topdown=True, onerror=None, followlinks=False): """ A version of os.walk that can follow symlinks for Python < 2.6 """ for dirpath, dirnames, filenames in os.walk(root, topdown, onerror): yield (dirpath, dirnames, filenames) if followlinks: for d in dirnames: p = os.path.join(dirpath, d) if os.path.islink(p): for link_dirpath, link_dirnames, link_filenames in walk(p): yield (link_dirpath, link_dirnames, link_filenames) def is_ignored(path, ignore_patterns): """ Helper function to check if the given path should be ignored or not. """ for pattern in ignore_patterns: if fnmatch.fnmatchcase(path, pattern): return True return False def find_files(root, ignore_patterns, verbosity, symlinks=False): """ Helper function to get all files in the given root. """ all_files = [] for (dirpath, dirnames, filenames) in walk(".", followlinks=symlinks): for f in filenames: norm_filepath = os.path.normpath(os.path.join(dirpath, f)) if is_ignored(norm_filepath, ignore_patterns): if verbosity > 1: sys.stdout.write('ignoring file %s in %s\n' % (f, dirpath)) else: all_files.extend([(dirpath, f)]) all_files.sort() return all_files def copy_plural_forms(msgs, locale, domain, verbosity): """ Copies plural forms header contents from a Django catalog of locale to the msgs string, inserting it at the right place. msgs should be the contents of a newly created .po file. """ import django django_dir = os.path.normpath(os.path.join(os.path.dirname(django.__file__))) if domain == 'djangojs': domains = ('djangojs', 'django') else: domains = ('django',) for domain in domains: django_po = os.path.join(django_dir, 'conf', 'locale', locale, 'LC_MESSAGES', '%s.po' % domain) if os.path.exists(django_po): m = plural_forms_re.search(open(django_po, 'rU').read()) if m: if verbosity > 1: sys.stderr.write("copying plural forms: %s\n" % m.group('value')) lines = [] seen = False for line in msgs.split('\n'): if not line and not seen: line = '%s\n' % m.group('value') seen = True lines.append(line) msgs = '\n'.join(lines) break return msgs def make_messages(locale=None, domain='django', verbosity='1', all=False, extensions=None, symlinks=False, ignore_patterns=[], no_wrap=False, no_obsolete=False): """ Uses the locale directory from the Django SVN tree or an application/ project to process all """ # Need to ensure that the i18n framework is enabled from django.conf import settings if settings.configured: settings.USE_I18N = True else: settings.configure(USE_I18N = True) from django.utils.translation import templatize invoked_for_django = False if os.path.isdir(os.path.join('conf', 'locale')): localedir = os.path.abspath(os.path.join('conf', 'locale')) invoked_for_django = True # Ignoring all contrib apps ignore_patterns += ['contrib/*'] elif os.path.isdir('locale'): localedir = os.path.abspath('locale') else: raise CommandError("This script should be run from the Django SVN tree or your project or app tree. If you did indeed run it from the SVN checkout or your project or application, maybe you are just missing the conf/locale (in the django tree) or locale (for project and application) directory? It is not created automatically, you have to create it by hand if you want to enable i18n for your project or application.") if domain not in ('django', 'djangojs'): raise CommandError("currently makemessages only supports domains 'django' and 'djangojs'") if (locale is None and not all) or domain is None: message = "Type '%s help %s' for usage information." % (os.path.basename(sys.argv[0]), sys.argv[1]) raise CommandError(message) # We require gettext version 0.15 or newer. output = _popen('xgettext --version')[0] match = re.search(r'(?P<major>\d+)\.(?P<minor>\d+)', output) if match: xversion = (int(match.group('major')), int(match.group('minor'))) if xversion < (0, 15): raise CommandError("Django internationalization requires GNU gettext 0.15 or newer. You are using version %s, please upgrade your gettext toolset." % match.group()) languages = [] if locale is not None: languages.append(locale) elif all: locale_dirs = filter(os.path.isdir, glob.glob('%s/*' % localedir)) languages = [os.path.basename(l) for l in locale_dirs] wrap = no_wrap and '--no-wrap' or '' for locale in languages: if verbosity > 0: print "processing language", locale basedir = os.path.join(localedir, locale, 'LC_MESSAGES') if not os.path.isdir(basedir): os.makedirs(basedir) pofile = os.path.join(basedir, '%s.po' % domain) potfile = os.path.join(basedir, '%s.pot' % domain) if os.path.exists(potfile): os.unlink(potfile) for dirpath, file in find_files(".", ignore_patterns, verbosity, symlinks=symlinks): file_base, file_ext = os.path.splitext(file) if domain == 'djangojs' and file_ext in extensions: if verbosity > 1: sys.stdout.write('processing file %s in %s\n' % (file, dirpath)) src = open(os.path.join(dirpath, file), "rU").read() src = pythonize_re.sub('\n#', src) thefile = '%s.py' % file f = open(os.path.join(dirpath, thefile), "w") try: f.write(src) finally: f.close() cmd = ( 'xgettext -d %s -L Perl %s --keyword=gettext_noop ' '--keyword=gettext_lazy --keyword=ngettext_lazy:1,2 ' '--keyword=pgettext:1c,2 --keyword=npgettext:1c,2,3 ' '--from-code UTF-8 --add-comments=Translators -o - "%s"' % ( domain, wrap, os.path.join(dirpath, thefile) ) ) msgs, errors = _popen(cmd) if errors: os.unlink(os.path.join(dirpath, thefile)) if os.path.exists(potfile): os.unlink(potfile) raise CommandError( "errors happened while running xgettext on %s\n%s" % (file, errors)) if msgs: old = '#: ' + os.path.join(dirpath, thefile)[2:] new = '#: ' + os.path.join(dirpath, file)[2:] msgs = msgs.replace(old, new) if os.path.exists(potfile): # Strip the header msgs = '\n'.join(dropwhile(len, msgs.split('\n'))) else: msgs = msgs.replace('charset=CHARSET', 'charset=UTF-8') f = open(potfile, 'ab') try: f.write(msgs) finally: f.close() os.unlink(os.path.join(dirpath, thefile)) elif domain == 'django' and (file_ext == '.py' or file_ext in extensions): thefile = file orig_file = os.path.join(dirpath, file) if file_ext in extensions: src = open(orig_file, "rU").read() thefile = '%s.py' % file f = open(os.path.join(dirpath, thefile), "w") try: f.write(templatize(src, orig_file[2:])) finally: f.close() if verbosity > 1: sys.stdout.write('processing file %s in %s\n' % (file, dirpath)) cmd = ( 'xgettext -d %s -L Python %s --keyword=gettext_noop ' '--keyword=gettext_lazy --keyword=ngettext_lazy:1,2 ' '--keyword=ugettext_noop --keyword=ugettext_lazy ' '--keyword=ungettext_lazy:1,2 --keyword=pgettext:1c,2 ' '--keyword=npgettext:1c,2,3 --keyword=pgettext_lazy:1c,2 ' '--keyword=npgettext_lazy:1c,2,3 --from-code UTF-8 ' '--add-comments=Translators -o - "%s"' % ( domain, wrap, os.path.join(dirpath, thefile)) ) msgs, errors = _popen(cmd) if errors: if thefile != file: os.unlink(os.path.join(dirpath, thefile)) if os.path.exists(potfile): os.unlink(potfile) raise CommandError( "errors happened while running xgettext on %s\n%s" % (file, errors)) if msgs: if thefile != file: old = '#: ' + os.path.join(dirpath, thefile)[2:] new = '#: ' + orig_file[2:] msgs = msgs.replace(old, new) if os.path.exists(potfile): # Strip the header msgs = '\n'.join(dropwhile(len, msgs.split('\n'))) else: msgs = msgs.replace('charset=CHARSET', 'charset=UTF-8') f = open(potfile, 'ab') try: f.write(msgs) finally: f.close() if thefile != file: os.unlink(os.path.join(dirpath, thefile)) if os.path.exists(potfile): msgs, errors = _popen('msguniq %s --to-code=utf-8 "%s"' % (wrap, potfile)) if errors: os.unlink(potfile) raise CommandError( "errors happened while running msguniq\n%s" % errors) if os.path.exists(pofile): f = open(potfile, 'w') try: f.write(msgs) finally: f.close() msgs, errors = _popen('msgmerge %s -q "%s" "%s"' % (wrap, pofile, potfile)) if errors: os.unlink(potfile) raise CommandError( "errors happened while running msgmerge\n%s" % errors) elif not invoked_for_django: msgs = copy_plural_forms(msgs, locale, domain, verbosity) msgs = msgs.replace( "#. #-#-#-#-# %s.pot (PACKAGE VERSION) #-#-#-#-#\n" % domain, "") f = open(pofile, 'wb') try: f.write(msgs) finally: f.close() os.unlink(potfile) if no_obsolete: msgs, errors = _popen('msgattrib %s -o "%s" --no-obsolete "%s"' % (wrap, pofile, pofile)) if errors: raise CommandError( "errors happened while running msgattrib\n%s" % errors) class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--locale', '-l', default=None, dest='locale', help='Creates or updates the message files for the given locale (e.g. pt_BR).'), make_option('--domain', '-d', default='django', dest='domain', help='The domain of the message files (default: "django").'), make_option('--all', '-a', action='store_true', dest='all', default=False, help='Updates the message files for all existing locales.'), make_option('--extension', '-e', dest='extensions', help='The file extension(s) to examine (default: ".html", separate multiple extensions with commas, or use -e multiple times)', action='append'), make_option('--symlinks', '-s', action='store_true', dest='symlinks', default=False, help='Follows symlinks to directories when examining source code and templates for translation strings.'), make_option('--ignore', '-i', action='append', dest='ignore_patterns', default=[], metavar='PATTERN', help='Ignore files or directories matching this glob-style pattern. Use multiple times to ignore more.'), make_option('--no-default-ignore', action='store_false', dest='use_default_ignore_patterns', default=True, help="Don't ignore the common glob-style patterns 'CVS', '.*' and '*~'."), make_option('--no-wrap', action='store_true', dest='no_wrap', default=False, help="Don't break long message lines into several lines"), make_option('--no-obsolete', action='store_true', dest='no_obsolete', default=False, help="Remove obsolete message strings"), ) help = ( "Runs over the entire source tree of the current directory and " "pulls out all strings marked for translation. It creates (or updates) a message " "file in the conf/locale (in the django tree) or locale (for projects and " "applications) directory.\n\nYou must run this command with one of either the " "--locale or --all options.") requires_model_validation = False can_import_settings = False def handle_noargs(self, *args, **options): locale = options.get('locale') domain = options.get('domain') verbosity = int(options.get('verbosity')) process_all = options.get('all') extensions = options.get('extensions') symlinks = options.get('symlinks') ignore_patterns = options.get('ignore_patterns') if options.get('use_default_ignore_patterns'): ignore_patterns += ['CVS', '.*', '*~'] ignore_patterns = list(set(ignore_patterns)) no_wrap = options.get('no_wrap') no_obsolete = options.get('no_obsolete') if domain == 'djangojs': extensions = handle_extensions(extensions or ['js']) else: extensions = handle_extensions(extensions or ['html']) if verbosity > 1: sys.stdout.write('examining files with the extensions: %s\n' % get_text_list(list(extensions), 'and')) make_messages(locale, domain, verbosity, process_all, extensions, symlinks, ignore_patterns, no_wrap, no_obsolete)
16,507
Python
.py
334
36.667665
426
0.553835
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,812
flush.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/flush.py
from optparse import make_option from django.conf import settings from django.db import connections, router, transaction, models, DEFAULT_DB_ALIAS from django.core.management import call_command from django.core.management.base import NoArgsCommand, CommandError from django.core.management.color import no_style from django.core.management.sql import sql_flush, emit_post_sync_signal from django.utils.importlib import import_module class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--noinput', action='store_false', dest='interactive', default=True, help='Tells Django to NOT prompt the user for input of any kind.'), make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to flush. ' 'Defaults to the "default" database.'), ) help = "Executes ``sqlflush`` on the current database." def handle_noargs(self, **options): db = options.get('database', DEFAULT_DB_ALIAS) connection = connections[db] verbosity = int(options.get('verbosity', 1)) interactive = options.get('interactive') self.style = no_style() # Import the 'management' module within each installed app, to register # dispatcher events. for app_name in settings.INSTALLED_APPS: try: import_module('.management', app_name) except ImportError: pass sql_list = sql_flush(self.style, connection, only_django=True) if interactive: confirm = raw_input("""You have requested a flush of the database. This will IRREVERSIBLY DESTROY all data currently in the %r database, and return each table to the state it was in after syncdb. Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: """ % connection.settings_dict['NAME']) else: confirm = 'yes' if confirm == 'yes': try: cursor = connection.cursor() for sql in sql_list: cursor.execute(sql) except Exception, e: transaction.rollback_unless_managed(using=db) raise CommandError("""Database %s couldn't be flushed. Possible reasons: * The database isn't running or isn't configured correctly. * At least one of the expected database tables doesn't exist. * The SQL was invalid. Hint: Look at the output of 'django-admin.py sqlflush'. That's the SQL this command wasn't able to run. The full error: %s""" % (connection.settings_dict['NAME'], e)) transaction.commit_unless_managed(using=db) # Emit the post sync signal. This allows individual # applications to respond as if the database had been # sync'd from scratch. all_models = [] for app in models.get_apps(): all_models.extend([ m for m in models.get_models(app, include_auto_created=True) if router.allow_syncdb(db, m) ]) emit_post_sync_signal(set(all_models), verbosity, interactive, db) # Reinstall the initial_data fixture. kwargs = options.copy() kwargs['database'] = db call_command('loaddata', 'initial_data', **kwargs) else: print "Flush cancelled."
3,437
Python
.py
69
40.072464
103
0.642325
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,813
sqlreset.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/sqlreset.py
from optparse import make_option from django.core.management.base import AppCommand from django.core.management.sql import sql_reset from django.db import connections, DEFAULT_DB_ALIAS class Command(AppCommand): help = "Prints the DROP TABLE SQL, then the CREATE TABLE SQL, for the given app name(s)." option_list = AppCommand.option_list + ( make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to print the ' 'SQL for. Defaults to the "default" database.'), ) output_transaction = True def handle_app(self, app, **options): return u'\n'.join(sql_reset(app, self.style, connections[options.get('database', DEFAULT_DB_ALIAS)])).encode('utf-8')
774
Python
.py
14
49.285714
125
0.706897
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,814
sqlclear.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/sqlclear.py
from optparse import make_option from django.core.management.base import AppCommand from django.core.management.sql import sql_delete from django.db import connections, DEFAULT_DB_ALIAS class Command(AppCommand): help = "Prints the DROP TABLE SQL statements for the given app name(s)." option_list = AppCommand.option_list + ( make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to print the ' 'SQL for. Defaults to the "default" database.'), ) output_transaction = True def handle_app(self, app, **options): return u'\n'.join(sql_delete(app, self.style, connections[options.get('database', DEFAULT_DB_ALIAS)])).encode('utf-8')
758
Python
.py
14
48.214286
126
0.709066
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,815
loaddata.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/loaddata.py
import sys import os import gzip import zipfile from optparse import make_option from django.conf import settings from django.core import serializers from django.core.management.base import BaseCommand from django.core.management.color import no_style from django.db import connections, router, transaction, DEFAULT_DB_ALIAS from django.db.models import get_apps from django.utils.itercompat import product try: import bz2 has_bz2 = True except ImportError: has_bz2 = False class Command(BaseCommand): help = 'Installs the named fixture(s) in the database.' args = "fixture [fixture ...]" option_list = BaseCommand.option_list + ( make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a specific database to load ' 'fixtures into. Defaults to the "default" database.'), ) def handle(self, *fixture_labels, **options): using = options.get('database', DEFAULT_DB_ALIAS) connection = connections[using] self.style = no_style() verbosity = int(options.get('verbosity', 1)) show_traceback = options.get('traceback', False) # commit is a stealth option - it isn't really useful as # a command line option, but it can be useful when invoking # loaddata from within another script. # If commit=True, loaddata will use its own transaction; # if commit=False, the data load SQL will become part of # the transaction in place when loaddata was invoked. commit = options.get('commit', True) # Keep a count of the installed objects and fixtures fixture_count = 0 loaded_object_count = 0 fixture_object_count = 0 models = set() humanize = lambda dirname: dirname and "'%s'" % dirname or 'absolute path' # Get a cursor (even though we don't need one yet). This has # the side effect of initializing the test database (if # it isn't already initialized). cursor = connection.cursor() # Start transaction management. All fixtures are installed in a # single transaction to ensure that all references are resolved. if commit: transaction.commit_unless_managed(using=using) transaction.enter_transaction_management(using=using) transaction.managed(True, using=using) class SingleZipReader(zipfile.ZipFile): def __init__(self, *args, **kwargs): zipfile.ZipFile.__init__(self, *args, **kwargs) if settings.DEBUG: assert len(self.namelist()) == 1, "Zip-compressed fixtures must contain only one file." def read(self): return zipfile.ZipFile.read(self, self.namelist()[0]) compression_types = { None: file, 'gz': gzip.GzipFile, 'zip': SingleZipReader } if has_bz2: compression_types['bz2'] = bz2.BZ2File app_module_paths = [] for app in get_apps(): if hasattr(app, '__path__'): # It's a 'models/' subpackage for path in app.__path__: app_module_paths.append(path) else: # It's a models.py module app_module_paths.append(app.__file__) app_fixtures = [os.path.join(os.path.dirname(path), 'fixtures') for path in app_module_paths] for fixture_label in fixture_labels: parts = fixture_label.split('.') if len(parts) > 1 and parts[-1] in compression_types: compression_formats = [parts[-1]] parts = parts[:-1] else: compression_formats = compression_types.keys() if len(parts) == 1: fixture_name = parts[0] formats = serializers.get_public_serializer_formats() else: fixture_name, format = '.'.join(parts[:-1]), parts[-1] if format in serializers.get_public_serializer_formats(): formats = [format] else: formats = [] if formats: if verbosity >= 2: self.stdout.write("Loading '%s' fixtures...\n" % fixture_name) else: self.stderr.write( self.style.ERROR("Problem installing fixture '%s': %s is not a known serialization format.\n" % (fixture_name, format))) if commit: transaction.rollback(using=using) transaction.leave_transaction_management(using=using) return if os.path.isabs(fixture_name): fixture_dirs = [fixture_name] else: fixture_dirs = app_fixtures + list(settings.FIXTURE_DIRS) + [''] for fixture_dir in fixture_dirs: if verbosity >= 2: self.stdout.write("Checking %s for fixtures...\n" % humanize(fixture_dir)) label_found = False for combo in product([using, None], formats, compression_formats): database, format, compression_format = combo file_name = '.'.join( p for p in [ fixture_name, database, format, compression_format ] if p ) if verbosity >= 3: self.stdout.write("Trying %s for %s fixture '%s'...\n" % \ (humanize(fixture_dir), file_name, fixture_name)) full_path = os.path.join(fixture_dir, file_name) open_method = compression_types[compression_format] try: fixture = open_method(full_path, 'r') if label_found: fixture.close() self.stderr.write(self.style.ERROR("Multiple fixtures named '%s' in %s. Aborting.\n" % (fixture_name, humanize(fixture_dir)))) if commit: transaction.rollback(using=using) transaction.leave_transaction_management(using=using) return else: fixture_count += 1 objects_in_fixture = 0 loaded_objects_in_fixture = 0 if verbosity >= 2: self.stdout.write("Installing %s fixture '%s' from %s.\n" % \ (format, fixture_name, humanize(fixture_dir))) try: objects = serializers.deserialize(format, fixture, using=using) for obj in objects: objects_in_fixture += 1 if router.allow_syncdb(using, obj.object.__class__): loaded_objects_in_fixture += 1 models.add(obj.object.__class__) obj.save(using=using) loaded_object_count += loaded_objects_in_fixture fixture_object_count += objects_in_fixture label_found = True except (SystemExit, KeyboardInterrupt): raise except Exception: import traceback fixture.close() if commit: transaction.rollback(using=using) transaction.leave_transaction_management(using=using) if show_traceback: traceback.print_exc() else: self.stderr.write( self.style.ERROR("Problem installing fixture '%s': %s\n" % (full_path, ''.join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))))) return fixture.close() # If the fixture we loaded contains 0 objects, assume that an # error was encountered during fixture loading. if objects_in_fixture == 0: self.stderr.write( self.style.ERROR("No fixture data found for '%s'. (File format may be invalid.)\n" % (fixture_name))) if commit: transaction.rollback(using=using) transaction.leave_transaction_management(using=using) return except Exception, e: if verbosity >= 2: self.stdout.write("No %s fixture '%s' in %s.\n" % \ (format, fixture_name, humanize(fixture_dir))) # If we found even one object in a fixture, we need to reset the # database sequences. if loaded_object_count > 0: sequence_sql = connection.ops.sequence_reset_sql(self.style, models) if sequence_sql: if verbosity >= 2: self.stdout.write("Resetting sequences\n") for line in sequence_sql: cursor.execute(line) if commit: transaction.commit(using=using) transaction.leave_transaction_management(using=using) if fixture_object_count == 0: if verbosity >= 1: self.stdout.write("No fixtures found.\n") else: if verbosity >= 1: if fixture_object_count == loaded_object_count: self.stdout.write("Installed %d object(s) from %d fixture(s)\n" % ( loaded_object_count, fixture_count)) else: self.stdout.write("Installed %d object(s) (of %d) from %d fixture(s)\n" % ( loaded_object_count, fixture_object_count, fixture_count)) # Close the DB connection. This is required as a workaround for an # edge case in MySQL: if the same connection is used to # create tables, load data, and query, the query can return # incorrect results. See Django #7572, MySQL #37735. if commit: connection.close()
11,042
Python
.py
214
33.163551
120
0.50588
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,816
diffsettings.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/diffsettings.py
from django.core.management.base import NoArgsCommand def module_to_dict(module, omittable=lambda k: k.startswith('_')): "Converts a module namespace to a Python dictionary. Used by get_settings_diff." return dict([(k, repr(v)) for k, v in module.__dict__.items() if not omittable(k)]) class Command(NoArgsCommand): help = """Displays differences between the current settings.py and Django's default settings. Settings that don't appear in the defaults are followed by "###".""" requires_model_validation = False def handle_noargs(self, **options): # Inspired by Postfix's "postconf -n". from django.conf import settings, global_settings # Because settings are imported lazily, we need to explicitly load them. settings._setup() user_settings = module_to_dict(settings._wrapped) default_settings = module_to_dict(global_settings) output = [] keys = user_settings.keys() keys.sort() for key in keys: if key not in default_settings: output.append("%s = %s ###" % (key, user_settings[key])) elif user_settings[key] != default_settings[key]: output.append("%s = %s" % (key, user_settings[key])) return '\n'.join(output)
1,296
Python
.py
25
43.68
87
0.651108
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,817
startapp.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/startapp.py
import os from django.core.management.base import copy_helper, CommandError, LabelCommand from django.utils.importlib import import_module class Command(LabelCommand): help = "Creates a Django app directory structure for the given app name in the current directory." args = "[appname]" label = 'application name' requires_model_validation = False # Can't import settings during this command, because they haven't # necessarily been created. can_import_settings = False def handle_label(self, app_name, directory=None, **options): if directory is None: directory = os.getcwd() # Determine the project_name by using the basename of directory, # which should be the full path of the project directory (or the # current directory if no directory was passed). project_name = os.path.basename(directory) if app_name == project_name: raise CommandError("You cannot create an app with the same name" " (%r) as your project." % app_name) # Check that the app_name cannot be imported. try: import_module(app_name) except ImportError: pass else: raise CommandError("%r conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name." % app_name) copy_helper(self.style, 'app', app_name, directory, project_name) class ProjectCommand(Command): help = ("Creates a Django app directory structure for the given app name" " in this project's directory.") def __init__(self, project_directory): super(ProjectCommand, self).__init__() self.project_directory = project_directory def handle_label(self, app_name, **options): super(ProjectCommand, self).handle_label(app_name, self.project_directory, **options)
1,909
Python
.py
37
43.324324
160
0.678303
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,818
sql.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/sql.py
from optparse import make_option from django.core.management.base import AppCommand from django.core.management.sql import sql_create from django.db import connections, DEFAULT_DB_ALIAS class Command(AppCommand): help = "Prints the CREATE TABLE SQL statements for the given app name(s)." option_list = AppCommand.option_list + ( make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to print the ' 'SQL for. Defaults to the "default" database.'), ) output_transaction = True def handle_app(self, app, **options): return u'\n'.join(sql_create(app, self.style, connections[options.get('database', DEFAULT_DB_ALIAS)])).encode('utf-8')
760
Python
.py
14
48.357143
126
0.709852
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,819
sqlindexes.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/sqlindexes.py
from optparse import make_option from django.core.management.base import AppCommand from django.core.management.sql import sql_indexes from django.db import connections, DEFAULT_DB_ALIAS class Command(AppCommand): help = "Prints the CREATE INDEX SQL statements for the given model module name(s)." option_list = AppCommand.option_list + ( make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to print the ' 'SQL for. Defaults to the "default" database.'), ) output_transaction = True def handle_app(self, app, **options): return u'\n'.join(sql_indexes(app, self.style, connections[options.get('database', DEFAULT_DB_ALIAS)])).encode('utf-8')
772
Python
.py
14
49.142857
127
0.712766
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,820
runserver.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/runserver.py
from optparse import make_option import os import re import sys import socket from django.core.management.base import BaseCommand, CommandError from django.core.handlers.wsgi import WSGIHandler from django.core.servers.basehttp import AdminMediaHandler, run, WSGIServerException from django.utils import autoreload naiveip_re = re.compile(r"""^(?: (?P<addr> (?P<ipv4>\d{1,3}(?:\.\d{1,3}){3}) | # IPv4 address (?P<ipv6>\[[a-fA-F0-9:]+\]) | # IPv6 address (?P<fqdn>[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*) # FQDN ):)?(?P<port>\d+)$""", re.X) DEFAULT_PORT = "8000" class BaseRunserverCommand(BaseCommand): option_list = BaseCommand.option_list + ( make_option('--ipv6', '-6', action='store_true', dest='use_ipv6', default=False, help='Tells Django to use a IPv6 address.'), make_option('--noreload', action='store_false', dest='use_reloader', default=True, help='Tells Django to NOT use the auto-reloader.'), ) help = "Starts a lightweight Web server for development." args = '[optional port number, or ipaddr:port]' # Validation is called explicitly each time the server is reloaded. requires_model_validation = False def get_handler(self, *args, **options): """ Returns the default WSGI handler for the runner. """ return WSGIHandler() def handle(self, addrport='', *args, **options): self.use_ipv6 = options.get('use_ipv6') if self.use_ipv6 and not socket.has_ipv6: raise CommandError('Your Python does not support IPv6.') if args: raise CommandError('Usage is runserver %s' % self.args) self._raw_ipv6 = False if not addrport: self.addr = '' self.port = DEFAULT_PORT else: m = re.match(naiveip_re, addrport) if m is None: raise CommandError('"%s" is not a valid port number ' 'or address:port pair.' % addrport) self.addr, _ipv4, _ipv6, _fqdn, self.port = m.groups() if not self.port.isdigit(): raise CommandError("%r is not a valid port number." % self.port) if self.addr: if _ipv6: self.addr = self.addr[1:-1] self.use_ipv6 = True self._raw_ipv6 = True elif self.use_ipv6 and not _fqdn: raise CommandError('"%s" is not a valid IPv6 address.' % self.addr) if not self.addr: self.addr = self.use_ipv6 and '::1' or '127.0.0.1' self._raw_ipv6 = bool(self.use_ipv6) self.run(*args, **options) def run(self, *args, **options): """ Runs the server, using the autoreloader if needed """ use_reloader = options.get('use_reloader', True) if use_reloader: autoreload.main(self.inner_run, args, options) else: self.inner_run(*args, **options) def inner_run(self, *args, **options): from django.conf import settings from django.utils import translation shutdown_message = options.get('shutdown_message', '') quit_command = (sys.platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C' self.stdout.write("Validating models...\n\n") self.validate(display_num_errors=True) self.stdout.write(( "Django version %(version)s, using settings %(settings)r\n" "Development server is running at http://%(addr)s:%(port)s/\n" "Quit the server with %(quit_command)s.\n" ) % { "version": self.get_version(), "settings": settings.SETTINGS_MODULE, "addr": self._raw_ipv6 and '[%s]' % self.addr or self.addr, "port": self.port, "quit_command": quit_command, }) # django.core.management.base forces the locale to en-us. We should # set it up correctly for the first request (particularly important # in the "--noreload" case). translation.activate(settings.LANGUAGE_CODE) try: handler = self.get_handler(*args, **options) run(self.addr, int(self.port), handler, ipv6=self.use_ipv6) except WSGIServerException, e: # Use helpful error messages instead of ugly tracebacks. ERRORS = { 13: "You don't have permission to access that port.", 98: "That port is already in use.", 99: "That IP address can't be assigned-to.", } try: error_text = ERRORS[e.args[0].args[0]] except (AttributeError, KeyError): error_text = str(e) sys.stderr.write(self.style.ERROR("Error: %s" % error_text) + '\n') # Need to use an OS exit because sys.exit doesn't work in a thread os._exit(1) except KeyboardInterrupt: if shutdown_message: self.stdout.write("%s\n" % shutdown_message) sys.exit(0) class Command(BaseRunserverCommand): option_list = BaseRunserverCommand.option_list + ( make_option('--adminmedia', dest='admin_media_path', default='', help='Specifies the directory from which to serve admin media.'), ) def get_handler(self, *args, **options): """ Serves admin media like old-school (deprecation pending). """ handler = super(Command, self).get_handler(*args, **options) return AdminMediaHandler(handler, options.get('admin_media_path', ''))
5,632
Python
.py
124
35.379032
90
0.587368
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,821
dumpdata.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/dumpdata.py
from django.core.exceptions import ImproperlyConfigured from django.core.management.base import BaseCommand, CommandError from django.core import serializers from django.db import connections, router, DEFAULT_DB_ALIAS from django.utils.datastructures import SortedDict from optparse import make_option class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('--format', default='json', dest='format', help='Specifies the output serialization format for fixtures.'), make_option('--indent', default=None, dest='indent', type='int', help='Specifies the indent level to use when pretty-printing output'), make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a specific database to load ' 'fixtures into. Defaults to the "default" database.'), make_option('-e', '--exclude', dest='exclude',action='append', default=[], help='An appname or appname.ModelName to exclude (use multiple --exclude to exclude multiple apps/models).'), make_option('-n', '--natural', action='store_true', dest='use_natural_keys', default=False, help='Use natural keys if they are available.'), make_option('-a', '--all', action='store_true', dest='use_base_manager', default=False, help="Use Django's base manager to dump all models stored in the database, including those that would otherwise be filtered or modified by a custom manager."), ) help = ("Output the contents of the database as a fixture of the given " "format (using each model's default manager unless --all is " "specified).") args = '[appname appname.ModelName ...]' def handle(self, *app_labels, **options): from django.db.models import get_app, get_apps, get_models, get_model format = options.get('format','json') indent = options.get('indent',None) using = options.get('database', DEFAULT_DB_ALIAS) connection = connections[using] excludes = options.get('exclude',[]) show_traceback = options.get('traceback', False) use_natural_keys = options.get('use_natural_keys', False) use_base_manager = options.get('use_base_manager', False) excluded_apps = set() excluded_models = set() for exclude in excludes: if '.' in exclude: app_label, model_name = exclude.split('.', 1) model_obj = get_model(app_label, model_name) if not model_obj: raise CommandError('Unknown model in excludes: %s' % exclude) excluded_models.add(model_obj) else: try: app_obj = get_app(exclude) excluded_apps.add(app_obj) except ImproperlyConfigured: raise CommandError('Unknown app in excludes: %s' % exclude) if len(app_labels) == 0: app_list = SortedDict((app, None) for app in get_apps() if app not in excluded_apps) else: app_list = SortedDict() for label in app_labels: try: app_label, model_label = label.split('.') try: app = get_app(app_label) except ImproperlyConfigured: raise CommandError("Unknown application: %s" % app_label) if app in excluded_apps: continue model = get_model(app_label, model_label) if model is None: raise CommandError("Unknown model: %s.%s" % (app_label, model_label)) if app in app_list.keys(): if app_list[app] and model not in app_list[app]: app_list[app].append(model) else: app_list[app] = [model] except ValueError: # This is just an app - no model qualifier app_label = label try: app = get_app(app_label) except ImproperlyConfigured: raise CommandError("Unknown application: %s" % app_label) if app in excluded_apps: continue app_list[app] = None # Check that the serialization format exists; this is a shortcut to # avoid collating all the objects and _then_ failing. if format not in serializers.get_public_serializer_formats(): raise CommandError("Unknown serialization format: %s" % format) try: serializers.get_serializer(format) except KeyError: raise CommandError("Unknown serialization format: %s" % format) # Now collate the objects to be serialized. objects = [] for model in sort_dependencies(app_list.items()): if model in excluded_models: continue if not model._meta.proxy and router.allow_syncdb(using, model): if use_base_manager: objects.extend(model._base_manager.using(using).all()) else: objects.extend(model._default_manager.using(using).all()) try: return serializers.serialize(format, objects, indent=indent, use_natural_keys=use_natural_keys) except Exception, e: if show_traceback: raise raise CommandError("Unable to serialize database: %s" % e) def sort_dependencies(app_list): """Sort a list of app,modellist pairs into a single list of models. The single list of models is sorted so that any model with a natural key is serialized before a normal model, and any model with a natural key dependency has it's dependencies serialized first. """ from django.db.models import get_model, get_models # Process the list of models, and get the list of dependencies model_dependencies = [] models = set() for app, model_list in app_list: if model_list is None: model_list = get_models(app) for model in model_list: models.add(model) # Add any explicitly defined dependencies if hasattr(model, 'natural_key'): deps = getattr(model.natural_key, 'dependencies', []) if deps: deps = [get_model(*d.split('.')) for d in deps] else: deps = [] # Now add a dependency for any FK or M2M relation with # a model that defines a natural key for field in model._meta.fields: if hasattr(field.rel, 'to'): rel_model = field.rel.to if hasattr(rel_model, 'natural_key'): deps.append(rel_model) for field in model._meta.many_to_many: rel_model = field.rel.to if hasattr(rel_model, 'natural_key'): deps.append(rel_model) model_dependencies.append((model, deps)) model_dependencies.reverse() # Now sort the models to ensure that dependencies are met. This # is done by repeatedly iterating over the input list of models. # If all the dependencies of a given model are in the final list, # that model is promoted to the end of the final list. This process # continues until the input list is empty, or we do a full iteration # over the input models without promoting a model to the final list. # If we do a full iteration without a promotion, that means there are # circular dependencies in the list. model_list = [] while model_dependencies: skipped = [] changed = False while model_dependencies: model, deps = model_dependencies.pop() # If all of the models in the dependency list are either already # on the final model list, or not on the original serialization list, # then we've found another model with all it's dependencies satisfied. found = True for candidate in ((d not in models or d in model_list) for d in deps): if not candidate: found = False if found: model_list.append(model) changed = True else: skipped.append((model, deps)) if not changed: raise CommandError("Can't resolve dependencies for %s in serialized app list." % ', '.join('%s.%s' % (model._meta.app_label, model._meta.object_name) for model, deps in sorted(skipped, key=lambda obj: obj[0].__name__)) ) model_dependencies = skipped return model_list
8,960
Python
.py
175
38.165714
171
0.58686
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,822
sqlsequencereset.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/sqlsequencereset.py
from optparse import make_option from django.core.management.base import AppCommand from django.db import connections, models, DEFAULT_DB_ALIAS class Command(AppCommand): help = 'Prints the SQL statements for resetting sequences for the given app name(s).' option_list = AppCommand.option_list + ( make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to print the ' 'SQL for. Defaults to the "default" database.'), ) output_transaction = True def handle_app(self, app, **options): connection = connections[options.get('database', DEFAULT_DB_ALIAS)] return u'\n'.join(connection.ops.sequence_reset_sql(self.style, models.get_models(app, include_auto_created=True))).encode('utf-8')
819
Python
.py
14
51.928571
139
0.709637
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,823
sqlall.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/sqlall.py
from optparse import make_option from django.core.management.base import AppCommand from django.core.management.sql import sql_all from django.db import connections, DEFAULT_DB_ALIAS class Command(AppCommand): help = "Prints the CREATE TABLE, custom SQL and CREATE INDEX SQL statements for the given model module name(s)." option_list = AppCommand.option_list + ( make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to print the ' 'SQL for. Defaults to the "default" database.'), ) output_transaction = True def handle_app(self, app, **options): return u'\n'.join(sql_all(app, self.style, connections[options.get('database', DEFAULT_DB_ALIAS)])).encode('utf-8')
792
Python
.py
14
50.642857
123
0.712807
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,824
cleanup.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/cleanup.py
import datetime from django.core.management.base import NoArgsCommand class Command(NoArgsCommand): help = "Can be run as a cronjob or directly to clean out old data from the database (only expired sessions at the moment)." def handle_noargs(self, **options): from django.db import transaction from django.contrib.sessions.models import Session Session.objects.filter(expire_date__lt=datetime.datetime.now()).delete() transaction.commit_unless_managed()
496
Python
.py
9
49.444444
127
0.754639
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,825
shell.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/shell.py
import os from django.core.management.base import NoArgsCommand from optparse import make_option class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--plain', action='store_true', dest='plain', help='Tells Django to use plain Python, not IPython.'), ) help = "Runs a Python interactive interpreter. Tries to use IPython, if it's available." shells = ['ipython', 'bpython'] requires_model_validation = False def ipython(self): try: from IPython.frontend.terminal.embed import TerminalInteractiveShell shell = TerminalInteractiveShell() shell.mainloop() except ImportError: # IPython < 0.11 # Explicitly pass an empty list as arguments, because otherwise # IPython would use sys.argv from this script. try: from IPython.Shell import IPShell shell = IPShell(argv=[]) shell.mainloop() except ImportError: # IPython not found at all, raise ImportError raise def bpython(self): import bpython bpython.embed() def run_shell(self): for shell in self.shells: try: return getattr(self, shell)() except ImportError: pass raise ImportError def handle_noargs(self, **options): # XXX: (Temporary) workaround for ticket #1796: force early loading of all # models from installed apps. from django.db.models.loading import get_models loaded_models = get_models() use_plain = options.get('plain', False) try: if use_plain: # Don't bother loading IPython, because the user wants plain Python. raise ImportError self.run_shell() except ImportError: import code # Set up a dictionary to serve as the environment for the shell, so # that tab completion works on objects that are imported at runtime. # See ticket 5082. imported_objects = {} try: # Try activating rlcompleter, because it's handy. import readline except ImportError: pass else: # We don't have to wrap the following import in a 'try', because # we already know 'readline' was imported successfully. import rlcompleter readline.set_completer(rlcompleter.Completer(imported_objects).complete) readline.parse_and_bind("tab:complete") # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system # conventions and get $PYTHONSTARTUP first then import user. if not use_plain: pythonrc = os.environ.get("PYTHONSTARTUP") if pythonrc and os.path.isfile(pythonrc): try: execfile(pythonrc) except NameError: pass # This will import .pythonrc.py as a side-effect import user code.interact(local=imported_objects)
3,263
Python
.py
76
30.486842
92
0.586662
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,826
validate.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/validate.py
from django.core.management.base import NoArgsCommand class Command(NoArgsCommand): help = "Validates all installed models." requires_model_validation = False def handle_noargs(self, **options): self.validate(display_num_errors=True)
257
Python
.py
6
38
53
0.762097
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,827
syncdb.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/syncdb.py
from optparse import make_option import sys from django.conf import settings from django.core.management.base import NoArgsCommand from django.core.management.color import no_style from django.core.management.sql import custom_sql_for_model, emit_post_sync_signal from django.db import connections, router, transaction, models, DEFAULT_DB_ALIAS from django.utils.datastructures import SortedDict from django.utils.importlib import import_module class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--noinput', action='store_false', dest='interactive', default=True, help='Tells Django to NOT prompt the user for input of any kind.'), make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to synchronize. ' 'Defaults to the "default" database.'), ) help = "Create the database tables for all apps in INSTALLED_APPS whose tables haven't already been created." def handle_noargs(self, **options): verbosity = int(options.get('verbosity', 1)) interactive = options.get('interactive') show_traceback = options.get('traceback', False) # Stealth option -- 'load_initial_data' is used by the testing setup # process to disable initial fixture loading. load_initial_data = options.get('load_initial_data', True) self.style = no_style() # Import the 'management' module within each installed app, to register # dispatcher events. for app_name in settings.INSTALLED_APPS: try: import_module('.management', app_name) except ImportError, exc: # This is slightly hackish. We want to ignore ImportErrors # if the "management" module itself is missing -- but we don't # want to ignore the exception if the management module exists # but raises an ImportError for some reason. The only way we # can do this is to check the text of the exception. Note that # we're a bit broad in how we check the text, because different # Python implementations may not use the same text. # CPython uses the text "No module named management" # PyPy uses "No module named myproject.myapp.management" msg = exc.args[0] if not msg.startswith('No module named') or 'management' not in msg: raise db = options.get('database', DEFAULT_DB_ALIAS) connection = connections[db] cursor = connection.cursor() # Get a list of already installed *models* so that references work right. tables = connection.introspection.table_names() seen_models = connection.introspection.installed_models(tables) created_models = set() pending_references = {} # Build the manifest of apps and models that are to be synchronized all_models = [ (app.__name__.split('.')[-2], [m for m in models.get_models(app, include_auto_created=True) if router.allow_syncdb(db, m)]) for app in models.get_apps() ] def model_installed(model): opts = model._meta converter = connection.introspection.table_name_converter return not ((converter(opts.db_table) in tables) or (opts.auto_created and converter(opts.auto_created._meta.db_table) in tables)) manifest = SortedDict( (app_name, filter(model_installed, model_list)) for app_name, model_list in all_models ) # Create the tables for each model if verbosity >= 1: print "Creating tables ..." for app_name, model_list in manifest.items(): for model in model_list: # Create the model's database table, if it doesn't already exist. if verbosity >= 3: print "Processing %s.%s model" % (app_name, model._meta.object_name) sql, references = connection.creation.sql_create_model(model, self.style, seen_models) seen_models.add(model) created_models.add(model) for refto, refs in references.items(): pending_references.setdefault(refto, []).extend(refs) if refto in seen_models: sql.extend(connection.creation.sql_for_pending_references(refto, self.style, pending_references)) sql.extend(connection.creation.sql_for_pending_references(model, self.style, pending_references)) if verbosity >= 1 and sql: print "Creating table %s" % model._meta.db_table for statement in sql: cursor.execute(statement) tables.append(connection.introspection.table_name_converter(model._meta.db_table)) transaction.commit_unless_managed(using=db) # Send the post_syncdb signal, so individual apps can do whatever they need # to do at this point. emit_post_sync_signal(created_models, verbosity, interactive, db) # The connection may have been closed by a syncdb handler. cursor = connection.cursor() # Install custom SQL for the app (but only if this # is a model we've just created) if verbosity >= 1: print "Installing custom SQL ..." for app_name, model_list in manifest.items(): for model in model_list: if model in created_models: custom_sql = custom_sql_for_model(model, self.style, connection) if custom_sql: if verbosity >= 2: print "Installing custom SQL for %s.%s model" % (app_name, model._meta.object_name) try: for sql in custom_sql: cursor.execute(sql) except Exception, e: sys.stderr.write("Failed to install custom SQL for %s.%s model: %s\n" % \ (app_name, model._meta.object_name, e)) if show_traceback: import traceback traceback.print_exc() transaction.rollback_unless_managed(using=db) else: transaction.commit_unless_managed(using=db) else: if verbosity >= 3: print "No custom SQL for %s.%s model" % (app_name, model._meta.object_name) if verbosity >= 1: print "Installing indexes ..." # Install SQL indicies for all newly created models for app_name, model_list in manifest.items(): for model in model_list: if model in created_models: index_sql = connection.creation.sql_indexes_for_model(model, self.style) if index_sql: if verbosity >= 2: print "Installing index for %s.%s model" % (app_name, model._meta.object_name) try: for sql in index_sql: cursor.execute(sql) except Exception, e: sys.stderr.write("Failed to install index for %s.%s model: %s\n" % \ (app_name, model._meta.object_name, e)) transaction.rollback_unless_managed(using=db) else: transaction.commit_unless_managed(using=db) # Load initial_data fixtures (unless that has been disabled) if load_initial_data: from django.core.management import call_command call_command('loaddata', 'initial_data', verbosity=verbosity, database=db)
8,141
Python
.py
144
41.0625
121
0.579416
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,828
startproject.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/startproject.py
from django.core.management.base import copy_helper, CommandError, LabelCommand from django.utils.importlib import import_module import os import re from random import choice class Command(LabelCommand): help = "Creates a Django project directory structure for the given project name in the current directory." args = "[projectname]" label = 'project name' requires_model_validation = False # Can't import settings during this command, because they haven't # necessarily been created. can_import_settings = False def handle_label(self, project_name, **options): # Determine the project_name a bit naively -- by looking at the name of # the parent directory. directory = os.getcwd() # Check that the project_name cannot be imported. try: import_module(project_name) except ImportError: pass else: raise CommandError("%r conflicts with the name of an existing Python module and cannot be used as a project name. Please try another name." % project_name) copy_helper(self.style, 'project', project_name, directory) # Create a random SECRET_KEY hash, and put it in the main settings. main_settings_file = os.path.join(directory, project_name, 'settings.py') settings_contents = open(main_settings_file, 'r').read() fp = open(main_settings_file, 'w') secret_key = ''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)]) settings_contents = re.sub(r"(?<=SECRET_KEY = ')'", secret_key + "'", settings_contents) fp.write(settings_contents) fp.close()
1,680
Python
.py
33
43.787879
167
0.68312
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,829
sqlflush.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/sqlflush.py
from optparse import make_option from django.core.management.base import NoArgsCommand from django.core.management.sql import sql_flush from django.db import connections, DEFAULT_DB_ALIAS class Command(NoArgsCommand): help = "Returns a list of the SQL statements required to return all tables in the database to the state they were in just after they were installed." option_list = NoArgsCommand.option_list + ( make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to print the ' 'SQL for. Defaults to the "default" database.'), ) output_transaction = True def handle_noargs(self, **options): return u'\n'.join(sql_flush(self.style, connections[options.get('database', DEFAULT_DB_ALIAS)], only_django=True)).encode('utf-8')
853
Python
.py
14
55
153
0.726619
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,830
sqlinitialdata.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/sqlinitialdata.py
from django.core.management.base import AppCommand, CommandError class Command(AppCommand): help = "RENAMED: see 'sqlcustom'" def handle(self, *apps, **options): raise CommandError("This command has been renamed. Use the 'sqlcustom' command instead.")
270
Python
.py
5
49.4
97
0.745247
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,831
sqlcustom.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/sqlcustom.py
from optparse import make_option from django.core.management.base import AppCommand from django.core.management.sql import sql_custom from django.db import connections, DEFAULT_DB_ALIAS class Command(AppCommand): help = "Prints the custom table modifying SQL statements for the given app name(s)." option_list = AppCommand.option_list + ( make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to print the ' 'SQL for. Defaults to the "default" database.'), ) output_transaction = True def handle_app(self, app, **options): return u'\n'.join(sql_custom(app, self.style, connections[options.get('database', DEFAULT_DB_ALIAS)])).encode('utf-8')
770
Python
.py
14
49.071429
126
0.712383
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,832
createcachetable.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/createcachetable.py
from optparse import make_option from django.core.management.base import LabelCommand from django.db import connections, transaction, models, DEFAULT_DB_ALIAS class Command(LabelCommand): help = "Creates the table needed to use the SQL cache backend." args = "<tablename>" label = 'tablename' option_list = LabelCommand.option_list + ( make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database onto ' 'which the cache table will be installed. ' 'Defaults to the "default" database.'), ) requires_model_validation = False def handle_label(self, tablename, **options): alias = options.get('database', DEFAULT_DB_ALIAS) connection = connections[alias] fields = ( # "key" is a reserved word in MySQL, so use "cache_key" instead. models.CharField(name='cache_key', max_length=255, unique=True, primary_key=True), models.TextField(name='value'), models.DateTimeField(name='expires', db_index=True), ) table_output = [] index_output = [] qn = connection.ops.quote_name for f in fields: field_output = [qn(f.name), f.db_type(connection=connection)] field_output.append("%sNULL" % (not f.null and "NOT " or "")) if f.primary_key: field_output.append("PRIMARY KEY") elif f.unique: field_output.append("UNIQUE") if f.db_index: unique = f.unique and "UNIQUE " or "" index_output.append("CREATE %sINDEX %s ON %s (%s);" % \ (unique, qn('%s_%s' % (tablename, f.name)), qn(tablename), qn(f.name))) table_output.append(" ".join(field_output)) full_statement = ["CREATE TABLE %s (" % qn(tablename)] for i, line in enumerate(table_output): full_statement.append(' %s%s' % (line, i < len(table_output)-1 and ',' or '')) full_statement.append(');') curs = connection.cursor() curs.execute("\n".join(full_statement)) for statement in index_output: curs.execute(statement) transaction.commit_unless_managed(using=alias)
2,307
Python
.py
48
37.625
94
0.594499
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,833
dbshell.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/dbshell.py
from optparse import make_option from django.core.management.base import BaseCommand, CommandError from django.db import connections, DEFAULT_DB_ALIAS class Command(BaseCommand): help = ("Runs the command-line client for specified database, or the " "default database if none is provided.") option_list = BaseCommand.option_list + ( make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database onto which to ' 'open a shell. Defaults to the "default" database.'), ) requires_model_validation = False def handle(self, **options): connection = connections[options.get('database', DEFAULT_DB_ALIAS)] try: connection.client.runshell() except OSError: # Note that we're assuming OSError means that the client program # isn't installed. There's a possibility OSError would be raised # for some other reason, in which case this error message would be # inaccurate. Still, this message catches the common case. raise CommandError('You appear not to have the %r program installed or on your path.' % \ connection.client.executable_name)
1,261
Python
.py
23
45.956522
101
0.679643
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,834
__init__.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/cache/__init__.py
""" Caching framework. This package defines set of cache backends that all conform to a simple API. In a nutshell, a cache is a set of values -- which can be any object that may be pickled -- identified by string keys. For the complete API, see the abstract BaseCache class in django.core.cache.backends.base. Client code should not access a cache backend directly; instead it should either use the "cache" variable made available here, or it should use the get_cache() function made available here. get_cache() takes a backend URI (e.g. "memcached://127.0.0.1:11211/") and returns an instance of a backend cache class. See docs/topics/cache.txt for information on the public API. """ from django.conf import settings from django.core import signals from django.core.cache.backends.base import ( InvalidCacheBackendError, CacheKeyWarning, BaseCache) from django.core.exceptions import ImproperlyConfigured from django.utils import importlib try: # The mod_python version is more efficient, so try importing it first. from mod_python.util import parse_qsl except ImportError: try: # Python 2.6 and greater from urlparse import parse_qsl except ImportError: # Python 2.5, 2.4. Works on Python 2.6 but raises # PendingDeprecationWarning from cgi import parse_qsl __all__ = [ 'get_cache', 'cache', 'DEFAULT_CACHE_ALIAS' ] # Name for use in settings file --> name of module in "backends" directory. # Any backend scheme that is not in this dictionary is treated as a Python # import path to a custom backend. BACKENDS = { 'memcached': 'memcached', 'locmem': 'locmem', 'file': 'filebased', 'db': 'db', 'dummy': 'dummy', } DEFAULT_CACHE_ALIAS = 'default' def parse_backend_uri(backend_uri): """ Converts the "backend_uri" into a cache scheme ('db', 'memcached', etc), a host and any extra params that are required for the backend. Returns a (scheme, host, params) tuple. """ if backend_uri.find(':') == -1: raise InvalidCacheBackendError("Backend URI must start with scheme://") scheme, rest = backend_uri.split(':', 1) if not rest.startswith('//'): raise InvalidCacheBackendError("Backend URI must start with scheme://") host = rest[2:] qpos = rest.find('?') if qpos != -1: params = dict(parse_qsl(rest[qpos+1:])) host = rest[2:qpos] else: params = {} if host.endswith('/'): host = host[:-1] return scheme, host, params if not settings.CACHES: legacy_backend = getattr(settings, 'CACHE_BACKEND', None) if legacy_backend: import warnings warnings.warn( "settings.CACHE_* is deprecated; use settings.CACHES instead.", PendingDeprecationWarning ) else: # The default cache setting is put here so that we # can differentiate between a user who has provided # an explicit CACHE_BACKEND of locmem://, and the # default value. When the deprecation cycle has completed, # the default can be restored to global_settings.py settings.CACHE_BACKEND = 'locmem://' # Mapping for new-style cache backend api backend_classes = { 'memcached': 'memcached.CacheClass', 'locmem': 'locmem.LocMemCache', 'file': 'filebased.FileBasedCache', 'db': 'db.DatabaseCache', 'dummy': 'dummy.DummyCache', } engine, host, params = parse_backend_uri(settings.CACHE_BACKEND) if engine in backend_classes: engine = 'django.core.cache.backends.%s' % backend_classes[engine] else: engine = '%s.CacheClass' % engine defaults = { 'BACKEND': engine, 'LOCATION': host, } defaults.update(params) settings.CACHES[DEFAULT_CACHE_ALIAS] = defaults if DEFAULT_CACHE_ALIAS not in settings.CACHES: raise ImproperlyConfigured("You must define a '%s' cache" % DEFAULT_CACHE_ALIAS) def parse_backend_conf(backend, **kwargs): """ Helper function to parse the backend configuration that doesn't use the URI notation. """ # Try to get the CACHES entry for the given backend name first conf = settings.CACHES.get(backend, None) if conf is not None: args = conf.copy() args.update(kwargs) backend = args.pop('BACKEND') location = args.pop('LOCATION', '') return backend, location, args else: # Trying to import the given backend, in case it's a dotted path mod_path, cls_name = backend.rsplit('.', 1) try: mod = importlib.import_module(mod_path) backend_cls = getattr(mod, cls_name) except (AttributeError, ImportError): raise InvalidCacheBackendError("Could not find backend '%s'" % backend) location = kwargs.pop('LOCATION', '') return backend, location, kwargs raise InvalidCacheBackendError( "Couldn't find a cache backend named '%s'" % backend) def get_cache(backend, **kwargs): """ Function to load a cache backend dynamically. This is flexible by design to allow different use cases: To load a backend with the old URI-based notation:: cache = get_cache('locmem://') To load a backend that is pre-defined in the settings:: cache = get_cache('default') To load a backend with its dotted import path, including arbitrary options:: cache = get_cache('django.core.cache.backends.memcached.MemcachedCache', **{ 'LOCATION': '127.0.0.1:11211', 'TIMEOUT': 30, }) """ try: if '://' in backend: # for backwards compatibility backend, location, params = parse_backend_uri(backend) if backend in BACKENDS: backend = 'django.core.cache.backends.%s' % BACKENDS[backend] params.update(kwargs) mod = importlib.import_module(backend) backend_cls = mod.CacheClass else: backend, location, params = parse_backend_conf(backend, **kwargs) mod_path, cls_name = backend.rsplit('.', 1) mod = importlib.import_module(mod_path) backend_cls = getattr(mod, cls_name) except (AttributeError, ImportError), e: raise InvalidCacheBackendError( "Could not find backend '%s': %s" % (backend, e)) return backend_cls(location, params) cache = get_cache(DEFAULT_CACHE_ALIAS) # Some caches -- python-memcached in particular -- need to do a cleanup at the # end of a request cycle. If the cache provides a close() method, wire it up # here. if hasattr(cache, 'close'): signals.request_finished.connect(cache.close)
6,689
Python
.py
164
34.493902
84
0.668205
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,835
db.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/cache/backends/db.py
"Database cache backend." from django.core.cache.backends.base import BaseCache from django.db import connections, router, transaction, DatabaseError import base64, time from datetime import datetime try: import cPickle as pickle except ImportError: import pickle class Options(object): """A class that will quack like a Django model _meta class. This allows cache operations to be controlled by the router """ def __init__(self, table): self.db_table = table self.app_label = 'django_cache' self.module_name = 'cacheentry' self.verbose_name = 'cache entry' self.verbose_name_plural = 'cache entries' self.object_name = 'CacheEntry' self.abstract = False self.managed = True self.proxy = False class BaseDatabaseCache(BaseCache): def __init__(self, table, params): BaseCache.__init__(self, params) self._table = table class CacheEntry(object): _meta = Options(table) self.cache_model_class = CacheEntry class DatabaseCache(BaseDatabaseCache): def get(self, key, default=None, version=None): key = self.make_key(key, version=version) self.validate_key(key) db = router.db_for_read(self.cache_model_class) table = connections[db].ops.quote_name(self._table) cursor = connections[db].cursor() cursor.execute("SELECT cache_key, value, expires FROM %s WHERE cache_key = %%s" % table, [key]) row = cursor.fetchone() if row is None: return default now = datetime.now() if row[2] < now: db = router.db_for_write(self.cache_model_class) cursor = connections[db].cursor() cursor.execute("DELETE FROM %s WHERE cache_key = %%s" % table, [key]) transaction.commit_unless_managed(using=db) return default value = connections[db].ops.process_clob(row[1]) return pickle.loads(base64.decodestring(value)) def set(self, key, value, timeout=None, version=None): key = self.make_key(key, version=version) self.validate_key(key) self._base_set('set', key, value, timeout) def add(self, key, value, timeout=None, version=None): key = self.make_key(key, version=version) self.validate_key(key) return self._base_set('add', key, value, timeout) def _base_set(self, mode, key, value, timeout=None): if timeout is None: timeout = self.default_timeout db = router.db_for_write(self.cache_model_class) table = connections[db].ops.quote_name(self._table) cursor = connections[db].cursor() cursor.execute("SELECT COUNT(*) FROM %s" % table) num = cursor.fetchone()[0] now = datetime.now().replace(microsecond=0) exp = datetime.fromtimestamp(time.time() + timeout).replace(microsecond=0) if num > self._max_entries: self._cull(db, cursor, now) encoded = base64.encodestring(pickle.dumps(value, 2)).strip() cursor.execute("SELECT cache_key, expires FROM %s WHERE cache_key = %%s" % table, [key]) try: result = cursor.fetchone() if result and (mode == 'set' or (mode == 'add' and result[1] < now)): cursor.execute("UPDATE %s SET value = %%s, expires = %%s WHERE cache_key = %%s" % table, [encoded, connections[db].ops.value_to_db_datetime(exp), key]) else: cursor.execute("INSERT INTO %s (cache_key, value, expires) VALUES (%%s, %%s, %%s)" % table, [key, encoded, connections[db].ops.value_to_db_datetime(exp)]) except DatabaseError: # To be threadsafe, updates/inserts are allowed to fail silently transaction.rollback_unless_managed(using=db) return False else: transaction.commit_unless_managed(using=db) return True def delete(self, key, version=None): key = self.make_key(key, version=version) self.validate_key(key) db = router.db_for_write(self.cache_model_class) table = connections[db].ops.quote_name(self._table) cursor = connections[db].cursor() cursor.execute("DELETE FROM %s WHERE cache_key = %%s" % table, [key]) transaction.commit_unless_managed(using=db) def has_key(self, key, version=None): key = self.make_key(key, version=version) self.validate_key(key) db = router.db_for_read(self.cache_model_class) table = connections[db].ops.quote_name(self._table) cursor = connections[db].cursor() now = datetime.now().replace(microsecond=0) cursor.execute("SELECT cache_key FROM %s WHERE cache_key = %%s and expires > %%s" % table, [key, connections[db].ops.value_to_db_datetime(now)]) return cursor.fetchone() is not None def _cull(self, db, cursor, now): if self._cull_frequency == 0: self.clear() else: table = connections[db].ops.quote_name(self._table) cursor.execute("DELETE FROM %s WHERE expires < %%s" % table, [connections[db].ops.value_to_db_datetime(now)]) cursor.execute("SELECT COUNT(*) FROM %s" % table) num = cursor.fetchone()[0] if num > self._max_entries: cursor.execute("SELECT cache_key FROM %s ORDER BY cache_key LIMIT 1 OFFSET %%s" % table, [num / self._cull_frequency]) cursor.execute("DELETE FROM %s WHERE cache_key < %%s" % table, [cursor.fetchone()[0]]) def clear(self): db = router.db_for_write(self.cache_model_class) table = connections[db].ops.quote_name(self._table) cursor = connections[db].cursor() cursor.execute('DELETE FROM %s' % table) # For backwards compatibility class CacheClass(DatabaseCache): pass
6,002
Python
.py
126
38.031746
134
0.617486
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,836
locmem.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/cache/backends/locmem.py
"Thread-safe in-memory cache backend." import time try: import cPickle as pickle except ImportError: import pickle from django.core.cache.backends.base import BaseCache from django.utils.synch import RWLock # Global in-memory store of cache data. Keyed by name, to provide # multiple named local memory caches. _caches = {} _expire_info = {} _locks = {} class LocMemCache(BaseCache): def __init__(self, name, params): BaseCache.__init__(self, params) global _caches, _expire_info, _locks self._cache = _caches.setdefault(name, {}) self._expire_info = _expire_info.setdefault(name, {}) self._lock = _locks.setdefault(name, RWLock()) def add(self, key, value, timeout=None, version=None): key = self.make_key(key, version=version) self.validate_key(key) self._lock.writer_enters() try: exp = self._expire_info.get(key) if exp is None or exp <= time.time(): try: self._set(key, pickle.dumps(value), timeout) return True except pickle.PickleError: pass return False finally: self._lock.writer_leaves() def get(self, key, default=None, version=None): key = self.make_key(key, version=version) self.validate_key(key) self._lock.reader_enters() try: exp = self._expire_info.get(key) if exp is None: return default elif exp > time.time(): try: return pickle.loads(self._cache[key]) except pickle.PickleError: return default finally: self._lock.reader_leaves() self._lock.writer_enters() try: try: del self._cache[key] del self._expire_info[key] except KeyError: pass return default finally: self._lock.writer_leaves() def _set(self, key, value, timeout=None): if len(self._cache) >= self._max_entries: self._cull() if timeout is None: timeout = self.default_timeout self._cache[key] = value self._expire_info[key] = time.time() + timeout def set(self, key, value, timeout=None, version=None): key = self.make_key(key, version=version) self.validate_key(key) self._lock.writer_enters() # Python 2.4 doesn't allow combined try-except-finally blocks. try: try: self._set(key, pickle.dumps(value), timeout) except pickle.PickleError: pass finally: self._lock.writer_leaves() def has_key(self, key, version=None): key = self.make_key(key, version=version) self.validate_key(key) self._lock.reader_enters() try: exp = self._expire_info.get(key) if exp is None: return False elif exp > time.time(): return True finally: self._lock.reader_leaves() self._lock.writer_enters() try: try: del self._cache[key] del self._expire_info[key] except KeyError: pass return False finally: self._lock.writer_leaves() def _cull(self): if self._cull_frequency == 0: self.clear() else: doomed = [k for (i, k) in enumerate(self._cache) if i % self._cull_frequency == 0] for k in doomed: self._delete(k) def _delete(self, key): try: del self._cache[key] except KeyError: pass try: del self._expire_info[key] except KeyError: pass def delete(self, key, version=None): key = self.make_key(key, version=version) self.validate_key(key) self._lock.writer_enters() try: self._delete(key) finally: self._lock.writer_leaves() def clear(self): self._cache.clear() self._expire_info.clear() # For backwards compatibility class CacheClass(LocMemCache): pass
4,336
Python
.py
131
22.763359
94
0.546778
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,837
memcached.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/cache/backends/memcached.py
"Memcached cache backend" import time from threading import local from django.core.cache.backends.base import BaseCache, InvalidCacheBackendError from django.utils import importlib class BaseMemcachedCache(BaseCache): def __init__(self, server, params, library, value_not_found_exception): super(BaseMemcachedCache, self).__init__(params) if isinstance(server, basestring): self._servers = server.split(';') else: self._servers = server # The exception type to catch from the underlying library for a key # that was not found. This is a ValueError for python-memcache, # pylibmc.NotFound for pylibmc, and cmemcache will return None without # raising an exception. self.LibraryValueNotFoundException = value_not_found_exception self._lib = library self._options = params.get('OPTIONS', None) @property def _cache(self): """ Implements transparent thread-safe access to a memcached client. """ if getattr(self, '_client', None) is None: self._client = self._lib.Client(self._servers) return self._client def _get_memcache_timeout(self, timeout): """ Memcached deals with long (> 30 days) timeouts in a special way. Call this function to obtain a safe value for your timeout. """ timeout = timeout or self.default_timeout if timeout > 2592000: # 60*60*24*30, 30 days # See http://code.google.com/p/memcached/wiki/FAQ # "You can set expire times up to 30 days in the future. After that # memcached interprets it as a date, and will expire the item after # said date. This is a simple (but obscure) mechanic." # # This means that we have to switch to absolute timestamps. timeout += int(time.time()) return timeout def add(self, key, value, timeout=0, version=None): key = self.make_key(key, version=version) return self._cache.add(key, value, self._get_memcache_timeout(timeout)) def get(self, key, default=None, version=None): key = self.make_key(key, version=version) val = self._cache.get(key) if val is None: return default return val def set(self, key, value, timeout=0, version=None): key = self.make_key(key, version=version) self._cache.set(key, value, self._get_memcache_timeout(timeout)) def delete(self, key, version=None): key = self.make_key(key, version=version) self._cache.delete(key) def get_many(self, keys, version=None): new_keys = map(lambda x: self.make_key(x, version=version), keys) ret = self._cache.get_multi(new_keys) if ret: _ = {} m = dict(zip(new_keys, keys)) for k, v in ret.items(): _[m[k]] = v ret = _ return ret def close(self, **kwargs): self._cache.disconnect_all() def incr(self, key, delta=1, version=None): key = self.make_key(key, version=version) try: val = self._cache.incr(key, delta) # python-memcache responds to incr on non-existent keys by # raising a ValueError, pylibmc by raising a pylibmc.NotFound # and Cmemcache returns None. In all cases, # we should raise a ValueError though. except self.LibraryValueNotFoundException: val = None if val is None: raise ValueError("Key '%s' not found" % key) return val def decr(self, key, delta=1, version=None): key = self.make_key(key, version=version) try: val = self._cache.decr(key, delta) # python-memcache responds to incr on non-existent keys by # raising a ValueError, pylibmc by raising a pylibmc.NotFound # and Cmemcache returns None. In all cases, # we should raise a ValueError though. except self.LibraryValueNotFoundException: val = None if val is None: raise ValueError("Key '%s' not found" % key) return val def set_many(self, data, timeout=0, version=None): safe_data = {} for key, value in data.items(): key = self.make_key(key, version=version) safe_data[key] = value self._cache.set_multi(safe_data, self._get_memcache_timeout(timeout)) def delete_many(self, keys, version=None): l = lambda x: self.make_key(x, version=version) self._cache.delete_multi(map(l, keys)) def clear(self): self._cache.flush_all() # For backwards compatibility -- the default cache class tries a # cascading lookup of cmemcache, then memcache. class CacheClass(BaseMemcachedCache): def __init__(self, server, params): try: import cmemcache as memcache import warnings warnings.warn( "Support for the 'cmemcache' library has been deprecated. Please use python-memcached or pyblimc instead.", DeprecationWarning ) except ImportError: try: import memcache except: raise InvalidCacheBackendError( "Memcached cache backend requires either the 'memcache' or 'cmemcache' library" ) super(CacheClass, self).__init__(server, params, library=memcache, value_not_found_exception=ValueError) class MemcachedCache(BaseMemcachedCache): "An implementation of a cache binding using python-memcached" def __init__(self, server, params): import memcache super(MemcachedCache, self).__init__(server, params, library=memcache, value_not_found_exception=ValueError) class PyLibMCCache(BaseMemcachedCache): "An implementation of a cache binding using pylibmc" def __init__(self, server, params): import pylibmc self._local = local() super(PyLibMCCache, self).__init__(server, params, library=pylibmc, value_not_found_exception=pylibmc.NotFound) @property def _cache(self): # PylibMC uses cache options as the 'behaviors' attribute. # It also needs to use threadlocals, because some versions of # PylibMC don't play well with the GIL. client = getattr(self._local, 'client', None) if client: return client client = self._lib.Client(self._servers) if self._options: client.behaviors = self._options self._local.client = client return client
6,890
Python
.py
155
33.83871
123
0.608916
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,838
base.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/cache/backends/base.py
"Base Cache class." import warnings from django.conf import settings from django.core.exceptions import ImproperlyConfigured, DjangoRuntimeWarning from django.utils.encoding import smart_str from django.utils.importlib import import_module class InvalidCacheBackendError(ImproperlyConfigured): pass class CacheKeyWarning(DjangoRuntimeWarning): pass # Memcached does not accept keys longer than this. MEMCACHE_MAX_KEY_LENGTH = 250 def default_key_func(key, key_prefix, version): """ Default function to generate keys. Constructs the key used by all other methods. By default it prepends the `key_prefix'. KEY_FUNCTION can be used to specify an alternate function with custom key making behavior. """ return ':'.join([key_prefix, str(version), smart_str(key)]) def get_key_func(key_func): """ Function to decide which key function to use. Defaults to ``default_key_func``. """ if key_func is not None: if callable(key_func): return key_func else: key_func_module_path, key_func_name = key_func.rsplit('.', 1) key_func_module = import_module(key_func_module_path) return getattr(key_func_module, key_func_name) return default_key_func class BaseCache(object): def __init__(self, params): timeout = params.get('timeout', params.get('TIMEOUT', 300)) try: timeout = int(timeout) except (ValueError, TypeError): timeout = 300 self.default_timeout = timeout options = params.get('OPTIONS', {}) max_entries = params.get('max_entries', options.get('MAX_ENTRIES', 300)) try: self._max_entries = int(max_entries) except (ValueError, TypeError): self._max_entries = 300 cull_frequency = params.get('cull_frequency', options.get('CULL_FREQUENCY', 3)) try: self._cull_frequency = int(cull_frequency) except (ValueError, TypeError): self._cull_frequency = 3 self.key_prefix = smart_str(params.get('KEY_PREFIX', '')) self.version = params.get('VERSION', 1) self.key_func = get_key_func(params.get('KEY_FUNCTION', None)) def make_key(self, key, version=None): """Constructs the key used by all other methods. By default it uses the key_func to generate a key (which, by default, prepends the `key_prefix' and 'version'). An different key function can be provided at the time of cache construction; alternatively, you can subclass the cache backend to provide custom key making behavior. """ if version is None: version = self.version new_key = self.key_func(key, self.key_prefix, version) return new_key def add(self, key, value, timeout=None, version=None): """ Set a value in the cache if the key does not already exist. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used. Returns True if the value was stored, False otherwise. """ raise NotImplementedError def get(self, key, default=None, version=None): """ Fetch a given key from the cache. If the key does not exist, return default, which itself defaults to None. """ raise NotImplementedError def set(self, key, value, timeout=None, version=None): """ Set a value in the cache. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used. """ raise NotImplementedError def delete(self, key, version=None): """ Delete a key from the cache, failing silently. """ raise NotImplementedError def get_many(self, keys, version=None): """ Fetch a bunch of keys from the cache. For certain backends (memcached, pgsql) this can be *much* faster when fetching multiple values. Returns a dict mapping each key in keys to its value. If the given key is missing, it will be missing from the response dict. """ d = {} for k in keys: val = self.get(k, version=version) if val is not None: d[k] = val return d def has_key(self, key, version=None): """ Returns True if the key is in the cache and has not expired. """ return self.get(key, version=version) is not None def incr(self, key, delta=1, version=None): """ Add delta to value in the cache. If the key does not exist, raise a ValueError exception. """ value = self.get(key, version=version) if value is None: raise ValueError("Key '%s' not found" % key) new_value = value + delta self.set(key, new_value, version=version) return new_value def decr(self, key, delta=1, version=None): """ Subtract delta from value in the cache. If the key does not exist, raise a ValueError exception. """ return self.incr(key, -delta, version=version) def __contains__(self, key): """ Returns True if the key is in the cache and has not expired. """ # This is a separate method, rather than just a copy of has_key(), # so that it always has the same functionality as has_key(), even # if a subclass overrides it. return self.has_key(key) def set_many(self, data, timeout=None, version=None): """ Set a bunch of values in the cache at once from a dict of key/value pairs. For certain backends (memcached), this is much more efficient than calling set() multiple times. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used. """ for key, value in data.items(): self.set(key, value, timeout=timeout, version=version) def delete_many(self, keys, version=None): """ Set a bunch of values in the cache at once. For certain backends (memcached), this is much more efficient than calling delete() multiple times. """ for key in keys: self.delete(key, version=version) def clear(self): """Remove *all* values from the cache at once.""" raise NotImplementedError def validate_key(self, key): """ Warn about keys that would not be portable to the memcached backend. This encourages (but does not force) writing backend-portable cache code. """ if len(key) > MEMCACHE_MAX_KEY_LENGTH: warnings.warn('Cache key will cause errors if used with memcached: ' '%s (longer than %s)' % (key, MEMCACHE_MAX_KEY_LENGTH), CacheKeyWarning) for char in key: if ord(char) < 33 or ord(char) == 127: warnings.warn('Cache key contains characters that will cause ' 'errors if used with memcached: %r' % key, CacheKeyWarning) def incr_version(self, key, delta=1, version=None): """Adds delta to the cache version for the supplied key. Returns the new version. """ if version is None: version = self.version value = self.get(key, version=version) if value is None: raise ValueError("Key '%s' not found" % key) self.set(key, value, version=version+delta) self.delete(key, version=version) return version+delta def decr_version(self, key, delta=1, version=None): """Substracts delta from the cache version for the supplied key. Returns the new version. """ return self.incr_version(key, -delta, version)
7,960
Python
.py
188
33.542553
87
0.627585
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,839
filebased.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/cache/backends/filebased.py
"File-based cache backend" import os import time import shutil try: import cPickle as pickle except ImportError: import pickle from django.core.cache.backends.base import BaseCache from django.utils.hashcompat import md5_constructor class FileBasedCache(BaseCache): def __init__(self, dir, params): BaseCache.__init__(self, params) self._dir = dir if not os.path.exists(self._dir): self._createdir() def add(self, key, value, timeout=None, version=None): if self.has_key(key, version=version): return False self.set(key, value, timeout, version=version) return True def get(self, key, default=None, version=None): key = self.make_key(key, version=version) self.validate_key(key) fname = self._key_to_file(key) try: f = open(fname, 'rb') try: exp = pickle.load(f) now = time.time() if exp < now: self._delete(fname) else: return pickle.load(f) finally: f.close() except (IOError, OSError, EOFError, pickle.PickleError): pass return default def set(self, key, value, timeout=None, version=None): key = self.make_key(key, version=version) self.validate_key(key) fname = self._key_to_file(key) dirname = os.path.dirname(fname) if timeout is None: timeout = self.default_timeout self._cull() try: if not os.path.exists(dirname): os.makedirs(dirname) f = open(fname, 'wb') try: now = time.time() pickle.dump(now + timeout, f, pickle.HIGHEST_PROTOCOL) pickle.dump(value, f, pickle.HIGHEST_PROTOCOL) finally: f.close() except (IOError, OSError): pass def delete(self, key, version=None): key = self.make_key(key, version=version) self.validate_key(key) try: self._delete(self._key_to_file(key)) except (IOError, OSError): pass def _delete(self, fname): os.remove(fname) try: # Remove the 2 subdirs if they're empty dirname = os.path.dirname(fname) os.rmdir(dirname) os.rmdir(os.path.dirname(dirname)) except (IOError, OSError): pass def has_key(self, key, version=None): key = self.make_key(key, version=version) self.validate_key(key) fname = self._key_to_file(key) try: f = open(fname, 'rb') try: exp = pickle.load(f) now = time.time() if exp < now: self._delete(fname) return False else: return True finally: f.close() except (IOError, OSError, EOFError, pickle.PickleError): return False def _cull(self): if int(self._num_entries) < self._max_entries: return try: filelist = sorted(os.listdir(self._dir)) except (IOError, OSError): return if self._cull_frequency == 0: doomed = filelist else: doomed = [os.path.join(self._dir, k) for (i, k) in enumerate(filelist) if i % self._cull_frequency == 0] for topdir in doomed: try: for root, _, files in os.walk(topdir): for f in files: self._delete(os.path.join(root, f)) except (IOError, OSError): pass def _createdir(self): try: os.makedirs(self._dir) except OSError: raise EnvironmentError("Cache directory '%s' does not exist and could not be created'" % self._dir) def _key_to_file(self, key): """ Convert the filename into an md5 string. We'll turn the first couple bits of the path into directory prefixes to be nice to filesystems that have problems with large numbers of files in a directory. Thus, a cache key of "foo" gets turnned into a file named ``{cache-dir}ac/bd/18db4cc2f85cedef654fccc4a4d8``. """ path = md5_constructor(key).hexdigest() path = os.path.join(path[:2], path[2:4], path[4:]) return os.path.join(self._dir, path) def _get_num_entries(self): count = 0 for _,_,files in os.walk(self._dir): count += len(files) return count _num_entries = property(_get_num_entries) def clear(self): try: shutil.rmtree(self._dir) except (IOError, OSError): pass # For backwards compatibility class CacheClass(FileBasedCache): pass
4,947
Python
.py
141
24.397163
116
0.550418
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,840
dummy.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/cache/backends/dummy.py
"Dummy cache backend" from django.core.cache.backends.base import BaseCache class DummyCache(BaseCache): def __init__(self, host, *args, **kwargs): BaseCache.__init__(self, *args, **kwargs) def add(self, key, value, timeout=None, version=None): key = self.make_key(key, version=version) self.validate_key(key) return True def get(self, key, default=None, version=None): key = self.make_key(key, version=version) self.validate_key(key) return default def set(self, key, value, timeout=None, version=None): key = self.make_key(key, version=version) self.validate_key(key) def delete(self, key, version=None): key = self.make_key(key, version=version) self.validate_key(key) def get_many(self, keys, version=None): return {} def has_key(self, key, version=None): key = self.make_key(key, version=version) self.validate_key(key) return False def set_many(self, data, version=None): pass def delete_many(self, keys, version=None): pass def clear(self): pass # For backwards compatibility class CacheClass(DummyCache): pass
1,218
Python
.py
34
28.941176
58
0.649317
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,841
python.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/serializers/python.py
""" A Python "serializer". Doesn't do much serializing per se -- just converts to and from basic Python data types (lists, dicts, strings, etc.). Useful as a basis for other serializers. """ from django.conf import settings from django.core.serializers import base from django.db import models, DEFAULT_DB_ALIAS from django.utils.encoding import smart_unicode, is_protected_type class Serializer(base.Serializer): """ Serializes a QuerySet to basic Python objects. """ internal_use_only = True def start_serialization(self): self._current = None self.objects = [] def end_serialization(self): pass def start_object(self, obj): self._current = {} def end_object(self, obj): self.objects.append({ "model" : smart_unicode(obj._meta), "pk" : smart_unicode(obj._get_pk_val(), strings_only=True), "fields" : self._current }) self._current = None def handle_field(self, obj, field): value = field._get_val_from_obj(obj) # Protected types (i.e., primitives like None, numbers, dates, # and Decimals) are passed through as is. All other values are # converted to string first. if is_protected_type(value): self._current[field.name] = value else: self._current[field.name] = field.value_to_string(obj) def handle_fk_field(self, obj, field): related = getattr(obj, field.name) if related is not None: if self.use_natural_keys and hasattr(related, 'natural_key'): related = related.natural_key() else: if field.rel.field_name == related._meta.pk.name: # Related to remote object via primary key related = related._get_pk_val() else: # Related to remote object via other field related = smart_unicode(getattr(related, field.rel.field_name), strings_only=True) self._current[field.name] = related def handle_m2m_field(self, obj, field): if field.rel.through._meta.auto_created: if self.use_natural_keys and hasattr(field.rel.to, 'natural_key'): m2m_value = lambda value: value.natural_key() else: m2m_value = lambda value: smart_unicode(value._get_pk_val(), strings_only=True) self._current[field.name] = [m2m_value(related) for related in getattr(obj, field.name).iterator()] def getvalue(self): return self.objects def Deserializer(object_list, **options): """ Deserialize simple Python objects back into Django ORM instances. It's expected that you pass the Python objects themselves (instead of a stream or a string) to the constructor """ db = options.pop('using', DEFAULT_DB_ALIAS) models.get_apps() for d in object_list: # Look up the model and starting build a dict of data for it. Model = _get_model(d["model"]) data = {Model._meta.pk.attname : Model._meta.pk.to_python(d["pk"])} m2m_data = {} # Handle each field for (field_name, field_value) in d["fields"].iteritems(): if isinstance(field_value, str): field_value = smart_unicode(field_value, options.get("encoding", settings.DEFAULT_CHARSET), strings_only=True) field = Model._meta.get_field(field_name) # Handle M2M relations if field.rel and isinstance(field.rel, models.ManyToManyRel): if hasattr(field.rel.to._default_manager, 'get_by_natural_key'): def m2m_convert(value): if hasattr(value, '__iter__'): return field.rel.to._default_manager.db_manager(db).get_by_natural_key(*value).pk else: return smart_unicode(field.rel.to._meta.pk.to_python(value)) else: m2m_convert = lambda v: smart_unicode(field.rel.to._meta.pk.to_python(v)) m2m_data[field.name] = [m2m_convert(pk) for pk in field_value] # Handle FK fields elif field.rel and isinstance(field.rel, models.ManyToOneRel): if field_value is not None: if hasattr(field.rel.to._default_manager, 'get_by_natural_key'): if hasattr(field_value, '__iter__'): obj = field.rel.to._default_manager.db_manager(db).get_by_natural_key(*field_value) value = getattr(obj, field.rel.field_name) # If this is a natural foreign key to an object that # has a FK/O2O as the foreign key, use the FK value if field.rel.to._meta.pk.rel: value = value.pk else: value = field.rel.to._meta.get_field(field.rel.field_name).to_python(field_value) data[field.attname] = value else: data[field.attname] = field.rel.to._meta.get_field(field.rel.field_name).to_python(field_value) else: data[field.attname] = None # Handle all other fields else: data[field.name] = field.to_python(field_value) yield base.DeserializedObject(Model(**data), m2m_data) def _get_model(model_identifier): """ Helper to look up a model from an "app_label.module_name" string. """ try: Model = models.get_model(*model_identifier.split(".")) except TypeError: Model = None if Model is None: raise base.DeserializationError(u"Invalid model identifier: '%s'" % model_identifier) return Model
5,919
Python
.py
122
36.278689
126
0.584213
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,842
pyyaml.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/serializers/pyyaml.py
""" YAML serializer. Requires PyYaml (http://pyyaml.org/), but that's checked for in __init__. """ from StringIO import StringIO import decimal import yaml from django.db import models from django.core.serializers.python import Serializer as PythonSerializer from django.core.serializers.python import Deserializer as PythonDeserializer class DjangoSafeDumper(yaml.SafeDumper): def represent_decimal(self, data): return self.represent_scalar('tag:yaml.org,2002:str', str(data)) DjangoSafeDumper.add_representer(decimal.Decimal, DjangoSafeDumper.represent_decimal) class Serializer(PythonSerializer): """ Convert a queryset to YAML. """ internal_use_only = False def handle_field(self, obj, field): # A nasty special case: base YAML doesn't support serialization of time # types (as opposed to dates or datetimes, which it does support). Since # we want to use the "safe" serializer for better interoperability, we # need to do something with those pesky times. Converting 'em to strings # isn't perfect, but it's better than a "!!python/time" type which would # halt deserialization under any other language. if isinstance(field, models.TimeField) and getattr(obj, field.name) is not None: self._current[field.name] = str(getattr(obj, field.name)) else: super(Serializer, self).handle_field(obj, field) def end_serialization(self): yaml.dump(self.objects, self.stream, Dumper=DjangoSafeDumper, **self.options) def getvalue(self): return self.stream.getvalue() def Deserializer(stream_or_string, **options): """ Deserialize a stream or string of YAML data. """ if isinstance(stream_or_string, basestring): stream = StringIO(stream_or_string) else: stream = stream_or_string for obj in PythonDeserializer(yaml.load(stream), **options): yield obj
1,948
Python
.py
44
38.636364
88
0.718816
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,843
xml_serializer.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/serializers/xml_serializer.py
""" XML serializer. """ from django.conf import settings from django.core.serializers import base from django.db import models, DEFAULT_DB_ALIAS from django.utils.xmlutils import SimplerXMLGenerator from django.utils.encoding import smart_unicode from xml.dom import pulldom class Serializer(base.Serializer): """ Serializes a QuerySet to XML. """ def indent(self, level): if self.options.get('indent', None) is not None: self.xml.ignorableWhitespace('\n' + ' ' * self.options.get('indent', None) * level) def start_serialization(self): """ Start serialization -- open the XML document and the root element. """ self.xml = SimplerXMLGenerator(self.stream, self.options.get("encoding", settings.DEFAULT_CHARSET)) self.xml.startDocument() self.xml.startElement("django-objects", {"version" : "1.0"}) def end_serialization(self): """ End serialization -- end the document. """ self.indent(0) self.xml.endElement("django-objects") self.xml.endDocument() def start_object(self, obj): """ Called as each object is handled. """ if not hasattr(obj, "_meta"): raise base.SerializationError("Non-model object (%s) encountered during serialization" % type(obj)) self.indent(1) obj_pk = obj._get_pk_val() if obj_pk is None: attrs = {"model": smart_unicode(obj._meta),} else: attrs = { "pk": smart_unicode(obj._get_pk_val()), "model": smart_unicode(obj._meta), } self.xml.startElement("object", attrs) def end_object(self, obj): """ Called after handling all fields for an object. """ self.indent(1) self.xml.endElement("object") def handle_field(self, obj, field): """ Called to handle each field on an object (except for ForeignKeys and ManyToManyFields) """ self.indent(2) self.xml.startElement("field", { "name" : field.name, "type" : field.get_internal_type() }) # Get a "string version" of the object's data. if getattr(obj, field.name) is not None: self.xml.characters(field.value_to_string(obj)) else: self.xml.addQuickElement("None") self.xml.endElement("field") def handle_fk_field(self, obj, field): """ Called to handle a ForeignKey (we need to treat them slightly differently from regular fields). """ self._start_relational_field(field) related = getattr(obj, field.name) if related is not None: if self.use_natural_keys and hasattr(related, 'natural_key'): # If related object has a natural key, use it related = related.natural_key() # Iterable natural keys are rolled out as subelements for key_value in related: self.xml.startElement("natural", {}) self.xml.characters(smart_unicode(key_value)) self.xml.endElement("natural") else: if field.rel.field_name == related._meta.pk.name: # Related to remote object via primary key related = related._get_pk_val() else: # Related to remote object via other field related = getattr(related, field.rel.field_name) self.xml.characters(smart_unicode(related)) else: self.xml.addQuickElement("None") self.xml.endElement("field") def handle_m2m_field(self, obj, field): """ Called to handle a ManyToManyField. Related objects are only serialized as references to the object's PK (i.e. the related *data* is not dumped, just the relation). """ if field.rel.through._meta.auto_created: self._start_relational_field(field) if self.use_natural_keys and hasattr(field.rel.to, 'natural_key'): # If the objects in the m2m have a natural key, use it def handle_m2m(value): natural = value.natural_key() # Iterable natural keys are rolled out as subelements self.xml.startElement("object", {}) for key_value in natural: self.xml.startElement("natural", {}) self.xml.characters(smart_unicode(key_value)) self.xml.endElement("natural") self.xml.endElement("object") else: def handle_m2m(value): self.xml.addQuickElement("object", attrs={ 'pk' : smart_unicode(value._get_pk_val()) }) for relobj in getattr(obj, field.name).iterator(): handle_m2m(relobj) self.xml.endElement("field") def _start_relational_field(self, field): """ Helper to output the <field> element for relational fields """ self.indent(2) self.xml.startElement("field", { "name" : field.name, "rel" : field.rel.__class__.__name__, "to" : smart_unicode(field.rel.to._meta), }) class Deserializer(base.Deserializer): """ Deserialize XML. """ def __init__(self, stream_or_string, **options): super(Deserializer, self).__init__(stream_or_string, **options) self.event_stream = pulldom.parse(self.stream) self.db = options.pop('using', DEFAULT_DB_ALIAS) def next(self): for event, node in self.event_stream: if event == "START_ELEMENT" and node.nodeName == "object": self.event_stream.expandNode(node) return self._handle_object(node) raise StopIteration def _handle_object(self, node): """ Convert an <object> node to a DeserializedObject. """ # Look up the model using the model loading mechanism. If this fails, # bail. Model = self._get_model_from_node(node, "model") # Start building a data dictionary from the object. # If the node is missing the pk set it to None if node.hasAttribute("pk"): pk = node.getAttribute("pk") else: pk = None data = {Model._meta.pk.attname : Model._meta.pk.to_python(pk)} # Also start building a dict of m2m data (this is saved as # {m2m_accessor_attribute : [list_of_related_objects]}) m2m_data = {} # Deseralize each field. for field_node in node.getElementsByTagName("field"): # If the field is missing the name attribute, bail (are you # sensing a pattern here?) field_name = field_node.getAttribute("name") if not field_name: raise base.DeserializationError("<field> node is missing the 'name' attribute") # Get the field from the Model. This will raise a # FieldDoesNotExist if, well, the field doesn't exist, which will # be propagated correctly. field = Model._meta.get_field(field_name) # As is usually the case, relation fields get the special treatment. if field.rel and isinstance(field.rel, models.ManyToManyRel): m2m_data[field.name] = self._handle_m2m_field_node(field_node, field) elif field.rel and isinstance(field.rel, models.ManyToOneRel): data[field.attname] = self._handle_fk_field_node(field_node, field) else: if field_node.getElementsByTagName('None'): value = None else: value = field.to_python(getInnerText(field_node).strip()) data[field.name] = value # Return a DeserializedObject so that the m2m data has a place to live. return base.DeserializedObject(Model(**data), m2m_data) def _handle_fk_field_node(self, node, field): """ Handle a <field> node for a ForeignKey """ # Check if there is a child node named 'None', returning None if so. if node.getElementsByTagName('None'): return None else: if hasattr(field.rel.to._default_manager, 'get_by_natural_key'): keys = node.getElementsByTagName('natural') if keys: # If there are 'natural' subelements, it must be a natural key field_value = [getInnerText(k).strip() for k in keys] obj = field.rel.to._default_manager.db_manager(self.db).get_by_natural_key(*field_value) obj_pk = getattr(obj, field.rel.field_name) # If this is a natural foreign key to an object that # has a FK/O2O as the foreign key, use the FK value if field.rel.to._meta.pk.rel: obj_pk = obj_pk.pk else: # Otherwise, treat like a normal PK field_value = getInnerText(node).strip() obj_pk = field.rel.to._meta.get_field(field.rel.field_name).to_python(field_value) return obj_pk else: field_value = getInnerText(node).strip() return field.rel.to._meta.get_field(field.rel.field_name).to_python(field_value) def _handle_m2m_field_node(self, node, field): """ Handle a <field> node for a ManyToManyField. """ if hasattr(field.rel.to._default_manager, 'get_by_natural_key'): def m2m_convert(n): keys = n.getElementsByTagName('natural') if keys: # If there are 'natural' subelements, it must be a natural key field_value = [getInnerText(k).strip() for k in keys] obj_pk = field.rel.to._default_manager.db_manager(self.db).get_by_natural_key(*field_value).pk else: # Otherwise, treat like a normal PK value. obj_pk = field.rel.to._meta.pk.to_python(n.getAttribute('pk')) return obj_pk else: m2m_convert = lambda n: field.rel.to._meta.pk.to_python(n.getAttribute('pk')) return [m2m_convert(c) for c in node.getElementsByTagName("object")] def _get_model_from_node(self, node, attr): """ Helper to look up a model from a <object model=...> or a <field rel=... to=...> node. """ model_identifier = node.getAttribute(attr) if not model_identifier: raise base.DeserializationError( "<%s> node is missing the required '%s' attribute" \ % (node.nodeName, attr)) try: Model = models.get_model(*model_identifier.split(".")) except TypeError: Model = None if Model is None: raise base.DeserializationError( "<%s> node has invalid model identifier: '%s'" % \ (node.nodeName, model_identifier)) return Model def getInnerText(node): """ Get all the inner text of a DOM node (recursively). """ # inspired by http://mail.python.org/pipermail/xml-sig/2005-March/011022.html inner_text = [] for child in node.childNodes: if child.nodeType == child.TEXT_NODE or child.nodeType == child.CDATA_SECTION_NODE: inner_text.append(child.data) elif child.nodeType == child.ELEMENT_NODE: inner_text.extend(getInnerText(child)) else: pass return u"".join(inner_text)
11,885
Python
.py
265
33.015094
114
0.574301
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,844
__init__.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/serializers/__init__.py
""" Interfaces for serializing Django objects. Usage:: from django.core import serializers json = serializers.serialize("json", some_query_set) objects = list(serializers.deserialize("json", json)) To add your own serializers, use the SERIALIZATION_MODULES setting:: SERIALIZATION_MODULES = { "csv" : "path.to.csv.serializer", "txt" : "path.to.txt.serializer", } """ from django.conf import settings from django.utils import importlib # Built-in serializers BUILTIN_SERIALIZERS = { "xml" : "django.core.serializers.xml_serializer", "python" : "django.core.serializers.python", "json" : "django.core.serializers.json", } # Check for PyYaml and register the serializer if it's available. try: import yaml BUILTIN_SERIALIZERS["yaml"] = "django.core.serializers.pyyaml" except ImportError: pass _serializers = {} def register_serializer(format, serializer_module, serializers=None): """Register a new serializer. ``serializer_module`` should be the fully qualified module name for the serializer. If ``serializers`` is provided, the registration will be added to the provided dictionary. If ``serializers`` is not provided, the registration will be made directly into the global register of serializers. Adding serializers directly is not a thread-safe operation. """ if serializers is None and not _serializers: _load_serializers() module = importlib.import_module(serializer_module) if serializers is None: _serializers[format] = module else: serializers[format] = module def unregister_serializer(format): "Unregister a given serializer. This is not a thread-safe operation." if not _serializers: _load_serializers() del _serializers[format] def get_serializer(format): if not _serializers: _load_serializers() return _serializers[format].Serializer def get_serializer_formats(): if not _serializers: _load_serializers() return _serializers.keys() def get_public_serializer_formats(): if not _serializers: _load_serializers() return [k for k, v in _serializers.iteritems() if not v.Serializer.internal_use_only] def get_deserializer(format): if not _serializers: _load_serializers() return _serializers[format].Deserializer def serialize(format, queryset, **options): """ Serialize a queryset (or any iterator that returns database objects) using a certain serializer. """ s = get_serializer(format)() s.serialize(queryset, **options) return s.getvalue() def deserialize(format, stream_or_string, **options): """ Deserialize a stream or a string. Returns an iterator that yields ``(obj, m2m_relation_dict)``, where ``obj`` is a instantiated -- but *unsaved* -- object, and ``m2m_relation_dict`` is a dictionary of ``{m2m_field_name : list_of_related_objects}``. """ d = get_deserializer(format) return d(stream_or_string, **options) def _load_serializers(): """ Register built-in and settings-defined serializers. This is done lazily so that user code has a chance to (e.g.) set up custom settings without needing to be careful of import order. """ global _serializers serializers = {} for format in BUILTIN_SERIALIZERS: register_serializer(format, BUILTIN_SERIALIZERS[format], serializers) if hasattr(settings, "SERIALIZATION_MODULES"): for format in settings.SERIALIZATION_MODULES: register_serializer(format, settings.SERIALIZATION_MODULES[format], serializers) _serializers = serializers
3,665
Python
.py
96
33.333333
92
0.714487
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,845
base.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/serializers/base.py
""" Module for abstract serializer/unserializer base classes. """ from StringIO import StringIO from django.db import models from django.utils.encoding import smart_str, smart_unicode from django.utils import datetime_safe class SerializationError(Exception): """Something bad happened during serialization.""" pass class DeserializationError(Exception): """Something bad happened during deserialization.""" pass class Serializer(object): """ Abstract serializer base class. """ # Indicates if the implemented serializer is only available for # internal Django use. internal_use_only = False def serialize(self, queryset, **options): """ Serialize a queryset. """ self.options = options self.stream = options.pop("stream", StringIO()) self.selected_fields = options.pop("fields", None) self.use_natural_keys = options.pop("use_natural_keys", False) self.start_serialization() for obj in queryset: self.start_object(obj) for field in obj._meta.local_fields: if field.serialize: if field.rel is None: if self.selected_fields is None or field.attname in self.selected_fields: self.handle_field(obj, field) else: if self.selected_fields is None or field.attname[:-3] in self.selected_fields: self.handle_fk_field(obj, field) for field in obj._meta.many_to_many: if field.serialize: if self.selected_fields is None or field.attname in self.selected_fields: self.handle_m2m_field(obj, field) self.end_object(obj) self.end_serialization() return self.getvalue() def get_string_value(self, obj, field): """ Convert a field's value to a string. """ return smart_unicode(field.value_to_string(obj)) def start_serialization(self): """ Called when serializing of the queryset starts. """ raise NotImplementedError def end_serialization(self): """ Called when serializing of the queryset ends. """ pass def start_object(self, obj): """ Called when serializing of an object starts. """ raise NotImplementedError def end_object(self, obj): """ Called when serializing of an object ends. """ pass def handle_field(self, obj, field): """ Called to handle each individual (non-relational) field on an object. """ raise NotImplementedError def handle_fk_field(self, obj, field): """ Called to handle a ForeignKey field. """ raise NotImplementedError def handle_m2m_field(self, obj, field): """ Called to handle a ManyToManyField. """ raise NotImplementedError def getvalue(self): """ Return the fully serialized queryset (or None if the output stream is not seekable). """ if callable(getattr(self.stream, 'getvalue', None)): return self.stream.getvalue() class Deserializer(object): """ Abstract base deserializer class. """ def __init__(self, stream_or_string, **options): """ Init this serializer given a stream or a string """ self.options = options if isinstance(stream_or_string, basestring): self.stream = StringIO(stream_or_string) else: self.stream = stream_or_string # hack to make sure that the models have all been loaded before # deserialization starts (otherwise subclass calls to get_model() # and friends might fail...) models.get_apps() def __iter__(self): return self def next(self): """Iteration iterface -- return the next item in the stream""" raise NotImplementedError class DeserializedObject(object): """ A deserialized model. Basically a container for holding the pre-saved deserialized data along with the many-to-many data saved with the object. Call ``save()`` to save the object (with the many-to-many data) to the database; call ``save(save_m2m=False)`` to save just the object fields (and not touch the many-to-many stuff.) """ def __init__(self, obj, m2m_data=None): self.object = obj self.m2m_data = m2m_data def __repr__(self): return "<DeserializedObject: %s.%s(pk=%s)>" % ( self.object._meta.app_label, self.object._meta.object_name, self.object.pk) def save(self, save_m2m=True, using=None): # Call save on the Model baseclass directly. This bypasses any # model-defined save. The save is also forced to be raw. # This ensures that the data that is deserialized is literally # what came from the file, not post-processed by pre_save/save # methods. models.Model.save_base(self.object, using=using, raw=True) if self.m2m_data and save_m2m: for accessor_name, object_list in self.m2m_data.items(): setattr(self.object, accessor_name, object_list) # prevent a second (possibly accidental) call to save() from saving # the m2m data twice. self.m2m_data = None
5,487
Python
.py
143
29.587413
102
0.622013
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,846
json.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/serializers/json.py
""" Serialize data to/from JSON """ import datetime import decimal from StringIO import StringIO from django.core.serializers.python import Serializer as PythonSerializer from django.core.serializers.python import Deserializer as PythonDeserializer from django.utils import datetime_safe from django.utils import simplejson class Serializer(PythonSerializer): """ Convert a queryset to JSON. """ internal_use_only = False def end_serialization(self): simplejson.dump(self.objects, self.stream, cls=DjangoJSONEncoder, **self.options) def getvalue(self): if callable(getattr(self.stream, 'getvalue', None)): return self.stream.getvalue() def Deserializer(stream_or_string, **options): """ Deserialize a stream or string of JSON data. """ if isinstance(stream_or_string, basestring): stream = StringIO(stream_or_string) else: stream = stream_or_string for obj in PythonDeserializer(simplejson.load(stream), **options): yield obj class DjangoJSONEncoder(simplejson.JSONEncoder): """ JSONEncoder subclass that knows how to encode date/time and decimal types. """ DATE_FORMAT = "%Y-%m-%d" TIME_FORMAT = "%H:%M:%S" def default(self, o): if isinstance(o, datetime.datetime): d = datetime_safe.new_datetime(o) return d.strftime("%s %s" % (self.DATE_FORMAT, self.TIME_FORMAT)) elif isinstance(o, datetime.date): d = datetime_safe.new_date(o) return d.strftime(self.DATE_FORMAT) elif isinstance(o, datetime.time): return o.strftime(self.TIME_FORMAT) elif isinstance(o, decimal.Decimal): return str(o) else: return super(DjangoJSONEncoder, self).default(o) # Older, deprecated class name (for backwards compatibility purposes). DateTimeAwareJSONEncoder = DjangoJSONEncoder
1,920
Python
.py
51
31.568627
89
0.696448
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,847
basehttp.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/servers/basehttp.py
""" BaseHTTPServer that implements the Python WSGI protocol (PEP 333, rev 1.21). Adapted from wsgiref.simple_server: http://svn.eby-sarna.com/wsgiref/ This is a simple server for use in testing or debugging Django apps. It hasn't been reviewed for security issues. Don't use it for production use. """ from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer import os import re import socket import sys import urllib import warnings from django.core.management.color import color_style from django.utils.http import http_date from django.utils._os import safe_join from django.views import static from django.contrib.staticfiles import handlers __version__ = "0.1" __all__ = ['WSGIServer','WSGIRequestHandler'] server_version = "WSGIServer/" + __version__ sys_version = "Python/" + sys.version.split()[0] software_version = server_version + ' ' + sys_version class WSGIServerException(Exception): pass class FileWrapper(object): """Wrapper to convert file-like objects to iterables""" def __init__(self, filelike, blksize=8192): self.filelike = filelike self.blksize = blksize if hasattr(filelike,'close'): self.close = filelike.close def __getitem__(self,key): data = self.filelike.read(self.blksize) if data: return data raise IndexError def __iter__(self): return self def next(self): data = self.filelike.read(self.blksize) if data: return data raise StopIteration # Regular expression that matches `special' characters in parameters, the # existence of which force quoting of the parameter value. tspecials = re.compile(r'[ \(\)<>@,;:\\"/\[\]\?=]') def _formatparam(param, value=None, quote=1): """Convenience function to format and return a key=value pair. This will quote the value if needed or if quote is true. """ if value is not None and len(value) > 0: if quote or tspecials.search(value): value = value.replace('\\', '\\\\').replace('"', r'\"') return '%s="%s"' % (param, value) else: return '%s=%s' % (param, value) else: return param class Headers(object): """Manage a collection of HTTP response headers""" def __init__(self,headers): if not isinstance(headers, list): raise TypeError("Headers must be a list of name/value tuples") self._headers = headers def __len__(self): """Return the total number of headers, including duplicates.""" return len(self._headers) def __setitem__(self, name, val): """Set the value of a header.""" del self[name] self._headers.append((name, val)) def __delitem__(self,name): """Delete all occurrences of a header, if present. Does *not* raise an exception if the header is missing. """ name = name.lower() self._headers[:] = [kv for kv in self._headers if kv[0].lower()<>name] def __getitem__(self,name): """Get the first header value for 'name' Return None if the header is missing instead of raising an exception. Note that if the header appeared multiple times, the first exactly which occurrance gets returned is undefined. Use getall() to get all the values matching a header field name. """ return self.get(name) def has_key(self, name): """Return true if the message contains the header.""" return self.get(name) is not None __contains__ = has_key def get_all(self, name): """Return a list of all the values for the named field. These will be sorted in the order they appeared in the original header list or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. If no fields exist with the given name, returns an empty list. """ name = name.lower() return [kv[1] for kv in self._headers if kv[0].lower()==name] def get(self,name,default=None): """Get the first header value for 'name', or return 'default'""" name = name.lower() for k,v in self._headers: if k.lower()==name: return v return default def keys(self): """Return a list of all the header field names. These will be sorted in the order they appeared in the original header list, or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. """ return [k for k, v in self._headers] def values(self): """Return a list of all header values. These will be sorted in the order they appeared in the original header list, or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. """ return [v for k, v in self._headers] def items(self): """Get all the header fields and values. These will be sorted in the order they were in the original header list, or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. """ return self._headers[:] def __repr__(self): return "Headers(%s)" % `self._headers` def __str__(self): """str() returns the formatted headers, complete with end line, suitable for direct HTTP transmission.""" return '\r\n'.join(["%s: %s" % kv for kv in self._headers]+['','']) def setdefault(self,name,value): """Return first matching header value for 'name', or 'value' If there is no header named 'name', add a new header with name 'name' and value 'value'.""" result = self.get(name) if result is None: self._headers.append((name,value)) return value else: return result def add_header(self, _name, _value, **_params): """Extended header setting. _name is the header field to add. keyword arguments can be used to set additional parameters for the header field, with underscores converted to dashes. Normally the parameter will be added as key="value" unless value is None, in which case only the key will be added. Example: h.add_header('content-disposition', 'attachment', filename='bud.gif') Note that unlike the corresponding 'email.Message' method, this does *not* handle '(charset, language, value)' tuples: all values must be strings or None. """ parts = [] if _value is not None: parts.append(_value) for k, v in _params.items(): if v is None: parts.append(k.replace('_', '-')) else: parts.append(_formatparam(k.replace('_', '-'), v)) self._headers.append((_name, "; ".join(parts))) def guess_scheme(environ): """Return a guess for whether 'wsgi.url_scheme' should be 'http' or 'https' """ if environ.get("HTTPS") in ('yes','on','1'): return 'https' else: return 'http' _hop_headers = { 'connection':1, 'keep-alive':1, 'proxy-authenticate':1, 'proxy-authorization':1, 'te':1, 'trailers':1, 'transfer-encoding':1, 'upgrade':1 } def is_hop_by_hop(header_name): """Return true if 'header_name' is an HTTP/1.1 "Hop-by-Hop" header""" return header_name.lower() in _hop_headers class ServerHandler(object): """Manage the invocation of a WSGI application""" # Configuration parameters; can override per-subclass or per-instance wsgi_version = (1,0) wsgi_multithread = True wsgi_multiprocess = True wsgi_run_once = False origin_server = True # We are transmitting direct to client http_version = "1.0" # Version that should be used for response server_software = software_version # os_environ is used to supply configuration from the OS environment: # by default it's a copy of 'os.environ' as of import time, but you can # override this in e.g. your __init__ method. os_environ = dict(os.environ.items()) # Collaborator classes wsgi_file_wrapper = FileWrapper # set to None to disable headers_class = Headers # must be a Headers-like class # Error handling (also per-subclass or per-instance) traceback_limit = None # Print entire traceback to self.get_stderr() error_status = "500 INTERNAL SERVER ERROR" error_headers = [('Content-Type','text/plain')] # State variables (don't mess with these) status = result = None headers_sent = False headers = None bytes_sent = 0 def __init__(self, stdin, stdout, stderr, environ, multithread=True, multiprocess=False): self.stdin = stdin self.stdout = stdout self.stderr = stderr self.base_env = environ self.wsgi_multithread = multithread self.wsgi_multiprocess = multiprocess def run(self, application): """Invoke the application""" # Note to self: don't move the close()! Asynchronous servers shouldn't # call close() from finish_response(), so if you close() anywhere but # the double-error branch here, you'll break asynchronous servers by # prematurely closing. Async servers must return from 'run()' without # closing if there might still be output to iterate over. try: self.setup_environ() self.result = application(self.environ, self.start_response) self.finish_response() except: try: self.handle_error() except: # If we get an error handling an error, just give up already! self.close() raise # ...and let the actual server figure it out. def setup_environ(self): """Set up the environment for one request""" env = self.environ = self.os_environ.copy() self.add_cgi_vars() env['wsgi.input'] = self.get_stdin() env['wsgi.errors'] = self.get_stderr() env['wsgi.version'] = self.wsgi_version env['wsgi.run_once'] = self.wsgi_run_once env['wsgi.url_scheme'] = self.get_scheme() env['wsgi.multithread'] = self.wsgi_multithread env['wsgi.multiprocess'] = self.wsgi_multiprocess if self.wsgi_file_wrapper is not None: env['wsgi.file_wrapper'] = self.wsgi_file_wrapper if self.origin_server and self.server_software: env.setdefault('SERVER_SOFTWARE',self.server_software) def finish_response(self): """ Send any iterable data, then close self and the iterable Subclasses intended for use in asynchronous servers will want to redefine this method, such that it sets up callbacks in the event loop to iterate over the data, and to call 'self.close()' once the response is finished. """ if not self.result_is_file() or not self.sendfile(): for data in self.result: self.write(data) self.finish_content() self.close() def get_scheme(self): """Return the URL scheme being used""" return guess_scheme(self.environ) def set_content_length(self): """Compute Content-Length or switch to chunked encoding if possible""" try: blocks = len(self.result) except (TypeError, AttributeError, NotImplementedError): pass else: if blocks==1: self.headers['Content-Length'] = str(self.bytes_sent) return # XXX Try for chunked encoding if origin server and client is 1.1 def cleanup_headers(self): """Make any necessary header changes or defaults Subclasses can extend this to add other defaults. """ if 'Content-Length' not in self.headers: self.set_content_length() def start_response(self, status, headers,exc_info=None): """'start_response()' callable as specified by PEP 333""" if exc_info: try: if self.headers_sent: # Re-raise original exception if headers sent raise exc_info[0], exc_info[1], exc_info[2] finally: exc_info = None # avoid dangling circular ref elif self.headers is not None: raise AssertionError("Headers already set!") assert isinstance(status, str),"Status must be a string" assert len(status)>=4,"Status must be at least 4 characters" assert int(status[:3]),"Status message must begin w/3-digit code" assert status[3]==" ", "Status message must have a space after code" if __debug__: for name,val in headers: assert isinstance(name, str),"Header names must be strings" assert isinstance(val, str),"Header values must be strings" assert not is_hop_by_hop(name),"Hop-by-hop headers not allowed" self.status = status self.headers = self.headers_class(headers) return self.write def send_preamble(self): """Transmit version/status/date/server, via self._write()""" if self.origin_server: if self.client_is_modern(): self._write('HTTP/%s %s\r\n' % (self.http_version,self.status)) if 'Date' not in self.headers: self._write( 'Date: %s\r\n' % http_date() ) if self.server_software and 'Server' not in self.headers: self._write('Server: %s\r\n' % self.server_software) else: self._write('Status: %s\r\n' % self.status) def write(self, data): """'write()' callable as specified by PEP 333""" assert isinstance(data, str), "write() argument must be string" if not self.status: raise AssertionError("write() before start_response()") elif not self.headers_sent: # Before the first output, send the stored headers self.bytes_sent = len(data) # make sure we know content-length self.send_headers() else: self.bytes_sent += len(data) # XXX check Content-Length and truncate if too many bytes written? # If data is too large, socket will choke, so write chunks no larger # than 32MB at a time. length = len(data) if length > 33554432: offset = 0 while offset < length: chunk_size = min(33554432, length) self._write(data[offset:offset+chunk_size]) self._flush() offset += chunk_size else: self._write(data) self._flush() def sendfile(self): """Platform-specific file transmission Override this method in subclasses to support platform-specific file transmission. It is only called if the application's return iterable ('self.result') is an instance of 'self.wsgi_file_wrapper'. This method should return a true value if it was able to actually transmit the wrapped file-like object using a platform-specific approach. It should return a false value if normal iteration should be used instead. An exception can be raised to indicate that transmission was attempted, but failed. NOTE: this method should call 'self.send_headers()' if 'self.headers_sent' is false and it is going to attempt direct transmission of the file1. """ return False # No platform-specific transmission by default def finish_content(self): """Ensure headers and content have both been sent""" if not self.headers_sent: self.headers['Content-Length'] = "0" self.send_headers() else: pass # XXX check if content-length was too short? def close(self): try: self.request_handler.log_request(self.status.split(' ',1)[0], self.bytes_sent) finally: try: if hasattr(self.result,'close'): self.result.close() finally: self.result = self.headers = self.status = self.environ = None self.bytes_sent = 0; self.headers_sent = False def send_headers(self): """Transmit headers to the client, via self._write()""" self.cleanup_headers() self.headers_sent = True if not self.origin_server or self.client_is_modern(): self.send_preamble() self._write(str(self.headers)) def result_is_file(self): """True if 'self.result' is an instance of 'self.wsgi_file_wrapper'""" wrapper = self.wsgi_file_wrapper return wrapper is not None and isinstance(self.result,wrapper) def client_is_modern(self): """True if client can accept status and headers""" return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9' def log_exception(self,exc_info): """Log the 'exc_info' tuple in the server log Subclasses may override to retarget the output or change its format. """ try: from traceback import print_exception stderr = self.get_stderr() print_exception( exc_info[0], exc_info[1], exc_info[2], self.traceback_limit, stderr ) stderr.flush() finally: exc_info = None def handle_error(self): """Log current error, and send error output to client if possible""" self.log_exception(sys.exc_info()) if not self.headers_sent: self.result = self.error_output(self.environ, self.start_response) self.finish_response() # XXX else: attempt advanced recovery techniques for HTML or text? def error_output(self, environ, start_response): import traceback start_response(self.error_status, self.error_headers[:], sys.exc_info()) return ['\n'.join(traceback.format_exception(*sys.exc_info()))] # Pure abstract methods; *must* be overridden in subclasses def _write(self,data): self.stdout.write(data) self._write = self.stdout.write def _flush(self): self.stdout.flush() self._flush = self.stdout.flush def get_stdin(self): return self.stdin def get_stderr(self): return self.stderr def add_cgi_vars(self): self.environ.update(self.base_env) class WSGIServer(HTTPServer): """BaseHTTPServer that implements the Python WSGI protocol""" application = None def __init__(self, *args, **kwargs): if kwargs.pop('ipv6', False): self.address_family = socket.AF_INET6 HTTPServer.__init__(self, *args, **kwargs) def server_bind(self): """Override server_bind to store the server name.""" try: HTTPServer.server_bind(self) except Exception, e: raise WSGIServerException(e) self.setup_environ() def setup_environ(self): # Set up base environment env = self.base_environ = {} env['SERVER_NAME'] = self.server_name env['GATEWAY_INTERFACE'] = 'CGI/1.1' env['SERVER_PORT'] = str(self.server_port) env['REMOTE_HOST']='' env['CONTENT_LENGTH']='' env['SCRIPT_NAME'] = '' def get_app(self): return self.application def set_app(self,application): self.application = application class WSGIRequestHandler(BaseHTTPRequestHandler): server_version = "WSGIServer/" + __version__ def __init__(self, *args, **kwargs): from django.conf import settings self.admin_media_prefix = settings.ADMIN_MEDIA_PREFIX # We set self.path to avoid crashes in log_message() on unsupported # requests (like "OPTIONS"). self.path = '' self.style = color_style() BaseHTTPRequestHandler.__init__(self, *args, **kwargs) def get_environ(self): env = self.server.base_environ.copy() env['SERVER_PROTOCOL'] = self.request_version env['REQUEST_METHOD'] = self.command if '?' in self.path: path,query = self.path.split('?',1) else: path,query = self.path,'' env['PATH_INFO'] = urllib.unquote(path) env['QUERY_STRING'] = query env['REMOTE_ADDR'] = self.client_address[0] if self.headers.typeheader is None: env['CONTENT_TYPE'] = self.headers.type else: env['CONTENT_TYPE'] = self.headers.typeheader length = self.headers.getheader('content-length') if length: env['CONTENT_LENGTH'] = length for h in self.headers.headers: k,v = h.split(':',1) k=k.replace('-','_').upper(); v=v.strip() if k in env: continue # skip content length, type,etc. if 'HTTP_'+k in env: env['HTTP_'+k] += ','+v # comma-separate multiple headers else: env['HTTP_'+k] = v return env def get_stderr(self): return sys.stderr def handle(self): """Handle a single HTTP request""" self.raw_requestline = self.rfile.readline() if not self.parse_request(): # An error code has been sent, just exit return handler = ServerHandler(self.rfile, self.wfile, self.get_stderr(), self.get_environ()) handler.request_handler = self # backpointer for logging handler.run(self.server.get_app()) def log_message(self, format, *args): # Don't bother logging requests for admin images or the favicon. if self.path.startswith(self.admin_media_prefix) or self.path == '/favicon.ico': return msg = "[%s] %s\n" % (self.log_date_time_string(), format % args) # Utilize terminal colors, if available if args[1][0] == '2': # Put 2XX first, since it should be the common case msg = self.style.HTTP_SUCCESS(msg) elif args[1][0] == '1': msg = self.style.HTTP_INFO(msg) elif args[1] == '304': msg = self.style.HTTP_NOT_MODIFIED(msg) elif args[1][0] == '3': msg = self.style.HTTP_REDIRECT(msg) elif args[1] == '404': msg = self.style.HTTP_NOT_FOUND(msg) elif args[1][0] == '4': msg = self.style.HTTP_BAD_REQUEST(msg) else: # Any 5XX, or any other response msg = self.style.HTTP_SERVER_ERROR(msg) sys.stderr.write(msg) class AdminMediaHandler(handlers.StaticFilesHandler): """ WSGI middleware that intercepts calls to the admin media directory, as defined by the ADMIN_MEDIA_PREFIX setting, and serves those images. Use this ONLY LOCALLY, for development! This hasn't been tested for security and is not super efficient. This is pending for deprecation since 1.3. """ def get_base_dir(self): import django return os.path.join(django.__path__[0], 'contrib', 'admin', 'media') def get_base_url(self): from django.conf import settings from django.core.exceptions import ImproperlyConfigured if not settings.ADMIN_MEDIA_PREFIX: raise ImproperlyConfigured( "The ADMIN_MEDIA_PREFIX setting can't be empty " "when using the AdminMediaHandler, e.g. with runserver.") return settings.ADMIN_MEDIA_PREFIX def file_path(self, url): """ Returns the path to the media file on disk for the given URL. The passed URL is assumed to begin with ``self.base_url``. If the resulting file path is outside the media directory, then a ValueError is raised. """ relative_url = url[len(self.base_url[2]):] relative_path = urllib.url2pathname(relative_url) return safe_join(self.base_dir, relative_path) def serve(self, request): document_root, path = os.path.split(self.file_path(request.path)) return static.serve(request, path, document_root=document_root) def _should_handle(self, path): """ Checks if the path should be handled. Ignores the path if: * the host is provided as part of the base_url * the request's path isn't under the base path """ return path.startswith(self.base_url[2]) and not self.base_url[1] def run(addr, port, wsgi_handler, ipv6=False): server_address = (addr, port) httpd = WSGIServer(server_address, WSGIRequestHandler, ipv6=ipv6) httpd.set_app(wsgi_handler) httpd.serve_forever()
25,156
Python
.py
570
35.087719
94
0.619256
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,848
fastcgi.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/servers/fastcgi.py
""" FastCGI (or SCGI, or AJP1.3 ...) server that implements the WSGI protocol. Uses the flup python package: http://www.saddi.com/software/flup/ This is a adaptation of the flup package to add FastCGI server support to run Django apps from Web servers that support the FastCGI protocol. This module can be run standalone or from the django-admin / manage.py scripts using the "runfcgi" directive. Run with the extra option "help" for a list of additional options you can pass to this server. """ from django.utils import importlib import sys, os __version__ = "0.1" __all__ = ["runfastcgi"] FASTCGI_HELP = r""" Run this project as a fastcgi (or some other protocol supported by flup) application. To do this, the flup package from http://www.saddi.com/software/flup/ is required. runfcgi [options] [fcgi settings] Optional Fcgi settings: (setting=value) protocol=PROTOCOL fcgi, scgi, ajp, ... (default fcgi) host=HOSTNAME hostname to listen on. port=PORTNUM port to listen on. socket=FILE UNIX socket to listen on. method=IMPL prefork or threaded (default prefork). maxrequests=NUMBER number of requests a child handles before it is killed and a new child is forked (0 = no limit). maxspare=NUMBER max number of spare processes / threads. minspare=NUMBER min number of spare processes / threads. maxchildren=NUMBER hard limit number of processes / threads. daemonize=BOOL whether to detach from terminal. pidfile=FILE write the spawned process-id to this file. workdir=DIRECTORY change to this directory when daemonizing. debug=BOOL set to true to enable flup tracebacks. outlog=FILE write stdout to this file. errlog=FILE write stderr to this file. umask=UMASK umask to use when daemonizing, in octal notation (default 022). Examples: Run a "standard" fastcgi process on a file-descriptor (for Web servers which spawn your processes for you) $ manage.py runfcgi method=threaded Run a scgi server on a TCP host/port $ manage.py runfcgi protocol=scgi method=prefork host=127.0.0.1 port=8025 Run a fastcgi server on a UNIX domain socket (posix platforms only) $ manage.py runfcgi method=prefork socket=/tmp/fcgi.sock Run a fastCGI as a daemon and write the spawned PID in a file $ manage.py runfcgi socket=/tmp/fcgi.sock method=prefork \ daemonize=true pidfile=/var/run/django-fcgi.pid """ FASTCGI_OPTIONS = { 'protocol': 'fcgi', 'host': None, 'port': None, 'socket': None, 'method': 'fork', 'daemonize': None, 'workdir': '/', 'pidfile': None, 'maxspare': 5, 'minspare': 2, 'maxchildren': 50, 'maxrequests': 0, 'debug': None, 'outlog': None, 'errlog': None, 'umask': None, } def fastcgi_help(message=None): print FASTCGI_HELP if message: print message return False def runfastcgi(argset=[], **kwargs): options = FASTCGI_OPTIONS.copy() options.update(kwargs) for x in argset: if "=" in x: k, v = x.split('=', 1) else: k, v = x, True options[k.lower()] = v if "help" in options: return fastcgi_help() try: import flup except ImportError, e: print >> sys.stderr, "ERROR: %s" % e print >> sys.stderr, " Unable to load the flup package. In order to run django" print >> sys.stderr, " as a FastCGI application, you will need to get flup from" print >> sys.stderr, " http://www.saddi.com/software/flup/ If you've already" print >> sys.stderr, " installed flup, then make sure you have it in your PYTHONPATH." return False flup_module = 'server.' + options['protocol'] if options['method'] in ('prefork', 'fork'): wsgi_opts = { 'maxSpare': int(options["maxspare"]), 'minSpare': int(options["minspare"]), 'maxChildren': int(options["maxchildren"]), 'maxRequests': int(options["maxrequests"]), } flup_module += '_fork' elif options['method'] in ('thread', 'threaded'): wsgi_opts = { 'maxSpare': int(options["maxspare"]), 'minSpare': int(options["minspare"]), 'maxThreads': int(options["maxchildren"]), } else: return fastcgi_help("ERROR: Implementation must be one of prefork or thread.") wsgi_opts['debug'] = options['debug'] is not None try: module = importlib.import_module('.%s' % flup_module, 'flup') WSGIServer = module.WSGIServer except: print "Can't import flup." + flup_module return False # Prep up and go from django.core.handlers.wsgi import WSGIHandler if options["host"] and options["port"] and not options["socket"]: wsgi_opts['bindAddress'] = (options["host"], int(options["port"])) elif options["socket"] and not options["host"] and not options["port"]: wsgi_opts['bindAddress'] = options["socket"] elif not options["socket"] and not options["host"] and not options["port"]: wsgi_opts['bindAddress'] = None else: return fastcgi_help("Invalid combination of host, port, socket.") if options["daemonize"] is None: # Default to daemonizing if we're running on a socket/named pipe. daemonize = (wsgi_opts['bindAddress'] is not None) else: if options["daemonize"].lower() in ('true', 'yes', 't'): daemonize = True elif options["daemonize"].lower() in ('false', 'no', 'f'): daemonize = False else: return fastcgi_help("ERROR: Invalid option for daemonize parameter.") daemon_kwargs = {} if options['outlog']: daemon_kwargs['out_log'] = options['outlog'] if options['errlog']: daemon_kwargs['err_log'] = options['errlog'] if options['umask']: daemon_kwargs['umask'] = int(options['umask'], 8) if daemonize: from django.utils.daemonize import become_daemon become_daemon(our_home_dir=options["workdir"], **daemon_kwargs) if options["pidfile"]: fp = open(options["pidfile"], "w") fp.write("%d\n" % os.getpid()) fp.close() WSGIServer(WSGIHandler(), **wsgi_opts).run() if __name__ == '__main__': runfastcgi(sys.argv[1:])
6,402
Python
.py
153
35.771242
95
0.646567
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,849
context.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/template/context.py
from copy import copy from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module from django.http import HttpRequest # Cache of actual callables. _standard_context_processors = None # We need the CSRF processor no matter what the user has in their settings, # because otherwise it is a security vulnerability, and we can't afford to leave # this to human error or failure to read migration instructions. _builtin_context_processors = ('django.core.context_processors.csrf',) class ContextPopException(Exception): "pop() has been called more times than push()" pass class EmptyClass(object): # No-op class which takes no args to its __init__ method, to help implement # __copy__ pass class BaseContext(object): def __init__(self, dict_=None): dict_ = dict_ or {} self.dicts = [dict_] def __copy__(self): duplicate = EmptyClass() duplicate.__class__ = self.__class__ duplicate.__dict__ = self.__dict__.copy() duplicate.dicts = duplicate.dicts[:] return duplicate def __repr__(self): return repr(self.dicts) def __iter__(self): for d in reversed(self.dicts): yield d def push(self): d = {} self.dicts.append(d) return d def pop(self): if len(self.dicts) == 1: raise ContextPopException return self.dicts.pop() def __setitem__(self, key, value): "Set a variable in the current context" self.dicts[-1][key] = value def __getitem__(self, key): "Get a variable's value, starting at the current context and going upward" for d in reversed(self.dicts): if key in d: return d[key] raise KeyError(key) def __delitem__(self, key): "Delete a variable from the current context" del self.dicts[-1][key] def has_key(self, key): for d in self.dicts: if key in d: return True return False def __contains__(self, key): return self.has_key(key) def get(self, key, otherwise=None): for d in reversed(self.dicts): if key in d: return d[key] return otherwise class Context(BaseContext): "A stack container for variable context" def __init__(self, dict_=None, autoescape=True, current_app=None, use_l10n=None): self.autoescape = autoescape self.use_l10n = use_l10n self.current_app = current_app self.render_context = RenderContext() super(Context, self).__init__(dict_) def __copy__(self): duplicate = super(Context, self).__copy__() duplicate.render_context = copy(self.render_context) return duplicate def update(self, other_dict): "Pushes other_dict to the stack of dictionaries in the Context" if not hasattr(other_dict, '__getitem__'): raise TypeError('other_dict must be a mapping (dictionary-like) object.') self.dicts.append(other_dict) return other_dict def new(self, values=None): """ Returns a new Context with the same 'autoescape' value etc, but with only the values given in 'values' stored. """ return self.__class__(dict_=values, autoescape=self.autoescape, current_app=self.current_app, use_l10n=self.use_l10n) class RenderContext(BaseContext): """ A stack container for storing Template state. RenderContext simplifies the implementation of template Nodes by providing a safe place to store state between invocations of a node's `render` method. The RenderContext also provides scoping rules that are more sensible for 'template local' variables. The render context stack is pushed before each template is rendered, creating a fresh scope with nothing in it. Name resolution fails if a variable is not found at the top of the RequestContext stack. Thus, variables are local to a specific template and don't affect the rendering of other templates as they would if they were stored in the normal template context. """ def __iter__(self): for d in self.dicts[-1]: yield d def has_key(self, key): return key in self.dicts[-1] def get(self, key, otherwise=None): d = self.dicts[-1] if key in d: return d[key] return otherwise # This is a function rather than module-level procedural code because we only # want it to execute if somebody uses RequestContext. def get_standard_processors(): from django.conf import settings global _standard_context_processors if _standard_context_processors is None: processors = [] collect = [] collect.extend(_builtin_context_processors) collect.extend(settings.TEMPLATE_CONTEXT_PROCESSORS) for path in collect: i = path.rfind('.') module, attr = path[:i], path[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error importing request processor module %s: "%s"' % (module, e)) try: func = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a "%s" callable request processor' % (module, attr)) processors.append(func) _standard_context_processors = tuple(processors) return _standard_context_processors class RequestContext(Context): """ This subclass of template.Context automatically populates itself using the processors defined in TEMPLATE_CONTEXT_PROCESSORS. Additional processors can be specified as a list of callables using the "processors" keyword argument. """ def __init__(self, request, dict=None, processors=None, current_app=None, use_l10n=None): Context.__init__(self, dict, current_app=current_app, use_l10n=use_l10n) if processors is None: processors = () else: processors = tuple(processors) for processor in get_standard_processors() + processors: self.update(processor(request))
6,298
Python
.py
151
33.821192
124
0.651037
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,850
defaulttags.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/template/defaulttags.py
"""Default tags used by the template system, available to all templates.""" import sys import re from itertools import groupby, cycle as itertools_cycle from django.template.base import Node, NodeList, Template, Context, Variable from django.template.base import TemplateSyntaxError, VariableDoesNotExist, BLOCK_TAG_START, BLOCK_TAG_END, VARIABLE_TAG_START, VARIABLE_TAG_END, SINGLE_BRACE_START, SINGLE_BRACE_END, COMMENT_TAG_START, COMMENT_TAG_END from django.template.base import get_library, Library, InvalidTemplateLibrary from django.template.smartif import IfParser, Literal from django.conf import settings from django.utils.encoding import smart_str, smart_unicode from django.utils.safestring import mark_safe register = Library() # Regex for token keyword arguments kwarg_re = re.compile(r"(?:(\w+)=)?(.+)") def token_kwargs(bits, parser, support_legacy=False): """ A utility method for parsing token keyword arguments. :param bits: A list containing remainder of the token (split by spaces) that is to be checked for arguments. Valid arguments will be removed from this list. :param support_legacy: If set to true ``True``, the legacy format ``1 as foo`` will be accepted. Otherwise, only the standard ``foo=1`` format is allowed. :returns: A dictionary of the arguments retrieved from the ``bits`` token list. There is no requirement for all remaining token ``bits`` to be keyword arguments, so the dictionary will be returned as soon as an invalid argument format is reached. """ if not bits: return {} match = kwarg_re.match(bits[0]) kwarg_format = match and match.group(1) if not kwarg_format: if not support_legacy: return {} if len(bits) < 3 or bits[1] != 'as': return {} kwargs = {} while bits: if kwarg_format: match = kwarg_re.match(bits[0]) if not match or not match.group(1): return kwargs key, value = match.groups() del bits[:1] else: if len(bits) < 3 or bits[1] != 'as': return kwargs key, value = bits[2], bits[0] del bits[:3] kwargs[key] = parser.compile_filter(value) if bits and not kwarg_format: if bits[0] != 'and': return kwargs del bits[:1] return kwargs class AutoEscapeControlNode(Node): """Implements the actions of the autoescape tag.""" def __init__(self, setting, nodelist): self.setting, self.nodelist = setting, nodelist def render(self, context): old_setting = context.autoescape context.autoescape = self.setting output = self.nodelist.render(context) context.autoescape = old_setting if self.setting: return mark_safe(output) else: return output class CommentNode(Node): def render(self, context): return '' class CsrfTokenNode(Node): def render(self, context): csrf_token = context.get('csrf_token', None) if csrf_token: if csrf_token == 'NOTPROVIDED': return mark_safe(u"") else: return mark_safe(u"<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='%s' /></div>" % csrf_token) else: # It's very probable that the token is missing because of # misconfiguration, so we raise a warning from django.conf import settings if settings.DEBUG: import warnings warnings.warn("A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.") return u'' class CycleNode(Node): def __init__(self, cyclevars, variable_name=None, silent=False): self.cyclevars = cyclevars self.variable_name = variable_name self.silent = silent def render(self, context): if self not in context.render_context: # First time the node is rendered in template context.render_context[self] = itertools_cycle(self.cyclevars) cycle_iter = context.render_context[self] value = cycle_iter.next().resolve(context) if self.variable_name: context[self.variable_name] = value if self.silent: return '' return value class DebugNode(Node): def render(self, context): from pprint import pformat output = [pformat(val) for val in context] output.append('\n\n') output.append(pformat(sys.modules)) return ''.join(output) class FilterNode(Node): def __init__(self, filter_expr, nodelist): self.filter_expr, self.nodelist = filter_expr, nodelist def render(self, context): output = self.nodelist.render(context) # Apply filters. context.update({'var': output}) filtered = self.filter_expr.resolve(context) context.pop() return filtered class FirstOfNode(Node): def __init__(self, vars): self.vars = vars def render(self, context): for var in self.vars: value = var.resolve(context, True) if value: return smart_unicode(value) return u'' class ForNode(Node): child_nodelists = ('nodelist_loop', 'nodelist_empty') def __init__(self, loopvars, sequence, is_reversed, nodelist_loop, nodelist_empty=None): self.loopvars, self.sequence = loopvars, sequence self.is_reversed = is_reversed self.nodelist_loop = nodelist_loop if nodelist_empty is None: self.nodelist_empty = NodeList() else: self.nodelist_empty = nodelist_empty def __repr__(self): reversed_text = self.is_reversed and ' reversed' or '' return "<For Node: for %s in %s, tail_len: %d%s>" % \ (', '.join(self.loopvars), self.sequence, len(self.nodelist_loop), reversed_text) def __iter__(self): for node in self.nodelist_loop: yield node for node in self.nodelist_empty: yield node def render(self, context): if 'forloop' in context: parentloop = context['forloop'] else: parentloop = {} context.push() try: values = self.sequence.resolve(context, True) except VariableDoesNotExist: values = [] if values is None: values = [] if not hasattr(values, '__len__'): values = list(values) len_values = len(values) if len_values < 1: context.pop() return self.nodelist_empty.render(context) nodelist = NodeList() if self.is_reversed: values = reversed(values) unpack = len(self.loopvars) > 1 # Create a forloop value in the context. We'll update counters on each # iteration just below. loop_dict = context['forloop'] = {'parentloop': parentloop} for i, item in enumerate(values): # Shortcuts for current loop iteration number. loop_dict['counter0'] = i loop_dict['counter'] = i+1 # Reverse counter iteration numbers. loop_dict['revcounter'] = len_values - i loop_dict['revcounter0'] = len_values - i - 1 # Boolean values designating first and last times through loop. loop_dict['first'] = (i == 0) loop_dict['last'] = (i == len_values - 1) pop_context = False if unpack: # If there are multiple loop variables, unpack the item into # them. try: unpacked_vars = dict(zip(self.loopvars, item)) except TypeError: pass else: pop_context = True context.update(unpacked_vars) else: context[self.loopvars[0]] = item for node in self.nodelist_loop: nodelist.append(node.render(context)) if pop_context: # The loop variables were pushed on to the context so pop them # off again. This is necessary because the tag lets the length # of loopvars differ to the length of each set of items and we # don't want to leave any vars from the previous loop on the # context. context.pop() context.pop() return nodelist.render(context) class IfChangedNode(Node): child_nodelists = ('nodelist_true', 'nodelist_false') def __init__(self, nodelist_true, nodelist_false, *varlist): self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false self._last_seen = None self._varlist = varlist self._id = str(id(self)) def render(self, context): if 'forloop' in context and self._id not in context['forloop']: self._last_seen = None context['forloop'][self._id] = 1 try: if self._varlist: # Consider multiple parameters. This automatically behaves # like an OR evaluation of the multiple variables. compare_to = [var.resolve(context, True) for var in self._varlist] else: compare_to = self.nodelist_true.render(context) except VariableDoesNotExist: compare_to = None if compare_to != self._last_seen: firstloop = (self._last_seen == None) self._last_seen = compare_to content = self.nodelist_true.render(context) return content elif self.nodelist_false: return self.nodelist_false.render(context) return '' class IfEqualNode(Node): child_nodelists = ('nodelist_true', 'nodelist_false') def __init__(self, var1, var2, nodelist_true, nodelist_false, negate): self.var1, self.var2 = var1, var2 self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false self.negate = negate def __repr__(self): return "<IfEqualNode>" def render(self, context): val1 = self.var1.resolve(context, True) val2 = self.var2.resolve(context, True) if (self.negate and val1 != val2) or (not self.negate and val1 == val2): return self.nodelist_true.render(context) return self.nodelist_false.render(context) class IfNode(Node): child_nodelists = ('nodelist_true', 'nodelist_false') def __init__(self, var, nodelist_true, nodelist_false=None): self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false self.var = var def __repr__(self): return "<If node>" def __iter__(self): for node in self.nodelist_true: yield node for node in self.nodelist_false: yield node def render(self, context): try: var = self.var.eval(context) except VariableDoesNotExist: var = None if var: return self.nodelist_true.render(context) else: return self.nodelist_false.render(context) class RegroupNode(Node): def __init__(self, target, expression, var_name): self.target, self.expression = target, expression self.var_name = var_name def render(self, context): obj_list = self.target.resolve(context, True) if obj_list == None: # target variable wasn't found in context; fail silently. context[self.var_name] = [] return '' # List of dictionaries in the format: # {'grouper': 'key', 'list': [list of contents]}. context[self.var_name] = [ {'grouper': key, 'list': list(val)} for key, val in groupby(obj_list, lambda v, f=self.expression.resolve: f(v, True)) ] return '' def include_is_allowed(filepath): for root in settings.ALLOWED_INCLUDE_ROOTS: if filepath.startswith(root): return True return False class SsiNode(Node): def __init__(self, filepath, parsed, legacy_filepath=True): self.filepath = filepath self.parsed = parsed self.legacy_filepath = legacy_filepath def render(self, context): filepath = self.filepath if not self.legacy_filepath: filepath = filepath.resolve(context) if not include_is_allowed(filepath): if settings.DEBUG: return "[Didn't have permission to include file]" else: return '' # Fail silently for invalid includes. try: fp = open(filepath, 'r') output = fp.read() fp.close() except IOError: output = '' if self.parsed: try: t = Template(output, name=filepath) return t.render(context) except TemplateSyntaxError, e: if settings.DEBUG: return "[Included template had syntax error: %s]" % e else: return '' # Fail silently for invalid included templates. return output class LoadNode(Node): def render(self, context): return '' class NowNode(Node): def __init__(self, format_string): self.format_string = format_string def render(self, context): from datetime import datetime from django.utils.dateformat import DateFormat df = DateFormat(datetime.now()) return df.format(self.format_string) class SpacelessNode(Node): def __init__(self, nodelist): self.nodelist = nodelist def render(self, context): from django.utils.html import strip_spaces_between_tags return strip_spaces_between_tags(self.nodelist.render(context).strip()) class TemplateTagNode(Node): mapping = {'openblock': BLOCK_TAG_START, 'closeblock': BLOCK_TAG_END, 'openvariable': VARIABLE_TAG_START, 'closevariable': VARIABLE_TAG_END, 'openbrace': SINGLE_BRACE_START, 'closebrace': SINGLE_BRACE_END, 'opencomment': COMMENT_TAG_START, 'closecomment': COMMENT_TAG_END, } def __init__(self, tagtype): self.tagtype = tagtype def render(self, context): return self.mapping.get(self.tagtype, '') class URLNode(Node): def __init__(self, view_name, args, kwargs, asvar, legacy_view_name=True): self.view_name = view_name self.legacy_view_name = legacy_view_name self.args = args self.kwargs = kwargs self.asvar = asvar def render(self, context): from django.core.urlresolvers import reverse, NoReverseMatch args = [arg.resolve(context) for arg in self.args] kwargs = dict([(smart_str(k, 'ascii'), v.resolve(context)) for k, v in self.kwargs.items()]) view_name = self.view_name if not self.legacy_view_name: view_name = view_name.resolve(context) # Try to look up the URL twice: once given the view name, and again # relative to what we guess is the "main" app. If they both fail, # re-raise the NoReverseMatch unless we're using the # {% url ... as var %} construct in which cause return nothing. url = '' try: url = reverse(view_name, args=args, kwargs=kwargs, current_app=context.current_app) except NoReverseMatch, e: if settings.SETTINGS_MODULE: project_name = settings.SETTINGS_MODULE.split('.')[0] try: url = reverse(project_name + '.' + view_name, args=args, kwargs=kwargs, current_app=context.current_app) except NoReverseMatch: if self.asvar is None: # Re-raise the original exception, not the one with # the path relative to the project. This makes a # better error message. raise e else: if self.asvar is None: raise e if self.asvar: context[self.asvar] = url return '' else: return url class WidthRatioNode(Node): def __init__(self, val_expr, max_expr, max_width): self.val_expr = val_expr self.max_expr = max_expr self.max_width = max_width def render(self, context): try: value = self.val_expr.resolve(context) maxvalue = self.max_expr.resolve(context) max_width = int(self.max_width.resolve(context)) except VariableDoesNotExist: return '' except ValueError: raise TemplateSyntaxError("widthratio final argument must be an number") try: value = float(value) maxvalue = float(maxvalue) ratio = (value / maxvalue) * max_width except (ValueError, ZeroDivisionError): return '' return str(int(round(ratio))) class WithNode(Node): def __init__(self, var, name, nodelist, extra_context=None): self.nodelist = nodelist # var and name are legacy attributes, being left in case they are used # by third-party subclasses of this Node. self.extra_context = extra_context or {} if name: self.extra_context[name] = var def __repr__(self): return "<WithNode>" def render(self, context): values = dict([(key, val.resolve(context)) for key, val in self.extra_context.iteritems()]) context.update(values) output = self.nodelist.render(context) context.pop() return output #@register.tag def autoescape(parser, token): """ Force autoescape behaviour for this block. """ args = token.contents.split() if len(args) != 2: raise TemplateSyntaxError("'autoescape' tag requires exactly one argument.") arg = args[1] if arg not in (u'on', u'off'): raise TemplateSyntaxError("'autoescape' argument should be 'on' or 'off'") nodelist = parser.parse(('endautoescape',)) parser.delete_first_token() return AutoEscapeControlNode((arg == 'on'), nodelist) autoescape = register.tag(autoescape) #@register.tag def comment(parser, token): """ Ignores everything between ``{% comment %}`` and ``{% endcomment %}``. """ parser.skip_past('endcomment') return CommentNode() comment = register.tag(comment) #@register.tag def cycle(parser, token): """ Cycles among the given strings each time this tag is encountered. Within a loop, cycles among the given strings each time through the loop:: {% for o in some_list %} <tr class="{% cycle 'row1' 'row2' %}"> ... </tr> {% endfor %} Outside of a loop, give the values a unique name the first time you call it, then use that name each sucessive time through:: <tr class="{% cycle 'row1' 'row2' 'row3' as rowcolors %}">...</tr> <tr class="{% cycle rowcolors %}">...</tr> <tr class="{% cycle rowcolors %}">...</tr> You can use any number of values, separated by spaces. Commas can also be used to separate values; if a comma is used, the cycle values are interpreted as literal strings. The optional flag "silent" can be used to prevent the cycle declaration from returning any value:: {% cycle 'row1' 'row2' as rowcolors silent %}{# no value here #} {% for o in some_list %} <tr class="{% cycle rowcolors %}">{# first value will be "row1" #} ... </tr> {% endfor %} """ # Note: This returns the exact same node on each {% cycle name %} call; # that is, the node object returned from {% cycle a b c as name %} and the # one returned from {% cycle name %} are the exact same object. This # shouldn't cause problems (heh), but if it does, now you know. # # Ugly hack warning: This stuffs the named template dict into parser so # that names are only unique within each template (as opposed to using # a global variable, which would make cycle names have to be unique across # *all* templates. args = token.split_contents() if len(args) < 2: raise TemplateSyntaxError("'cycle' tag requires at least two arguments") if ',' in args[1]: # Backwards compatibility: {% cycle a,b %} or {% cycle a,b as foo %} # case. args[1:2] = ['"%s"' % arg for arg in args[1].split(",")] if len(args) == 2: # {% cycle foo %} case. name = args[1] if not hasattr(parser, '_namedCycleNodes'): raise TemplateSyntaxError("No named cycles in template. '%s' is not defined" % name) if not name in parser._namedCycleNodes: raise TemplateSyntaxError("Named cycle '%s' does not exist" % name) return parser._namedCycleNodes[name] as_form = False if len(args) > 4: # {% cycle ... as foo [silent] %} case. if args[-3] == "as": if args[-1] != "silent": raise TemplateSyntaxError("Only 'silent' flag is allowed after cycle's name, not '%s'." % args[-1]) as_form = True silent = True args = args[:-1] elif args[-2] == "as": as_form = True silent = False if as_form: name = args[-1] values = [parser.compile_filter(arg) for arg in args[1:-2]] node = CycleNode(values, name, silent=silent) if not hasattr(parser, '_namedCycleNodes'): parser._namedCycleNodes = {} parser._namedCycleNodes[name] = node else: values = [parser.compile_filter(arg) for arg in args[1:]] node = CycleNode(values) return node cycle = register.tag(cycle) def csrf_token(parser, token): return CsrfTokenNode() register.tag(csrf_token) def debug(parser, token): """ Outputs a whole load of debugging information, including the current context and imported modules. Sample usage:: <pre> {% debug %} </pre> """ return DebugNode() debug = register.tag(debug) #@register.tag(name="filter") def do_filter(parser, token): """ Filters the contents of the block through variable filters. Filters can also be piped through each other, and they can have arguments -- just like in variable syntax. Sample usage:: {% filter force_escape|lower %} This text will be HTML-escaped, and will appear in lowercase. {% endfilter %} """ _, rest = token.contents.split(None, 1) filter_expr = parser.compile_filter("var|%s" % (rest)) for func, unused in filter_expr.filters: if getattr(func, '_decorated_function', func).__name__ in ('escape', 'safe'): raise TemplateSyntaxError('"filter %s" is not permitted. Use the "autoescape" tag instead.' % func.__name__) nodelist = parser.parse(('endfilter',)) parser.delete_first_token() return FilterNode(filter_expr, nodelist) do_filter = register.tag("filter", do_filter) #@register.tag def firstof(parser, token): """ Outputs the first variable passed that is not False, without escaping. Outputs nothing if all the passed variables are False. Sample usage:: {% firstof var1 var2 var3 %} This is equivalent to:: {% if var1 %} {{ var1|safe }} {% else %}{% if var2 %} {{ var2|safe }} {% else %}{% if var3 %} {{ var3|safe }} {% endif %}{% endif %}{% endif %} but obviously much cleaner! You can also use a literal string as a fallback value in case all passed variables are False:: {% firstof var1 var2 var3 "fallback value" %} If you want to escape the output, use a filter tag:: {% filter force_escape %} {% firstof var1 var2 var3 "fallback value" %} {% endfilter %} """ bits = token.split_contents()[1:] if len(bits) < 1: raise TemplateSyntaxError("'firstof' statement requires at least one argument") return FirstOfNode([parser.compile_filter(bit) for bit in bits]) firstof = register.tag(firstof) #@register.tag(name="for") def do_for(parser, token): """ Loops over each item in an array. For example, to display a list of athletes given ``athlete_list``:: <ul> {% for athlete in athlete_list %} <li>{{ athlete.name }}</li> {% endfor %} </ul> You can loop over a list in reverse by using ``{% for obj in list reversed %}``. You can also unpack multiple values from a two-dimensional array:: {% for key,value in dict.items %} {{ key }}: {{ value }} {% endfor %} The ``for`` tag can take an optional ``{% empty %}`` clause that will be displayed if the given array is empty or could not be found:: <ul> {% for athlete in athlete_list %} <li>{{ athlete.name }}</li> {% empty %} <li>Sorry, no athletes in this list.</li> {% endfor %} <ul> The above is equivalent to -- but shorter, cleaner, and possibly faster than -- the following:: <ul> {% if althete_list %} {% for athlete in athlete_list %} <li>{{ athlete.name }}</li> {% endfor %} {% else %} <li>Sorry, no athletes in this list.</li> {% endif %} </ul> The for loop sets a number of variables available within the loop: ========================== ================================================ Variable Description ========================== ================================================ ``forloop.counter`` The current iteration of the loop (1-indexed) ``forloop.counter0`` The current iteration of the loop (0-indexed) ``forloop.revcounter`` The number of iterations from the end of the loop (1-indexed) ``forloop.revcounter0`` The number of iterations from the end of the loop (0-indexed) ``forloop.first`` True if this is the first time through the loop ``forloop.last`` True if this is the last time through the loop ``forloop.parentloop`` For nested loops, this is the loop "above" the current one ========================== ================================================ """ bits = token.contents.split() if len(bits) < 4: raise TemplateSyntaxError("'for' statements should have at least four" " words: %s" % token.contents) is_reversed = bits[-1] == 'reversed' in_index = is_reversed and -3 or -2 if bits[in_index] != 'in': raise TemplateSyntaxError("'for' statements should use the format" " 'for x in y': %s" % token.contents) loopvars = re.split(r' *, *', ' '.join(bits[1:in_index])) for var in loopvars: if not var or ' ' in var: raise TemplateSyntaxError("'for' tag received an invalid argument:" " %s" % token.contents) sequence = parser.compile_filter(bits[in_index+1]) nodelist_loop = parser.parse(('empty', 'endfor',)) token = parser.next_token() if token.contents == 'empty': nodelist_empty = parser.parse(('endfor',)) parser.delete_first_token() else: nodelist_empty = None return ForNode(loopvars, sequence, is_reversed, nodelist_loop, nodelist_empty) do_for = register.tag("for", do_for) def do_ifequal(parser, token, negate): bits = list(token.split_contents()) if len(bits) != 3: raise TemplateSyntaxError("%r takes two arguments" % bits[0]) end_tag = 'end' + bits[0] nodelist_true = parser.parse(('else', end_tag)) token = parser.next_token() if token.contents == 'else': nodelist_false = parser.parse((end_tag,)) parser.delete_first_token() else: nodelist_false = NodeList() val1 = parser.compile_filter(bits[1]) val2 = parser.compile_filter(bits[2]) return IfEqualNode(val1, val2, nodelist_true, nodelist_false, negate) #@register.tag def ifequal(parser, token): """ Outputs the contents of the block if the two arguments equal each other. Examples:: {% ifequal user.id comment.user_id %} ... {% endifequal %} {% ifnotequal user.id comment.user_id %} ... {% else %} ... {% endifnotequal %} """ return do_ifequal(parser, token, False) ifequal = register.tag(ifequal) #@register.tag def ifnotequal(parser, token): """ Outputs the contents of the block if the two arguments are not equal. See ifequal. """ return do_ifequal(parser, token, True) ifnotequal = register.tag(ifnotequal) class TemplateLiteral(Literal): def __init__(self, value, text): self.value = value self.text = text # for better error messages def display(self): return self.text def eval(self, context): return self.value.resolve(context, ignore_failures=True) class TemplateIfParser(IfParser): error_class = TemplateSyntaxError def __init__(self, parser, *args, **kwargs): self.template_parser = parser return super(TemplateIfParser, self).__init__(*args, **kwargs) def create_var(self, value): return TemplateLiteral(self.template_parser.compile_filter(value), value) #@register.tag(name="if") def do_if(parser, token): """ The ``{% if %}`` tag evaluates a variable, and if that variable is "true" (i.e., exists, is not empty, and is not a false boolean value), the contents of the block are output: :: {% if athlete_list %} Number of athletes: {{ athlete_list|count }} {% else %} No athletes. {% endif %} In the above, if ``athlete_list`` is not empty, the number of athletes will be displayed by the ``{{ athlete_list|count }}`` variable. As you can see, the ``if`` tag can take an option ``{% else %}`` clause that will be displayed if the test fails. ``if`` tags may use ``or``, ``and`` or ``not`` to test a number of variables or to negate a given variable:: {% if not athlete_list %} There are no athletes. {% endif %} {% if athlete_list or coach_list %} There are some athletes or some coaches. {% endif %} {% if athlete_list and coach_list %} Both atheletes and coaches are available. {% endif %} {% if not athlete_list or coach_list %} There are no athletes, or there are some coaches. {% endif %} {% if athlete_list and not coach_list %} There are some athletes and absolutely no coaches. {% endif %} Comparison operators are also available, and the use of filters is also allowed, for example:: {% if articles|length >= 5 %}...{% endif %} Arguments and operators _must_ have a space between them, so ``{% if 1>2 %}`` is not a valid if tag. All supported operators are: ``or``, ``and``, ``in``, ``not in`` ``==`` (or ``=``), ``!=``, ``>``, ``>=``, ``<`` and ``<=``. Operator precedence follows Python. """ bits = token.split_contents()[1:] var = TemplateIfParser(parser, bits).parse() nodelist_true = parser.parse(('else', 'endif')) token = parser.next_token() if token.contents == 'else': nodelist_false = parser.parse(('endif',)) parser.delete_first_token() else: nodelist_false = NodeList() return IfNode(var, nodelist_true, nodelist_false) do_if = register.tag("if", do_if) #@register.tag def ifchanged(parser, token): """ Checks if a value has changed from the last iteration of a loop. The 'ifchanged' block tag is used within a loop. It has two possible uses. 1. Checks its own rendered contents against its previous state and only displays the content if it has changed. For example, this displays a list of days, only displaying the month if it changes:: <h1>Archive for {{ year }}</h1> {% for date in days %} {% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %} <a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a> {% endfor %} 2. If given a variable, check whether that variable has changed. For example, the following shows the date every time it changes, but only shows the hour if both the hour and the date have changed:: {% for date in days %} {% ifchanged date.date %} {{ date.date }} {% endifchanged %} {% ifchanged date.hour date.date %} {{ date.hour }} {% endifchanged %} {% endfor %} """ bits = token.contents.split() nodelist_true = parser.parse(('else', 'endifchanged')) token = parser.next_token() if token.contents == 'else': nodelist_false = parser.parse(('endifchanged',)) parser.delete_first_token() else: nodelist_false = NodeList() values = [parser.compile_filter(bit) for bit in bits[1:]] return IfChangedNode(nodelist_true, nodelist_false, *values) ifchanged = register.tag(ifchanged) #@register.tag def ssi(parser, token): """ Outputs the contents of a given file into the page. Like a simple "include" tag, the ``ssi`` tag includes the contents of another file -- which must be specified using an absolute path -- in the current page:: {% ssi /home/html/ljworld.com/includes/right_generic.html %} If the optional "parsed" parameter is given, the contents of the included file are evaluated as template code, with the current context:: {% ssi /home/html/ljworld.com/includes/right_generic.html parsed %} """ import warnings warnings.warn('The syntax for the ssi template tag is changing. Load the `ssi` tag from the `future` tag library to start using the new behavior.', category=PendingDeprecationWarning) bits = token.contents.split() parsed = False if len(bits) not in (2, 3): raise TemplateSyntaxError("'ssi' tag takes one argument: the path to" " the file to be included") if len(bits) == 3: if bits[2] == 'parsed': parsed = True else: raise TemplateSyntaxError("Second (optional) argument to %s tag" " must be 'parsed'" % bits[0]) return SsiNode(bits[1], parsed, legacy_filepath=True) ssi = register.tag(ssi) #@register.tag def load(parser, token): """ Loads a custom template tag set. For example, to load the template tags in ``django/templatetags/news/photos.py``:: {% load news.photos %} Can also be used to load an individual tag/filter from a library:: {% load byline from news %} """ bits = token.contents.split() if len(bits) >= 4 and bits[-2] == "from": try: taglib = bits[-1] lib = get_library(taglib) except InvalidTemplateLibrary, e: raise TemplateSyntaxError("'%s' is not a valid tag library: %s" % (taglib, e)) else: temp_lib = Library() for name in bits[1:-2]: if name in lib.tags: temp_lib.tags[name] = lib.tags[name] # a name could be a tag *and* a filter, so check for both if name in lib.filters: temp_lib.filters[name] = lib.filters[name] elif name in lib.filters: temp_lib.filters[name] = lib.filters[name] else: raise TemplateSyntaxError("'%s' is not a valid tag or filter in tag library '%s'" % (name, taglib)) parser.add_library(temp_lib) else: for taglib in bits[1:]: # add the library to the parser try: lib = get_library(taglib) parser.add_library(lib) except InvalidTemplateLibrary, e: raise TemplateSyntaxError("'%s' is not a valid tag library: %s" % (taglib, e)) return LoadNode() load = register.tag(load) #@register.tag def now(parser, token): """ Displays the date, formatted according to the given string. Uses the same format as PHP's ``date()`` function; see http://php.net/date for all the possible values. Sample usage:: It is {% now "jS F Y H:i" %} """ bits = token.contents.split('"') if len(bits) != 3: raise TemplateSyntaxError("'now' statement takes one argument") format_string = bits[1] return NowNode(format_string) now = register.tag(now) #@register.tag def regroup(parser, token): """ Regroups a list of alike objects by a common attribute. This complex tag is best illustrated by use of an example: say that ``people`` is a list of ``Person`` objects that have ``first_name``, ``last_name``, and ``gender`` attributes, and you'd like to display a list that looks like: * Male: * George Bush * Bill Clinton * Female: * Margaret Thatcher * Colendeeza Rice * Unknown: * Pat Smith The following snippet of template code would accomplish this dubious task:: {% regroup people by gender as grouped %} <ul> {% for group in grouped %} <li>{{ group.grouper }} <ul> {% for item in group.list %} <li>{{ item }}</li> {% endfor %} </ul> {% endfor %} </ul> As you can see, ``{% regroup %}`` populates a variable with a list of objects with ``grouper`` and ``list`` attributes. ``grouper`` contains the item that was grouped by; ``list`` contains the list of objects that share that ``grouper``. In this case, ``grouper`` would be ``Male``, ``Female`` and ``Unknown``, and ``list`` is the list of people with those genders. Note that ``{% regroup %}`` does not work when the list to be grouped is not sorted by the key you are grouping by! This means that if your list of people was not sorted by gender, you'd need to make sure it is sorted before using it, i.e.:: {% regroup people|dictsort:"gender" by gender as grouped %} """ firstbits = token.contents.split(None, 3) if len(firstbits) != 4: raise TemplateSyntaxError("'regroup' tag takes five arguments") target = parser.compile_filter(firstbits[1]) if firstbits[2] != 'by': raise TemplateSyntaxError("second argument to 'regroup' tag must be 'by'") lastbits_reversed = firstbits[3][::-1].split(None, 2) if lastbits_reversed[1][::-1] != 'as': raise TemplateSyntaxError("next-to-last argument to 'regroup' tag must" " be 'as'") expression = parser.compile_filter(lastbits_reversed[2][::-1]) var_name = lastbits_reversed[0][::-1] return RegroupNode(target, expression, var_name) regroup = register.tag(regroup) def spaceless(parser, token): """ Removes whitespace between HTML tags, including tab and newline characters. Example usage:: {% spaceless %} <p> <a href="foo/">Foo</a> </p> {% endspaceless %} This example would return this HTML:: <p><a href="foo/">Foo</a></p> Only space between *tags* is normalized -- not space between tags and text. In this example, the space around ``Hello`` won't be stripped:: {% spaceless %} <strong> Hello </strong> {% endspaceless %} """ nodelist = parser.parse(('endspaceless',)) parser.delete_first_token() return SpacelessNode(nodelist) spaceless = register.tag(spaceless) #@register.tag def templatetag(parser, token): """ Outputs one of the bits used to compose template tags. Since the template system has no concept of "escaping", to display one of the bits used in template tags, you must use the ``{% templatetag %}`` tag. The argument tells which template bit to output: ================== ======= Argument Outputs ================== ======= ``openblock`` ``{%`` ``closeblock`` ``%}`` ``openvariable`` ``{{`` ``closevariable`` ``}}`` ``openbrace`` ``{`` ``closebrace`` ``}`` ``opencomment`` ``{#`` ``closecomment`` ``#}`` ================== ======= """ bits = token.contents.split() if len(bits) != 2: raise TemplateSyntaxError("'templatetag' statement takes one argument") tag = bits[1] if tag not in TemplateTagNode.mapping: raise TemplateSyntaxError("Invalid templatetag argument: '%s'." " Must be one of: %s" % (tag, TemplateTagNode.mapping.keys())) return TemplateTagNode(tag) templatetag = register.tag(templatetag) def url(parser, token): """ Returns an absolute URL matching given view with its parameters. This is a way to define links that aren't tied to a particular URL configuration:: {% url path.to.some_view arg1 arg2 %} or {% url path.to.some_view name1=value1 name2=value2 %} The first argument is a path to a view. It can be an absolute python path or just ``app_name.view_name`` without the project name if the view is located inside the project. Other arguments are comma-separated values that will be filled in place of positional and keyword arguments in the URL. All arguments for the URL should be present. For example if you have a view ``app_name.client`` taking client's id and the corresponding line in a URLconf looks like this:: ('^client/(\d+)/$', 'app_name.client') and this app's URLconf is included into the project's URLconf under some path:: ('^clients/', include('project_name.app_name.urls')) then in a template you can create a link for a certain client like this:: {% url app_name.client client.id %} The URL will look like ``/clients/client/123/``. """ import warnings warnings.warn('The syntax for the url template tag is changing. Load the `url` tag from the `future` tag library to start using the new behavior.', category=PendingDeprecationWarning) bits = token.split_contents() if len(bits) < 2: raise TemplateSyntaxError("'%s' takes at least one argument" " (path to a view)" % bits[0]) viewname = bits[1] args = [] kwargs = {} asvar = None bits = bits[2:] if len(bits) >= 2 and bits[-2] == 'as': asvar = bits[-1] bits = bits[:-2] # Backwards compatibility: check for the old comma separated format # {% url urlname arg1,arg2 %} # Initial check - that the first space separated bit has a comma in it if bits and ',' in bits[0]: check_old_format = True # In order to *really* be old format, there must be a comma # in *every* space separated bit, except the last. for bit in bits[1:-1]: if ',' not in bit: # No comma in this bit. Either the comma we found # in bit 1 was a false positive (e.g., comma in a string), # or there is a syntax problem with missing commas check_old_format = False break else: # No comma found - must be new format. check_old_format = False if check_old_format: # Confirm that this is old format by trying to parse the first # argument. An exception will be raised if the comma is # unexpected (i.e. outside of a static string). match = kwarg_re.match(bits[0]) if match: value = match.groups()[1] try: parser.compile_filter(value) except TemplateSyntaxError: bits = ''.join(bits).split(',') # Now all the bits are parsed into new format, # process them as template vars if len(bits): for bit in bits: match = kwarg_re.match(bit) if not match: raise TemplateSyntaxError("Malformed arguments to url tag") name, value = match.groups() if name: kwargs[name] = parser.compile_filter(value) else: args.append(parser.compile_filter(value)) return URLNode(viewname, args, kwargs, asvar, legacy_view_name=True) url = register.tag(url) #@register.tag def widthratio(parser, token): """ For creating bar charts and such, this tag calculates the ratio of a given value to a maximum value, and then applies that ratio to a constant. For example:: <img src='bar.gif' height='10' width='{% widthratio this_value max_value 100 %}' /> Above, if ``this_value`` is 175 and ``max_value`` is 200, the image in the above example will be 88 pixels wide (because 175/200 = .875; .875 * 100 = 87.5 which is rounded up to 88). """ bits = token.contents.split() if len(bits) != 4: raise TemplateSyntaxError("widthratio takes three arguments") tag, this_value_expr, max_value_expr, max_width = bits return WidthRatioNode(parser.compile_filter(this_value_expr), parser.compile_filter(max_value_expr), parser.compile_filter(max_width)) widthratio = register.tag(widthratio) #@register.tag def do_with(parser, token): """ Adds one or more values to the context (inside of this block) for caching and easy access. For example:: {% with total=person.some_sql_method %} {{ total }} object{{ total|pluralize }} {% endwith %} Multiple values can be added to the context:: {% with foo=1 bar=2 %} ... {% endwith %} The legacy format of ``{% with person.some_sql_method as total %}`` is still accepted. """ bits = token.split_contents() remaining_bits = bits[1:] extra_context = token_kwargs(remaining_bits, parser, support_legacy=True) if not extra_context: raise TemplateSyntaxError("%r expected at least one variable " "assignment" % bits[0]) if remaining_bits: raise TemplateSyntaxError("%r received an invalid token: %r" % (bits[0], remaining_bits[0])) nodelist = parser.parse(('endwith',)) parser.delete_first_token() return WithNode(None, None, nodelist, extra_context=extra_context) do_with = register.tag('with', do_with)
47,838
Python
.py
1,138
32.93761
218
0.594961
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,851
response.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/template/response.py
from django.http import HttpResponse from django.template import loader, Context, RequestContext class ContentNotRenderedError(Exception): pass class SimpleTemplateResponse(HttpResponse): def __init__(self, template, context=None, mimetype=None, status=None, content_type=None): # It would seem obvious to call these next two members 'template' and # 'context', but those names are reserved as part of the test Client API. # To avoid the name collision, we use # tricky-to-debug problems self.template_name = template self.context_data = context # _is_rendered tracks whether the template and context has been baked into # a final response. self._is_rendered = False self._post_render_callbacks = [] # content argument doesn't make sense here because it will be replaced # with rendered template so we always pass empty string in order to # prevent errors and provide shorter signature. super(SimpleTemplateResponse, self).__init__('', mimetype, status, content_type) def __getstate__(self): """Pickling support function. Ensures that the object can't be pickled before it has been rendered, and that the pickled state only includes rendered data, not the data used to construct the response. """ obj_dict = self.__dict__.copy() if not self._is_rendered: raise ContentNotRenderedError('The response content must be rendered before it can be pickled.') del obj_dict['template_name'] del obj_dict['context_data'] del obj_dict['_post_render_callbacks'] return obj_dict def resolve_template(self, template): "Accepts a template object, path-to-template or list of paths" if isinstance(template, (list, tuple)): return loader.select_template(template) elif isinstance(template, basestring): return loader.get_template(template) else: return template def resolve_context(self, context): """Convert context data into a full Context object (assuming it isn't already a Context object). """ if isinstance(context, Context): return context else: return Context(context) @property def rendered_content(self): """Returns the freshly rendered content for the template and context described by the TemplateResponse. This *does not* set the final content of the response. To set the response content, you must either call render(), or set the content explicitly using the value of this property. """ template = self.resolve_template(self.template_name) context = self.resolve_context(self.context_data) content = template.render(context) return content def add_post_render_callback(self, callback): """Add a new post-rendering callback. If the response has already been rendered, invoke the callback immediately. """ if self._is_rendered: callback(self) else: self._post_render_callbacks.append(callback) def render(self): """Render (thereby finalizing) the content of the response. If the content has already been rendered, this is a no-op. Returns the baked response instance. """ if not self._is_rendered: self._set_content(self.rendered_content) for post_callback in self._post_render_callbacks: post_callback(self) return self is_rendered = property(lambda self: self._is_rendered) def __iter__(self): if not self._is_rendered: raise ContentNotRenderedError('The response content must be rendered before it can be iterated over.') return super(SimpleTemplateResponse, self).__iter__() def _get_content(self): if not self._is_rendered: raise ContentNotRenderedError('The response content must be rendered before it can be accessed.') return super(SimpleTemplateResponse, self)._get_content() def _set_content(self, value): "Sets the content for the response" super(SimpleTemplateResponse, self)._set_content(value) self._is_rendered = True content = property(_get_content, _set_content) class TemplateResponse(SimpleTemplateResponse): def __init__(self, request, template, context=None, mimetype=None, status=None, content_type=None, current_app=None): # self.request gets over-written by django.test.client.Client - and # unlike context_data and template_name the _request should not # be considered part of the public API. self._request = request # As a convenience we'll allow callers to provide current_app without # having to avoid needing to create the RequestContext directly self._current_app = current_app super(TemplateResponse, self).__init__( template, context, mimetype, status, content_type) def __getstate__(self): """Pickling support function. Ensures that the object can't be pickled before it has been rendered, and that the pickled state only includes rendered data, not the data used to construct the response. """ obj_dict = super(TemplateResponse, self).__getstate__() del obj_dict['_request'] del obj_dict['_current_app'] return obj_dict def resolve_context(self, context): """Convert context data into a full RequestContext object (assuming it isn't already a Context object). """ if isinstance(context, Context): return context else: return RequestContext(self._request, context, current_app=self._current_app)
5,970
Python
.py
125
38.4
114
0.659556
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,852
loader.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/template/loader.py
# Wrapper for loading templates from storage of some sort (e.g. filesystem, database). # # This uses the TEMPLATE_LOADERS setting, which is a list of loaders to use. # Each loader is expected to have this interface: # # callable(name, dirs=[]) # # name is the template name. # dirs is an optional list of directories to search instead of TEMPLATE_DIRS. # # The loader should return a tuple of (template_source, path). The path returned # might be shown to the user for debugging purposes, so it should identify where # the template was loaded from. # # A loader may return an already-compiled template instead of the actual # template source. In that case the path returned should be None, since the # path information is associated with the template during the compilation, # which has already been done. # # Each loader should have an "is_usable" attribute set. This is a boolean that # specifies whether the loader can be used in this Python installation. Each # loader is responsible for setting this when it's initialized. # # For example, the eggs loader (which is capable of loading templates from # Python eggs) sets is_usable to False if the "pkg_resources" module isn't # installed, because pkg_resources is necessary to read eggs. from django.core.exceptions import ImproperlyConfigured from django.template.base import Origin, Template, Context, TemplateDoesNotExist, add_to_builtins from django.utils.importlib import import_module from django.conf import settings template_source_loaders = None class BaseLoader(object): is_usable = False def __init__(self, *args, **kwargs): pass def __call__(self, template_name, template_dirs=None): return self.load_template(template_name, template_dirs) def load_template(self, template_name, template_dirs=None): source, display_name = self.load_template_source(template_name, template_dirs) origin = make_origin(display_name, self.load_template_source, template_name, template_dirs) try: template = get_template_from_string(source, origin, template_name) return template, None except TemplateDoesNotExist: # If compiling the template we found raises TemplateDoesNotExist, back off to # returning the source and display name for the template we were asked to load. # This allows for correct identification (later) of the actual template that does # not exist. return source, display_name def load_template_source(self, template_name, template_dirs=None): """ Returns a tuple containing the source and origin for the given template name. """ raise NotImplementedError def reset(self): """ Resets any state maintained by the loader instance (e.g., cached templates or cached loader modules). """ pass class LoaderOrigin(Origin): def __init__(self, display_name, loader, name, dirs): super(LoaderOrigin, self).__init__(display_name) self.loader, self.loadname, self.dirs = loader, name, dirs def reload(self): return self.loader(self.loadname, self.dirs)[0] def make_origin(display_name, loader, name, dirs): if settings.TEMPLATE_DEBUG and display_name: return LoaderOrigin(display_name, loader, name, dirs) else: return None def find_template_loader(loader): if isinstance(loader, (tuple, list)): loader, args = loader[0], loader[1:] else: args = [] if isinstance(loader, basestring): module, attr = loader.rsplit('.', 1) try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error importing template source loader %s: "%s"' % (loader, e)) try: TemplateLoader = getattr(mod, attr) except AttributeError, e: raise ImproperlyConfigured('Error importing template source loader %s: "%s"' % (loader, e)) if hasattr(TemplateLoader, 'load_template_source'): func = TemplateLoader(*args) else: # Try loading module the old way - string is full path to callable if args: raise ImproperlyConfigured("Error importing template source loader %s - can't pass arguments to function-based loader." % loader) func = TemplateLoader if not func.is_usable: import warnings warnings.warn("Your TEMPLATE_LOADERS setting includes %r, but your Python installation doesn't support that type of template loading. Consider removing that line from TEMPLATE_LOADERS." % loader) return None else: return func else: raise ImproperlyConfigured('Loader does not define a "load_template" callable template source loader') def find_template(name, dirs=None): # Calculate template_source_loaders the first time the function is executed # because putting this logic in the module-level namespace may cause # circular import errors. See Django ticket #1292. global template_source_loaders if template_source_loaders is None: loaders = [] for loader_name in settings.TEMPLATE_LOADERS: loader = find_template_loader(loader_name) if loader is not None: loaders.append(loader) template_source_loaders = tuple(loaders) for loader in template_source_loaders: try: source, display_name = loader(name, dirs) return (source, make_origin(display_name, loader, name, dirs)) except TemplateDoesNotExist: pass raise TemplateDoesNotExist(name) def find_template_source(name, dirs=None): # For backward compatibility import warnings warnings.warn( "`django.template.loader.find_template_source` is deprecated; use `django.template.loader.find_template` instead.", DeprecationWarning ) template, origin = find_template(name, dirs) if hasattr(template, 'render'): raise Exception("Found a compiled template that is incompatible with the deprecated `django.template.loader.find_template_source` function.") return template, origin def get_template(template_name): """ Returns a compiled Template object for the given template name, handling template inheritance recursively. """ template, origin = find_template(template_name) if not hasattr(template, 'render'): # template needs to be compiled template = get_template_from_string(template, origin, template_name) return template def get_template_from_string(source, origin=None, name=None): """ Returns a compiled Template object for the given template code, handling template inheritance recursively. """ return Template(source, origin, name) def render_to_string(template_name, dictionary=None, context_instance=None): """ Loads the given template_name and renders it with the given dictionary as context. The template_name may be a string to load a single template using get_template, or it may be a tuple to use select_template to find one of the templates in the list. Returns a string. """ dictionary = dictionary or {} if isinstance(template_name, (list, tuple)): t = select_template(template_name) else: t = get_template(template_name) if not context_instance: return t.render(Context(dictionary)) # Add the dictionary to the context stack, ensuring it gets removed again # to keep the context_instance in the same state it started in. context_instance.update(dictionary) try: return t.render(context_instance) finally: context_instance.pop() def select_template(template_name_list): "Given a list of template names, returns the first that can be loaded." not_found = [] for template_name in template_name_list: try: return get_template(template_name) except TemplateDoesNotExist, e: if e.args[0] not in not_found: not_found.append(e.args[0]) continue # If we get here, none of the templates could be loaded raise TemplateDoesNotExist(', '.join(not_found)) add_to_builtins('django.template.loader_tags')
8,326
Python
.py
182
39.06044
207
0.699544
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,853
__init__.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/template/__init__.py
""" This is the Django template system. How it works: The Lexer.tokenize() function converts a template string (i.e., a string containing markup with custom template tags) to tokens, which can be either plain text (TOKEN_TEXT), variables (TOKEN_VAR) or block statements (TOKEN_BLOCK). The Parser() class takes a list of tokens in its constructor, and its parse() method returns a compiled template -- which is, under the hood, a list of Node objects. Each Node is responsible for creating some sort of output -- e.g. simple text (TextNode), variable values in a given context (VariableNode), results of basic logic (IfNode), results of looping (ForNode), or anything else. The core Node types are TextNode, VariableNode, IfNode and ForNode, but plugin modules can define their own custom node types. Each Node has a render() method, which takes a Context and returns a string of the rendered node. For example, the render() method of a Variable Node returns the variable's value as a string. The render() method of an IfNode returns the rendered output of whatever was inside the loop, recursively. The Template class is a convenient wrapper that takes care of template compilation and rendering. Usage: The only thing you should ever use directly in this file is the Template class. Create a compiled template object with a template_string, then call render() with a context. In the compilation stage, the TemplateSyntaxError exception will be raised if the template doesn't have proper syntax. Sample code: >>> from django import template >>> s = u'<html>{% if test %}<h1>{{ varvalue }}</h1>{% endif %}</html>' >>> t = template.Template(s) (t is now a compiled template, and its render() method can be called multiple times with multiple contexts) >>> c = template.Context({'test':True, 'varvalue': 'Hello'}) >>> t.render(c) u'<html><h1>Hello</h1></html>' >>> c = template.Context({'test':False, 'varvalue': 'Hello'}) >>> t.render(c) u'<html></html>' """ # Template lexing symbols from django.template.base import (ALLOWED_VARIABLE_CHARS, BLOCK_TAG_END, BLOCK_TAG_START, COMMENT_TAG_END, COMMENT_TAG_START, FILTER_ARGUMENT_SEPARATOR, FILTER_SEPARATOR, SINGLE_BRACE_END, SINGLE_BRACE_START, TOKEN_BLOCK, TOKEN_COMMENT, TOKEN_TEXT, TOKEN_VAR, TRANSLATOR_COMMENT_MARK, UNKNOWN_SOURCE, VARIABLE_ATTRIBUTE_SEPARATOR, VARIABLE_TAG_END, VARIABLE_TAG_START, filter_re, tag_re) # Exceptions from django.template.base import (ContextPopException, InvalidTemplateLibrary, TemplateDoesNotExist, TemplateEncodingError, TemplateSyntaxError, VariableDoesNotExist) # Template parts from django.template.base import (Context, FilterExpression, Lexer, Node, NodeList, Parser, RequestContext, Origin, StringOrigin, Template, TextNode, Token, TokenParser, Variable, VariableNode, constant_string, filter_raw_string) # Compiling templates from django.template.base import (compile_string, resolve_variable, unescape_string_literal, generic_tag_compiler) # Library management from django.template.base import (Library, add_to_builtins, builtins, get_library, get_templatetags_modules, get_text_list, import_library, libraries) __all__ = ('Template', 'Context', 'RequestContext', 'compile_string')
3,247
Python
.py
62
50.241935
83
0.774234
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,854
loader_tags.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/template/loader_tags.py
from django.template.base import TemplateSyntaxError, TemplateDoesNotExist, Variable from django.template.base import Library, Node, TextNode from django.template.context import Context from django.template.defaulttags import token_kwargs from django.template.loader import get_template from django.conf import settings from django.utils.safestring import mark_safe register = Library() BLOCK_CONTEXT_KEY = 'block_context' class ExtendsError(Exception): pass class BlockContext(object): def __init__(self): # Dictionary of FIFO queues. self.blocks = {} def add_blocks(self, blocks): for name, block in blocks.iteritems(): if name in self.blocks: self.blocks[name].insert(0, block) else: self.blocks[name] = [block] def pop(self, name): try: return self.blocks[name].pop() except (IndexError, KeyError): return None def push(self, name, block): self.blocks[name].append(block) def get_block(self, name): try: return self.blocks[name][-1] except (IndexError, KeyError): return None class BlockNode(Node): def __init__(self, name, nodelist, parent=None): self.name, self.nodelist, self.parent = name, nodelist, parent def __repr__(self): return "<Block Node: %s. Contents: %r>" % (self.name, self.nodelist) def render(self, context): block_context = context.render_context.get(BLOCK_CONTEXT_KEY) context.push() if block_context is None: context['block'] = self result = self.nodelist.render(context) else: push = block = block_context.pop(self.name) if block is None: block = self # Create new block so we can store context without thread-safety issues. block = BlockNode(block.name, block.nodelist) block.context = context context['block'] = block result = block.nodelist.render(context) if push is not None: block_context.push(self.name, push) context.pop() return result def super(self): render_context = self.context.render_context if (BLOCK_CONTEXT_KEY in render_context and render_context[BLOCK_CONTEXT_KEY].get_block(self.name) is not None): return mark_safe(self.render(self.context)) return '' class ExtendsNode(Node): must_be_first = True def __init__(self, nodelist, parent_name, parent_name_expr, template_dirs=None): self.nodelist = nodelist self.parent_name, self.parent_name_expr = parent_name, parent_name_expr self.template_dirs = template_dirs self.blocks = dict([(n.name, n) for n in nodelist.get_nodes_by_type(BlockNode)]) def __repr__(self): if self.parent_name_expr: return "<ExtendsNode: extends %s>" % self.parent_name_expr.token return '<ExtendsNode: extends "%s">' % self.parent_name def get_parent(self, context): if self.parent_name_expr: self.parent_name = self.parent_name_expr.resolve(context) parent = self.parent_name if not parent: error_msg = "Invalid template name in 'extends' tag: %r." % parent if self.parent_name_expr: error_msg += " Got this from the '%s' variable." % self.parent_name_expr.token raise TemplateSyntaxError(error_msg) if hasattr(parent, 'render'): return parent # parent is a Template object return get_template(parent) def render(self, context): compiled_parent = self.get_parent(context) if BLOCK_CONTEXT_KEY not in context.render_context: context.render_context[BLOCK_CONTEXT_KEY] = BlockContext() block_context = context.render_context[BLOCK_CONTEXT_KEY] # Add the block nodes from this node to the block context block_context.add_blocks(self.blocks) # If this block's parent doesn't have an extends node it is the root, # and its block nodes also need to be added to the block context. for node in compiled_parent.nodelist: # The ExtendsNode has to be the first non-text node. if not isinstance(node, TextNode): if not isinstance(node, ExtendsNode): blocks = dict([(n.name, n) for n in compiled_parent.nodelist.get_nodes_by_type(BlockNode)]) block_context.add_blocks(blocks) break # Call Template._render explicitly so the parser context stays # the same. return compiled_parent._render(context) class BaseIncludeNode(Node): def __init__(self, *args, **kwargs): self.extra_context = kwargs.pop('extra_context', {}) self.isolated_context = kwargs.pop('isolated_context', False) super(BaseIncludeNode, self).__init__(*args, **kwargs) def render_template(self, template, context): values = dict([(name, var.resolve(context)) for name, var in self.extra_context.iteritems()]) if self.isolated_context: return template.render(context.new(values)) context.update(values) output = template.render(context) context.pop() return output class ConstantIncludeNode(BaseIncludeNode): def __init__(self, template_path, *args, **kwargs): super(ConstantIncludeNode, self).__init__(*args, **kwargs) try: t = get_template(template_path) self.template = t except: if settings.TEMPLATE_DEBUG: raise self.template = None def render(self, context): if not self.template: return '' return self.render_template(self.template, context) class IncludeNode(BaseIncludeNode): def __init__(self, template_name, *args, **kwargs): super(IncludeNode, self).__init__(*args, **kwargs) self.template_name = template_name def render(self, context): try: template_name = self.template_name.resolve(context) template = get_template(template_name) return self.render_template(template, context) except: if settings.TEMPLATE_DEBUG: raise return '' def do_block(parser, token): """ Define a block that can be overridden by child templates. """ bits = token.contents.split() if len(bits) != 2: raise TemplateSyntaxError("'%s' tag takes only one argument" % bits[0]) block_name = bits[1] # Keep track of the names of BlockNodes found in this template, so we can # check for duplication. try: if block_name in parser.__loaded_blocks: raise TemplateSyntaxError("'%s' tag with name '%s' appears more than once" % (bits[0], block_name)) parser.__loaded_blocks.append(block_name) except AttributeError: # parser.__loaded_blocks isn't a list yet parser.__loaded_blocks = [block_name] nodelist = parser.parse(('endblock', 'endblock %s' % block_name)) parser.delete_first_token() return BlockNode(block_name, nodelist) def do_extends(parser, token): """ Signal that this template extends a parent template. This tag may be used in two ways: ``{% extends "base" %}`` (with quotes) uses the literal value "base" as the name of the parent template to extend, or ``{% extends variable %}`` uses the value of ``variable`` as either the name of the parent template to extend (if it evaluates to a string) or as the parent tempate itelf (if it evaluates to a Template object). """ bits = token.split_contents() if len(bits) != 2: raise TemplateSyntaxError("'%s' takes one argument" % bits[0]) parent_name, parent_name_expr = None, None if bits[1][0] in ('"', "'") and bits[1][-1] == bits[1][0]: parent_name = bits[1][1:-1] else: parent_name_expr = parser.compile_filter(bits[1]) nodelist = parser.parse() if nodelist.get_nodes_by_type(ExtendsNode): raise TemplateSyntaxError("'%s' cannot appear more than once in the same template" % bits[0]) return ExtendsNode(nodelist, parent_name, parent_name_expr) def do_include(parser, token): """ Loads a template and renders it with the current context. You can pass additional context using keyword arguments. Example:: {% include "foo/some_include" %} {% include "foo/some_include" with bar="BAZZ!" baz="BING!" %} Use the ``only`` argument to exclude the current context when rendering the included template:: {% include "foo/some_include" only %} {% include "foo/some_include" with bar="1" only %} """ bits = token.split_contents() if len(bits) < 2: raise TemplateSyntaxError("%r tag takes at least one argument: the name of the template to be included." % bits[0]) options = {} remaining_bits = bits[2:] while remaining_bits: option = remaining_bits.pop(0) if option in options: raise TemplateSyntaxError('The %r option was specified more ' 'than once.' % option) if option == 'with': value = token_kwargs(remaining_bits, parser, support_legacy=False) if not value: raise TemplateSyntaxError('"with" in %r tag needs at least ' 'one keyword argument.' % bits[0]) elif option == 'only': value = True else: raise TemplateSyntaxError('Unknown argument for %r tag: %r.' % (bits[0], option)) options[option] = value isolated_context = options.get('only', False) namemap = options.get('with', {}) path = bits[1] if path[0] in ('"', "'") and path[-1] == path[0]: return ConstantIncludeNode(path[1:-1], extra_context=namemap, isolated_context=isolated_context) return IncludeNode(parser.compile_filter(bits[1]), extra_context=namemap, isolated_context=isolated_context) register.tag('block', do_block) register.tag('extends', do_extends) register.tag('include', do_include)
10,409
Python
.py
231
35.844156
123
0.626109
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,855
base.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/template/base.py
import imp import re from inspect import getargspec from django.conf import settings from django.template.context import Context, RequestContext, ContextPopException from django.utils.importlib import import_module from django.utils.itercompat import is_iterable from django.utils.functional import curry, Promise from django.utils.text import smart_split, unescape_string_literal, get_text_list from django.utils.encoding import smart_unicode, force_unicode, smart_str from django.utils.translation import ugettext_lazy from django.utils.safestring import SafeData, EscapeData, mark_safe, mark_for_escaping from django.utils.formats import localize from django.utils.html import escape from django.utils.module_loading import module_has_submodule TOKEN_TEXT = 0 TOKEN_VAR = 1 TOKEN_BLOCK = 2 TOKEN_COMMENT = 3 # template syntax constants FILTER_SEPARATOR = '|' FILTER_ARGUMENT_SEPARATOR = ':' VARIABLE_ATTRIBUTE_SEPARATOR = '.' BLOCK_TAG_START = '{%' BLOCK_TAG_END = '%}' VARIABLE_TAG_START = '{{' VARIABLE_TAG_END = '}}' COMMENT_TAG_START = '{#' COMMENT_TAG_END = '#}' TRANSLATOR_COMMENT_MARK = 'Translators' SINGLE_BRACE_START = '{' SINGLE_BRACE_END = '}' ALLOWED_VARIABLE_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.' # what to report as the origin for templates that come from non-loader sources # (e.g. strings) UNKNOWN_SOURCE = '<unknown source>' # match a variable or block tag and capture the entire tag, including start/end delimiters tag_re = re.compile('(%s.*?%s|%s.*?%s|%s.*?%s)' % (re.escape(BLOCK_TAG_START), re.escape(BLOCK_TAG_END), re.escape(VARIABLE_TAG_START), re.escape(VARIABLE_TAG_END), re.escape(COMMENT_TAG_START), re.escape(COMMENT_TAG_END))) # global dictionary of libraries that have been loaded using get_library libraries = {} # global list of libraries to load by default for a new parser builtins = [] # True if TEMPLATE_STRING_IF_INVALID contains a format string (%s). None means # uninitialised. invalid_var_format_string = None class TemplateSyntaxError(Exception): pass class TemplateDoesNotExist(Exception): pass class TemplateEncodingError(Exception): pass class VariableDoesNotExist(Exception): def __init__(self, msg, params=()): self.msg = msg self.params = params def __str__(self): return unicode(self).encode('utf-8') def __unicode__(self): return self.msg % tuple([force_unicode(p, errors='replace') for p in self.params]) class InvalidTemplateLibrary(Exception): pass class Origin(object): def __init__(self, name): self.name = name def reload(self): raise NotImplementedError def __str__(self): return self.name class StringOrigin(Origin): def __init__(self, source): super(StringOrigin, self).__init__(UNKNOWN_SOURCE) self.source = source def reload(self): return self.source class Template(object): def __init__(self, template_string, origin=None, name='<Unknown Template>'): try: template_string = smart_unicode(template_string) except UnicodeDecodeError: raise TemplateEncodingError("Templates can only be constructed from unicode or UTF-8 strings.") if settings.TEMPLATE_DEBUG and origin is None: origin = StringOrigin(template_string) self.nodelist = compile_string(template_string, origin) self.name = name def __iter__(self): for node in self.nodelist: for subnode in node: yield subnode def _render(self, context): return self.nodelist.render(context) def render(self, context): "Display stage -- can be called many times" context.render_context.push() try: return self._render(context) finally: context.render_context.pop() def compile_string(template_string, origin): "Compiles template_string into NodeList ready for rendering" if settings.TEMPLATE_DEBUG: from debug import DebugLexer, DebugParser lexer_class, parser_class = DebugLexer, DebugParser else: lexer_class, parser_class = Lexer, Parser lexer = lexer_class(template_string, origin) parser = parser_class(lexer.tokenize()) return parser.parse() class Token(object): def __init__(self, token_type, contents): # token_type must be TOKEN_TEXT, TOKEN_VAR, TOKEN_BLOCK or TOKEN_COMMENT. self.token_type, self.contents = token_type, contents self.lineno = None def __str__(self): return '<%s token: "%s...">' % \ ({TOKEN_TEXT: 'Text', TOKEN_VAR: 'Var', TOKEN_BLOCK: 'Block', TOKEN_COMMENT: 'Comment'}[self.token_type], self.contents[:20].replace('\n', '')) def split_contents(self): split = [] bits = iter(smart_split(self.contents)) for bit in bits: # Handle translation-marked template pieces if bit.startswith('_("') or bit.startswith("_('"): sentinal = bit[2] + ')' trans_bit = [bit] while not bit.endswith(sentinal): bit = bits.next() trans_bit.append(bit) bit = ' '.join(trans_bit) split.append(bit) return split class Lexer(object): def __init__(self, template_string, origin): self.template_string = template_string self.origin = origin self.lineno = 1 def tokenize(self): "Return a list of tokens from a given template_string." in_tag = False result = [] for bit in tag_re.split(self.template_string): if bit: result.append(self.create_token(bit, in_tag)) in_tag = not in_tag return result def create_token(self, token_string, in_tag): """ Convert the given token string into a new Token object and return it. If in_tag is True, we are processing something that matched a tag, otherwise it should be treated as a literal string. """ if in_tag: if token_string.startswith(VARIABLE_TAG_START): token = Token(TOKEN_VAR, token_string[len(VARIABLE_TAG_START):-len(VARIABLE_TAG_END)].strip()) elif token_string.startswith(BLOCK_TAG_START): token = Token(TOKEN_BLOCK, token_string[len(BLOCK_TAG_START):-len(BLOCK_TAG_END)].strip()) elif token_string.startswith(COMMENT_TAG_START): content = '' if token_string.find(TRANSLATOR_COMMENT_MARK): content = token_string[len(COMMENT_TAG_START):-len(COMMENT_TAG_END)].strip() token = Token(TOKEN_COMMENT, content) else: token = Token(TOKEN_TEXT, token_string) token.lineno = self.lineno self.lineno += token_string.count('\n') return token class Parser(object): def __init__(self, tokens): self.tokens = tokens self.tags = {} self.filters = {} for lib in builtins: self.add_library(lib) def parse(self, parse_until=None): if parse_until is None: parse_until = [] nodelist = self.create_nodelist() while self.tokens: token = self.next_token() if token.token_type == TOKEN_TEXT: self.extend_nodelist(nodelist, TextNode(token.contents), token) elif token.token_type == TOKEN_VAR: if not token.contents: self.empty_variable(token) filter_expression = self.compile_filter(token.contents) var_node = self.create_variable_node(filter_expression) self.extend_nodelist(nodelist, var_node,token) elif token.token_type == TOKEN_BLOCK: if token.contents in parse_until: # put token back on token list so calling code knows why it terminated self.prepend_token(token) return nodelist try: command = token.contents.split()[0] except IndexError: self.empty_block_tag(token) # execute callback function for this tag and append resulting node self.enter_command(command, token) try: compile_func = self.tags[command] except KeyError: self.invalid_block_tag(token, command, parse_until) try: compiled_result = compile_func(self, token) except TemplateSyntaxError, e: if not self.compile_function_error(token, e): raise self.extend_nodelist(nodelist, compiled_result, token) self.exit_command() if parse_until: self.unclosed_block_tag(parse_until) return nodelist def skip_past(self, endtag): while self.tokens: token = self.next_token() if token.token_type == TOKEN_BLOCK and token.contents == endtag: return self.unclosed_block_tag([endtag]) def create_variable_node(self, filter_expression): return VariableNode(filter_expression) def create_nodelist(self): return NodeList() def extend_nodelist(self, nodelist, node, token): if node.must_be_first and nodelist: try: if nodelist.contains_nontext: raise AttributeError except AttributeError: raise TemplateSyntaxError("%r must be the first tag in the template." % node) if isinstance(nodelist, NodeList) and not isinstance(node, TextNode): nodelist.contains_nontext = True nodelist.append(node) def enter_command(self, command, token): pass def exit_command(self): pass def error(self, token, msg): return TemplateSyntaxError(msg) def empty_variable(self, token): raise self.error(token, "Empty variable tag") def empty_block_tag(self, token): raise self.error(token, "Empty block tag") def invalid_block_tag(self, token, command, parse_until=None): if parse_until: raise self.error(token, "Invalid block tag: '%s', expected %s" % (command, get_text_list(["'%s'" % p for p in parse_until]))) raise self.error(token, "Invalid block tag: '%s'" % command) def unclosed_block_tag(self, parse_until): raise self.error(None, "Unclosed tags: %s " % ', '.join(parse_until)) def compile_function_error(self, token, e): pass def next_token(self): return self.tokens.pop(0) def prepend_token(self, token): self.tokens.insert(0, token) def delete_first_token(self): del self.tokens[0] def add_library(self, lib): self.tags.update(lib.tags) self.filters.update(lib.filters) def compile_filter(self, token): "Convenient wrapper for FilterExpression" return FilterExpression(token, self) def find_filter(self, filter_name): if filter_name in self.filters: return self.filters[filter_name] else: raise TemplateSyntaxError("Invalid filter: '%s'" % filter_name) class TokenParser(object): """ Subclass this and implement the top() method to parse a template line. When instantiating the parser, pass in the line from the Django template parser. The parser's "tagname" instance-variable stores the name of the tag that the filter was called with. """ def __init__(self, subject): self.subject = subject self.pointer = 0 self.backout = [] self.tagname = self.tag() def top(self): "Overload this method to do the actual parsing and return the result." raise NotImplementedError() def more(self): "Returns True if there is more stuff in the tag." return self.pointer < len(self.subject) def back(self): "Undoes the last microparser. Use this for lookahead and backtracking." if not len(self.backout): raise TemplateSyntaxError("back called without some previous parsing") self.pointer = self.backout.pop() def tag(self): "A microparser that just returns the next tag from the line." subject = self.subject i = self.pointer if i >= len(subject): raise TemplateSyntaxError("expected another tag, found end of string: %s" % subject) p = i while i < len(subject) and subject[i] not in (' ', '\t'): i += 1 s = subject[p:i] while i < len(subject) and subject[i] in (' ', '\t'): i += 1 self.backout.append(self.pointer) self.pointer = i return s def value(self): "A microparser that parses for a value: some string constant or variable name." subject = self.subject i = self.pointer def next_space_index(subject, i): "Increment pointer until a real space (i.e. a space not within quotes) is encountered" while i < len(subject) and subject[i] not in (' ', '\t'): if subject[i] in ('"', "'"): c = subject[i] i += 1 while i < len(subject) and subject[i] != c: i += 1 if i >= len(subject): raise TemplateSyntaxError("Searching for value. Unexpected end of string in column %d: %s" % (i, subject)) i += 1 return i if i >= len(subject): raise TemplateSyntaxError("Searching for value. Expected another value but found end of string: %s" % subject) if subject[i] in ('"', "'"): p = i i += 1 while i < len(subject) and subject[i] != subject[p]: i += 1 if i >= len(subject): raise TemplateSyntaxError("Searching for value. Unexpected end of string in column %d: %s" % (i, subject)) i += 1 # Continue parsing until next "real" space, so that filters are also included i = next_space_index(subject, i) res = subject[p:i] while i < len(subject) and subject[i] in (' ', '\t'): i += 1 self.backout.append(self.pointer) self.pointer = i return res else: p = i i = next_space_index(subject, i) s = subject[p:i] while i < len(subject) and subject[i] in (' ', '\t'): i += 1 self.backout.append(self.pointer) self.pointer = i return s # This only matches constant *strings* (things in quotes or marked for # translation). Numbers are treated as variables for implementation reasons # (so that they retain their type when passed to filters). constant_string = r""" (?:%(i18n_open)s%(strdq)s%(i18n_close)s| %(i18n_open)s%(strsq)s%(i18n_close)s| %(strdq)s| %(strsq)s) """ % { 'strdq': r'"[^"\\]*(?:\\.[^"\\]*)*"', # double-quoted string 'strsq': r"'[^'\\]*(?:\\.[^'\\]*)*'", # single-quoted string 'i18n_open' : re.escape("_("), 'i18n_close' : re.escape(")"), } constant_string = constant_string.replace("\n", "") filter_raw_string = r""" ^(?P<constant>%(constant)s)| ^(?P<var>[%(var_chars)s]+|%(num)s)| (?:%(filter_sep)s (?P<filter_name>\w+) (?:%(arg_sep)s (?: (?P<constant_arg>%(constant)s)| (?P<var_arg>[%(var_chars)s]+|%(num)s) ) )? )""" % { 'constant': constant_string, 'num': r'[-+\.]?\d[\d\.e]*', 'var_chars': "\w\." , 'filter_sep': re.escape(FILTER_SEPARATOR), 'arg_sep': re.escape(FILTER_ARGUMENT_SEPARATOR), } filter_re = re.compile(filter_raw_string, re.UNICODE|re.VERBOSE) class FilterExpression(object): r""" Parses a variable token and its optional filters (all as a single string), and return a list of tuples of the filter name and arguments. Sample: >>> token = 'variable|default:"Default value"|date:"Y-m-d"' >>> p = Parser('') >>> fe = FilterExpression(token, p) >>> len(fe.filters) 2 >>> fe.var <Variable: 'variable'> This class should never be instantiated outside of the get_filters_from_token helper function. """ def __init__(self, token, parser): self.token = token matches = filter_re.finditer(token) var_obj = None filters = [] upto = 0 for match in matches: start = match.start() if upto != start: raise TemplateSyntaxError("Could not parse some characters: %s|%s|%s" % \ (token[:upto], token[upto:start], token[start:])) if var_obj is None: var, constant = match.group("var", "constant") if constant: try: var_obj = Variable(constant).resolve({}) except VariableDoesNotExist: var_obj = None elif var is None: raise TemplateSyntaxError("Could not find variable at start of %s." % token) else: var_obj = Variable(var) else: filter_name = match.group("filter_name") args = [] constant_arg, var_arg = match.group("constant_arg", "var_arg") if constant_arg: args.append((False, Variable(constant_arg).resolve({}))) elif var_arg: args.append((True, Variable(var_arg))) filter_func = parser.find_filter(filter_name) self.args_check(filter_name, filter_func, args) filters.append((filter_func, args)) upto = match.end() if upto != len(token): raise TemplateSyntaxError("Could not parse the remainder: '%s' from '%s'" % (token[upto:], token)) self.filters = filters self.var = var_obj def resolve(self, context, ignore_failures=False): if isinstance(self.var, Variable): try: obj = self.var.resolve(context) except VariableDoesNotExist: if ignore_failures: obj = None else: if settings.TEMPLATE_STRING_IF_INVALID: global invalid_var_format_string if invalid_var_format_string is None: invalid_var_format_string = '%s' in settings.TEMPLATE_STRING_IF_INVALID if invalid_var_format_string: return settings.TEMPLATE_STRING_IF_INVALID % self.var return settings.TEMPLATE_STRING_IF_INVALID else: obj = settings.TEMPLATE_STRING_IF_INVALID else: obj = self.var for func, args in self.filters: arg_vals = [] for lookup, arg in args: if not lookup: arg_vals.append(mark_safe(arg)) else: arg_vals.append(arg.resolve(context)) if getattr(func, 'needs_autoescape', False): new_obj = func(obj, autoescape=context.autoescape, *arg_vals) else: new_obj = func(obj, *arg_vals) if getattr(func, 'is_safe', False) and isinstance(obj, SafeData): obj = mark_safe(new_obj) elif isinstance(obj, EscapeData): obj = mark_for_escaping(new_obj) else: obj = new_obj return obj def args_check(name, func, provided): provided = list(provided) plen = len(provided) # Check to see if a decorator is providing the real function. func = getattr(func, '_decorated_function', func) args, varargs, varkw, defaults = getargspec(func) # First argument is filter input. args.pop(0) if defaults: nondefs = args[:-len(defaults)] else: nondefs = args # Args without defaults must be provided. try: for arg in nondefs: provided.pop(0) except IndexError: # Not enough raise TemplateSyntaxError("%s requires %d arguments, %d provided" % (name, len(nondefs), plen)) # Defaults can be overridden. defaults = defaults and list(defaults) or [] try: for parg in provided: defaults.pop(0) except IndexError: # Too many. raise TemplateSyntaxError("%s requires %d arguments, %d provided" % (name, len(nondefs), plen)) return True args_check = staticmethod(args_check) def __str__(self): return self.token def resolve_variable(path, context): """ Returns the resolved variable, which may contain attribute syntax, within the given context. Deprecated; use the Variable class instead. """ return Variable(path).resolve(context) class Variable(object): r""" A template variable, resolvable against a given context. The variable may be a hard-coded string (if it begins and ends with single or double quote marks):: >>> c = {'article': {'section':u'News'}} >>> Variable('article.section').resolve(c) u'News' >>> Variable('article').resolve(c) {'section': u'News'} >>> class AClass: pass >>> c = AClass() >>> c.article = AClass() >>> c.article.section = u'News' (The example assumes VARIABLE_ATTRIBUTE_SEPARATOR is '.') """ def __init__(self, var): self.var = var self.literal = None self.lookups = None self.translate = False try: # First try to treat this variable as a number. # # Note that this could cause an OverflowError here that we're not # catching. Since this should only happen at compile time, that's # probably OK. self.literal = float(var) # So it's a float... is it an int? If the original value contained a # dot or an "e" then it was a float, not an int. if '.' not in var and 'e' not in var.lower(): self.literal = int(self.literal) # "2." is invalid if var.endswith('.'): raise ValueError except ValueError: # A ValueError means that the variable isn't a number. if var.startswith('_(') and var.endswith(')'): # The result of the lookup should be translated at rendering # time. self.translate = True var = var[2:-1] # If it's wrapped with quotes (single or double), then # we're also dealing with a literal. try: self.literal = mark_safe(unescape_string_literal(var)) except ValueError: # Otherwise we'll set self.lookups so that resolve() knows we're # dealing with a bonafide variable if var.find(VARIABLE_ATTRIBUTE_SEPARATOR + '_') > -1 or var[0] == '_': raise TemplateSyntaxError("Variables and attributes may not begin with underscores: '%s'" % var) self.lookups = tuple(var.split(VARIABLE_ATTRIBUTE_SEPARATOR)) def resolve(self, context): """Resolve this variable against a given context.""" if self.lookups is not None: # We're dealing with a variable that needs to be resolved value = self._resolve_lookup(context) else: # We're dealing with a literal, so it's already been "resolved" value = self.literal if self.translate: return ugettext_lazy(value) return value def __repr__(self): return "<%s: %r>" % (self.__class__.__name__, self.var) def __str__(self): return self.var def _resolve_lookup(self, context): """ Performs resolution of a real variable (i.e. not a literal) against the given context. As indicated by the method's name, this method is an implementation detail and shouldn't be called by external code. Use Variable.resolve() instead. """ current = context try: # catch-all for silent variable failures for bit in self.lookups: try: # dictionary lookup current = current[bit] except (TypeError, AttributeError, KeyError): try: # attribute lookup current = getattr(current, bit) except (TypeError, AttributeError): try: # list-index lookup current = current[int(bit)] except (IndexError, # list index out of range ValueError, # invalid literal for int() KeyError, # current is a dict without `int(bit)` key TypeError, # unsubscriptable object ): raise VariableDoesNotExist("Failed lookup for key [%s] in %r", (bit, current)) # missing attribute if callable(current): if getattr(current, 'alters_data', False): current = settings.TEMPLATE_STRING_IF_INVALID else: try: # method call (assuming no args required) current = current() except TypeError: # arguments *were* required # GOTCHA: This will also catch any TypeError # raised in the function itself. current = settings.TEMPLATE_STRING_IF_INVALID # invalid method call except Exception, e: if getattr(e, 'silent_variable_failure', False): current = settings.TEMPLATE_STRING_IF_INVALID else: raise return current class Node(object): # Set this to True for nodes that must be first in the template (although # they can be preceded by text nodes. must_be_first = False child_nodelists = ('nodelist',) def render(self, context): "Return the node rendered as a string" pass def __iter__(self): yield self def get_nodes_by_type(self, nodetype): "Return a list of all nodes (within this node and its nodelist) of the given type" nodes = [] if isinstance(self, nodetype): nodes.append(self) for attr in self.child_nodelists: nodelist = getattr(self, attr, None) if nodelist: nodes.extend(nodelist.get_nodes_by_type(nodetype)) return nodes class NodeList(list): # Set to True the first time a non-TextNode is inserted by # extend_nodelist(). contains_nontext = False def render(self, context): bits = [] for node in self: if isinstance(node, Node): bits.append(self.render_node(node, context)) else: bits.append(node) return mark_safe(''.join([force_unicode(b) for b in bits])) def get_nodes_by_type(self, nodetype): "Return a list of all nodes of the given type" nodes = [] for node in self: nodes.extend(node.get_nodes_by_type(nodetype)) return nodes def render_node(self, node, context): return node.render(context) class TextNode(Node): def __init__(self, s): self.s = s def __repr__(self): return "<Text Node: '%s'>" % smart_str(self.s[:25], 'ascii', errors='replace') def render(self, context): return self.s def _render_value_in_context(value, context): """ Converts any value to a string to become part of a rendered template. This means escaping, if required, and conversion to a unicode object. If value is a string, it is expected to have already been translated. """ value = localize(value, use_l10n=context.use_l10n) value = force_unicode(value) if (context.autoescape and not isinstance(value, SafeData)) or isinstance(value, EscapeData): return escape(value) else: return value class VariableNode(Node): def __init__(self, filter_expression): self.filter_expression = filter_expression def __repr__(self): return "<Variable Node: %s>" % self.filter_expression def render(self, context): try: output = self.filter_expression.resolve(context) except UnicodeDecodeError: # Unicode conversion can fail sometimes for reasons out of our # control (e.g. exception rendering). In that case, we fail quietly. return '' return _render_value_in_context(output, context) def generic_tag_compiler(params, defaults, name, node_class, parser, token): "Returns a template.Node subclass." bits = token.split_contents()[1:] bmax = len(params) def_len = defaults and len(defaults) or 0 bmin = bmax - def_len if(len(bits) < bmin or len(bits) > bmax): if bmin == bmax: message = "%s takes %s arguments" % (name, bmin) else: message = "%s takes between %s and %s arguments" % (name, bmin, bmax) raise TemplateSyntaxError(message) return node_class(bits) class Library(object): def __init__(self): self.filters = {} self.tags = {} def tag(self, name=None, compile_function=None): if name == None and compile_function == None: # @register.tag() return self.tag_function elif name != None and compile_function == None: if(callable(name)): # @register.tag return self.tag_function(name) else: # @register.tag('somename') or @register.tag(name='somename') def dec(func): return self.tag(name, func) return dec elif name != None and compile_function != None: # register.tag('somename', somefunc) self.tags[name] = compile_function return compile_function else: raise InvalidTemplateLibrary("Unsupported arguments to Library.tag: (%r, %r)", (name, compile_function)) def tag_function(self,func): self.tags[getattr(func, "_decorated_function", func).__name__] = func return func def filter(self, name=None, filter_func=None): if name == None and filter_func == None: # @register.filter() return self.filter_function elif filter_func == None: if(callable(name)): # @register.filter return self.filter_function(name) else: # @register.filter('somename') or @register.filter(name='somename') def dec(func): return self.filter(name, func) return dec elif name != None and filter_func != None: # register.filter('somename', somefunc) self.filters[name] = filter_func return filter_func else: raise InvalidTemplateLibrary("Unsupported arguments to Library.filter: (%r, %r)", (name, filter_func)) def filter_function(self, func): self.filters[getattr(func, "_decorated_function", func).__name__] = func return func def simple_tag(self, func=None, takes_context=None): def dec(func): params, xx, xxx, defaults = getargspec(func) if takes_context: if params[0] == 'context': params = params[1:] else: raise TemplateSyntaxError("Any tag function decorated with takes_context=True must have a first argument of 'context'") class SimpleNode(Node): def __init__(self, vars_to_resolve): self.vars_to_resolve = map(Variable, vars_to_resolve) def render(self, context): resolved_vars = [var.resolve(context) for var in self.vars_to_resolve] if takes_context: func_args = [context] + resolved_vars else: func_args = resolved_vars return func(*func_args) compile_func = curry(generic_tag_compiler, params, defaults, getattr(func, "_decorated_function", func).__name__, SimpleNode) compile_func.__doc__ = func.__doc__ self.tag(getattr(func, "_decorated_function", func).__name__, compile_func) return func if func is None: # @register.simple_tag(...) return dec elif callable(func): # @register.simple_tag return dec(func) else: raise TemplateSyntaxError("Invalid arguments provided to simple_tag") def inclusion_tag(self, file_name, context_class=Context, takes_context=False): def dec(func): params, xx, xxx, defaults = getargspec(func) if takes_context: if params[0] == 'context': params = params[1:] else: raise TemplateSyntaxError("Any tag function decorated with takes_context=True must have a first argument of 'context'") class InclusionNode(Node): def __init__(self, vars_to_resolve): self.vars_to_resolve = map(Variable, vars_to_resolve) def render(self, context): resolved_vars = [var.resolve(context) for var in self.vars_to_resolve] if takes_context: args = [context] + resolved_vars else: args = resolved_vars dict = func(*args) if not getattr(self, 'nodelist', False): from django.template.loader import get_template, select_template if not isinstance(file_name, basestring) and is_iterable(file_name): t = select_template(file_name) else: t = get_template(file_name) self.nodelist = t.nodelist new_context = context_class(dict, autoescape=context.autoescape) # Copy across the CSRF token, if present, because inclusion # tags are often used for forms, and we need instructions # for using CSRF protection to be as simple as possible. csrf_token = context.get('csrf_token', None) if csrf_token is not None: new_context['csrf_token'] = csrf_token return self.nodelist.render(new_context) compile_func = curry(generic_tag_compiler, params, defaults, getattr(func, "_decorated_function", func).__name__, InclusionNode) compile_func.__doc__ = func.__doc__ self.tag(getattr(func, "_decorated_function", func).__name__, compile_func) return func return dec def import_library(taglib_module): """Load a template tag library module. Verifies that the library contains a 'register' attribute, and returns that attribute as the representation of the library """ app_path, taglib = taglib_module.rsplit('.',1) app_module = import_module(app_path) try: mod = import_module(taglib_module) except ImportError, e: # If the ImportError is because the taglib submodule does not exist, that's not # an error that should be raised. If the submodule exists and raised an ImportError # on the attempt to load it, that we want to raise. if not module_has_submodule(app_module, taglib): return None else: raise InvalidTemplateLibrary("ImportError raised loading %s: %s" % (taglib_module, e)) try: return mod.register except AttributeError: raise InvalidTemplateLibrary("Template library %s does not have a variable named 'register'" % taglib_module) templatetags_modules = [] def get_templatetags_modules(): """Return the list of all available template tag modules. Caches the result for faster access. """ global templatetags_modules if not templatetags_modules: _templatetags_modules = [] # Populate list once per thread. for app_module in ['django'] + list(settings.INSTALLED_APPS): try: templatetag_module = '%s.templatetags' % app_module import_module(templatetag_module) _templatetags_modules.append(templatetag_module) except ImportError: continue templatetags_modules = _templatetags_modules return templatetags_modules def get_library(library_name): """ Load the template library module with the given name. If library is not already loaded loop over all templatetags modules to locate it. {% load somelib %} and {% load someotherlib %} loops twice. Subsequent loads eg. {% load somelib %} in the same process will grab the cached module from libraries. """ lib = libraries.get(library_name, None) if not lib: templatetags_modules = get_templatetags_modules() tried_modules = [] for module in templatetags_modules: taglib_module = '%s.%s' % (module, library_name) tried_modules.append(taglib_module) lib = import_library(taglib_module) if lib: libraries[library_name] = lib break if not lib: raise InvalidTemplateLibrary("Template library %s not found, tried %s" % (library_name, ','.join(tried_modules))) return lib def add_to_builtins(module): builtins.append(import_library(module)) add_to_builtins('django.template.defaulttags') add_to_builtins('django.template.defaultfilters')
38,683
Python
.py
885
32.753672
140
0.586794
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,856
debug.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/template/debug.py
from django.conf import settings from django.template.base import Lexer, Parser, tag_re, NodeList, VariableNode, TemplateSyntaxError from django.utils.encoding import force_unicode from django.utils.html import escape from django.utils.safestring import SafeData, EscapeData from django.utils.formats import localize class DebugLexer(Lexer): def __init__(self, template_string, origin): super(DebugLexer, self).__init__(template_string, origin) def tokenize(self): "Return a list of tokens from a given template_string" result, upto = [], 0 for match in tag_re.finditer(self.template_string): start, end = match.span() if start > upto: result.append(self.create_token(self.template_string[upto:start], (upto, start), False)) upto = start result.append(self.create_token(self.template_string[start:end], (start, end), True)) upto = end last_bit = self.template_string[upto:] if last_bit: result.append(self.create_token(last_bit, (upto, upto + len(last_bit)), False)) return result def create_token(self, token_string, source, in_tag): token = super(DebugLexer, self).create_token(token_string, in_tag) token.source = self.origin, source return token class DebugParser(Parser): def __init__(self, lexer): super(DebugParser, self).__init__(lexer) self.command_stack = [] def enter_command(self, command, token): self.command_stack.append( (command, token.source) ) def exit_command(self): self.command_stack.pop() def error(self, token, msg): return self.source_error(token.source, msg) def source_error(self, source,msg): e = TemplateSyntaxError(msg) e.source = source return e def create_nodelist(self): return DebugNodeList() def create_variable_node(self, contents): return DebugVariableNode(contents) def extend_nodelist(self, nodelist, node, token): node.source = token.source super(DebugParser, self).extend_nodelist(nodelist, node, token) def unclosed_block_tag(self, parse_until): command, source = self.command_stack.pop() msg = "Unclosed tag '%s'. Looking for one of: %s " % (command, ', '.join(parse_until)) raise self.source_error(source, msg) def compile_function_error(self, token, e): if not hasattr(e, 'source'): e.source = token.source class DebugNodeList(NodeList): def render_node(self, node, context): try: result = node.render(context) except TemplateSyntaxError, e: if not hasattr(e, 'source'): e.source = node.source raise except Exception, e: from sys import exc_info wrapped = TemplateSyntaxError(u'Caught %s while rendering: %s' % (e.__class__.__name__, force_unicode(e, errors='replace'))) wrapped.source = node.source wrapped.exc_info = exc_info() raise wrapped, None, wrapped.exc_info[2] return result class DebugVariableNode(VariableNode): def render(self, context): try: output = self.filter_expression.resolve(context) output = localize(output, use_l10n=context.use_l10n) output = force_unicode(output) except TemplateSyntaxError, e: if not hasattr(e, 'source'): e.source = self.source raise except UnicodeDecodeError: return '' if (context.autoescape and not isinstance(output, SafeData)) or isinstance(output, EscapeData): return escape(output) else: return output
3,797
Python
.py
87
34.609195
104
0.637618
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,857
smartif.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/template/smartif.py
""" Parser and utilities for the smart 'if' tag """ import operator # Using a simple top down parser, as described here: # http://effbot.org/zone/simple-top-down-parsing.htm. # 'led' = left denotation # 'nud' = null denotation # 'bp' = binding power (left = lbp, right = rbp) class TokenBase(object): """ Base class for operators and literals, mainly for debugging and for throwing syntax errors. """ id = None # node/token type name value = None # used by literals first = second = None # used by tree nodes def nud(self, parser): # Null denotation - called in prefix context raise parser.error_class( "Not expecting '%s' in this position in if tag." % self.id ) def led(self, left, parser): # Left denotation - called in infix context raise parser.error_class( "Not expecting '%s' as infix operator in if tag." % self.id ) def display(self): """ Returns what to display in error messages for this node """ return self.id def __repr__(self): out = [str(x) for x in [self.id, self.first, self.second] if x is not None] return "(" + " ".join(out) + ")" def infix(bp, func): """ Creates an infix operator, given a binding power and a function that evaluates the node """ class Operator(TokenBase): lbp = bp def led(self, left, parser): self.first = left self.second = parser.expression(bp) return self def eval(self, context): try: return func(context, self.first, self.second) except Exception: # Templates shouldn't throw exceptions when rendering. We are # most likely to get exceptions for things like {% if foo in bar # %} where 'bar' does not support 'in', so default to False return False return Operator def prefix(bp, func): """ Creates a prefix operator, given a binding power and a function that evaluates the node. """ class Operator(TokenBase): lbp = bp def nud(self, parser): self.first = parser.expression(bp) self.second = None return self def eval(self, context): try: return func(context, self.first) except Exception: return False return Operator # Operator precedence follows Python. # NB - we can get slightly more accurate syntax error messages by not using the # same object for '==' and '='. # We defer variable evaluation to the lambda to ensure that terms are # lazily evaluated using Python's boolean parsing logic. OPERATORS = { 'or': infix(6, lambda context, x, y: x.eval(context) or y.eval(context)), 'and': infix(7, lambda context, x, y: x.eval(context) and y.eval(context)), 'not': prefix(8, lambda context, x: not x.eval(context)), 'in': infix(9, lambda context, x, y: x.eval(context) in y.eval(context)), 'not in': infix(9, lambda context, x, y: x.eval(context) not in y.eval(context)), '=': infix(10, lambda context, x, y: x.eval(context) == y.eval(context)), '==': infix(10, lambda context, x, y: x.eval(context) == y.eval(context)), '!=': infix(10, lambda context, x, y: x.eval(context) != y.eval(context)), '>': infix(10, lambda context, x, y: x.eval(context) > y.eval(context)), '>=': infix(10, lambda context, x, y: x.eval(context) >= y.eval(context)), '<': infix(10, lambda context, x, y: x.eval(context) < y.eval(context)), '<=': infix(10, lambda context, x, y: x.eval(context) <= y.eval(context)), } # Assign 'id' to each: for key, op in OPERATORS.items(): op.id = key class Literal(TokenBase): """ A basic self-resolvable object similar to a Django template variable. """ # IfParser uses Literal in create_var, but TemplateIfParser overrides # create_var so that a proper implementation that actually resolves # variables, filters etc is used. id = "literal" lbp = 0 def __init__(self, value): self.value = value def display(self): return repr(self.value) def nud(self, parser): return self def eval(self, context): return self.value def __repr__(self): return "(%s %r)" % (self.id, self.value) class EndToken(TokenBase): lbp = 0 def nud(self, parser): raise parser.error_class("Unexpected end of expression in if tag.") EndToken = EndToken() class IfParser(object): error_class = ValueError def __init__(self, tokens): # pre-pass necessary to turn 'not','in' into single token l = len(tokens) mapped_tokens = [] i = 0 while i < l: token = tokens[i] if token == "not" and i + 1 < l and tokens[i+1] == "in": token = "not in" i += 1 # skip 'in' mapped_tokens.append(self.translate_token(token)) i += 1 self.tokens = mapped_tokens self.pos = 0 self.current_token = self.next() def translate_token(self, token): try: op = OPERATORS[token] except (KeyError, TypeError): return self.create_var(token) else: return op() def next(self): if self.pos >= len(self.tokens): return EndToken else: retval = self.tokens[self.pos] self.pos += 1 return retval def parse(self): retval = self.expression() # Check that we have exhausted all the tokens if self.current_token is not EndToken: raise self.error_class("Unused '%s' at end of if expression." % self.current_token.display()) return retval def expression(self, rbp=0): t = self.current_token self.current_token = self.next() left = t.nud(self) while rbp < self.current_token.lbp: t = self.current_token self.current_token = self.next() left = t.led(left, self) return left def create_var(self, value): return Literal(value)
6,261
Python
.py
167
29.60479
85
0.598018
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,858
defaultfilters.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/template/defaultfilters.py
"""Default variable filters.""" import re from decimal import Decimal, InvalidOperation, ROUND_HALF_UP import random as random_module try: from functools import wraps except ImportError: from django.utils.functional import wraps # Python 2.4 fallback. from django.template.base import Variable, Library from django.conf import settings from django.utils import formats from django.utils.encoding import force_unicode, iri_to_uri from django.utils.html import conditional_escape from django.utils.safestring import mark_safe, SafeData from django.utils.translation import ugettext, ungettext register = Library() ####################### # STRING DECORATOR # ####################### def stringfilter(func): """ Decorator for filters which should only receive unicode objects. The object passed as the first positional argument will be converted to a unicode object. """ def _dec(*args, **kwargs): if args: args = list(args) args[0] = force_unicode(args[0]) if isinstance(args[0], SafeData) and getattr(func, 'is_safe', False): return mark_safe(func(*args, **kwargs)) return func(*args, **kwargs) # Include a reference to the real function (used to check original # arguments by the template parser). _dec._decorated_function = getattr(func, '_decorated_function', func) for attr in ('is_safe', 'needs_autoescape'): if hasattr(func, attr): setattr(_dec, attr, getattr(func, attr)) return wraps(func)(_dec) ################### # STRINGS # ################### def addslashes(value): """ Adds slashes before quotes. Useful for escaping strings in CSV, for example. Less useful for escaping JavaScript; use the ``escapejs`` filter instead. """ return value.replace('\\', '\\\\').replace('"', '\\"').replace("'", "\\'") addslashes.is_safe = True addslashes = stringfilter(addslashes) def capfirst(value): """Capitalizes the first character of the value.""" return value and value[0].upper() + value[1:] capfirst.is_safe=True capfirst = stringfilter(capfirst) def escapejs(value): """Hex encodes characters for use in JavaScript strings.""" from django.utils.html import escapejs return escapejs(value) escapejs = stringfilter(escapejs) def fix_ampersands(value): """Replaces ampersands with ``&amp;`` entities.""" from django.utils.html import fix_ampersands return fix_ampersands(value) fix_ampersands.is_safe=True fix_ampersands = stringfilter(fix_ampersands) # Values for testing floatformat input against infinity and NaN representations, # which differ across platforms and Python versions. Some (i.e. old Windows # ones) are not recognized by Decimal but we want to return them unchanged vs. # returning an empty string as we do for completley invalid input. Note these # need to be built up from values that are not inf/nan, since inf/nan values do # not reload properly from .pyc files on Windows prior to some level of Python 2.5 # (see Python Issue757815 and Issue1080440). pos_inf = 1e200 * 1e200 neg_inf = -1e200 * 1e200 nan = (1e200 * 1e200) / (1e200 * 1e200) special_floats = [str(pos_inf), str(neg_inf), str(nan)] def floatformat(text, arg=-1): """ Displays a float to a specified number of decimal places. If called without an argument, it displays the floating point number with one decimal place -- but only if there's a decimal place to be displayed: * num1 = 34.23234 * num2 = 34.00000 * num3 = 34.26000 * {{ num1|floatformat }} displays "34.2" * {{ num2|floatformat }} displays "34" * {{ num3|floatformat }} displays "34.3" If arg is positive, it will always display exactly arg number of decimal places: * {{ num1|floatformat:3 }} displays "34.232" * {{ num2|floatformat:3 }} displays "34.000" * {{ num3|floatformat:3 }} displays "34.260" If arg is negative, it will display arg number of decimal places -- but only if there are places to be displayed: * {{ num1|floatformat:"-3" }} displays "34.232" * {{ num2|floatformat:"-3" }} displays "34" * {{ num3|floatformat:"-3" }} displays "34.260" If the input float is infinity or NaN, the (platform-dependent) string representation of that value will be displayed. """ try: input_val = force_unicode(text) d = Decimal(input_val) except UnicodeEncodeError: return u'' except InvalidOperation: if input_val in special_floats: return input_val try: d = Decimal(force_unicode(float(text))) except (ValueError, InvalidOperation, TypeError, UnicodeEncodeError): return u'' try: p = int(arg) except ValueError: return input_val try: m = int(d) - d except (ValueError, OverflowError, InvalidOperation): return input_val if not m and p < 0: return mark_safe(formats.number_format(u'%d' % (int(d)), 0)) if p == 0: exp = Decimal(1) else: exp = Decimal(u'1.0') / (Decimal(10) ** abs(p)) try: # Avoid conversion to scientific notation by accessing `sign`, `digits` # and `exponent` from `Decimal.as_tuple()` directly. sign, digits, exponent = d.quantize(exp, ROUND_HALF_UP).as_tuple() digits = [unicode(digit) for digit in reversed(digits)] while len(digits) <= abs(exponent): digits.append(u'0') digits.insert(-exponent, u'.') if sign: digits.append(u'-') number = u''.join(reversed(digits)) return mark_safe(formats.number_format(number, abs(p))) except InvalidOperation: return input_val floatformat.is_safe = True def iriencode(value): """Escapes an IRI value for use in a URL.""" return force_unicode(iri_to_uri(value)) iriencode.is_safe = True iriencode = stringfilter(iriencode) def linenumbers(value, autoescape=None): """Displays text with line numbers.""" from django.utils.html import escape lines = value.split(u'\n') # Find the maximum width of the line count, for use with zero padding # string format command width = unicode(len(unicode(len(lines)))) if not autoescape or isinstance(value, SafeData): for i, line in enumerate(lines): lines[i] = (u"%0" + width + u"d. %s") % (i + 1, line) else: for i, line in enumerate(lines): lines[i] = (u"%0" + width + u"d. %s") % (i + 1, escape(line)) return mark_safe(u'\n'.join(lines)) linenumbers.is_safe = True linenumbers.needs_autoescape = True linenumbers = stringfilter(linenumbers) def lower(value): """Converts a string into all lowercase.""" return value.lower() lower.is_safe = True lower = stringfilter(lower) def make_list(value): """ Returns the value turned into a list. For an integer, it's a list of digits. For a string, it's a list of characters. """ return list(value) make_list.is_safe = False make_list = stringfilter(make_list) def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. """ import unicodedata value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore') value = unicode(re.sub('[^\w\s-]', '', value).strip().lower()) return mark_safe(re.sub('[-\s]+', '-', value)) slugify.is_safe = True slugify = stringfilter(slugify) def stringformat(value, arg): """ Formats the variable according to the arg, a string formatting specifier. This specifier uses Python string formating syntax, with the exception that the leading "%" is dropped. See http://docs.python.org/lib/typesseq-strings.html for documentation of Python string formatting """ try: return (u"%" + unicode(arg)) % value except (ValueError, TypeError): return u"" stringformat.is_safe = True def title(value): """Converts a string into titlecase.""" t = re.sub("([a-z])'([A-Z])", lambda m: m.group(0).lower(), value.title()) return re.sub("\d([A-Z])", lambda m: m.group(0).lower(), t) title.is_safe = True title = stringfilter(title) def truncatewords(value, arg): """ Truncates a string after a certain number of words. Argument: Number of words to truncate after. Newlines within the string are removed. """ from django.utils.text import truncate_words try: length = int(arg) except ValueError: # Invalid literal for int(). return value # Fail silently. return truncate_words(value, length) truncatewords.is_safe = True truncatewords = stringfilter(truncatewords) def truncatewords_html(value, arg): """ Truncates HTML after a certain number of words. Argument: Number of words to truncate after. Newlines in the HTML are preserved. """ from django.utils.text import truncate_html_words try: length = int(arg) except ValueError: # invalid literal for int() return value # Fail silently. return truncate_html_words(value, length) truncatewords_html.is_safe = True truncatewords_html = stringfilter(truncatewords_html) def upper(value): """Converts a string into all uppercase.""" return value.upper() upper.is_safe = False upper = stringfilter(upper) def urlencode(value, safe=None): """ Escapes a value for use in a URL. Takes an optional ``safe`` parameter used to determine the characters which should not be escaped by Django's ``urlquote`` method. If not provided, the default safe characters will be used (but an empty string can be provided when *all* characters should be escaped). """ from django.utils.http import urlquote kwargs = {} if safe is not None: kwargs['safe'] = safe return urlquote(value, **kwargs) urlencode.is_safe = False urlencode = stringfilter(urlencode) def urlize(value, autoescape=None): """Converts URLs in plain text into clickable links.""" from django.utils.html import urlize return mark_safe(urlize(value, nofollow=True, autoescape=autoescape)) urlize.is_safe=True urlize.needs_autoescape = True urlize = stringfilter(urlize) def urlizetrunc(value, limit, autoescape=None): """ Converts URLs into clickable links, truncating URLs to the given character limit, and adding 'rel=nofollow' attribute to discourage spamming. Argument: Length to truncate URLs to. """ from django.utils.html import urlize return mark_safe(urlize(value, trim_url_limit=int(limit), nofollow=True, autoescape=autoescape)) urlizetrunc.is_safe = True urlizetrunc.needs_autoescape = True urlizetrunc = stringfilter(urlizetrunc) def wordcount(value): """Returns the number of words.""" return len(value.split()) wordcount.is_safe = False wordcount = stringfilter(wordcount) def wordwrap(value, arg): """ Wraps words at specified line length. Argument: number of characters to wrap the text at. """ from django.utils.text import wrap return wrap(value, int(arg)) wordwrap.is_safe = True wordwrap = stringfilter(wordwrap) def ljust(value, arg): """ Left-aligns the value in a field of a given width. Argument: field size. """ return value.ljust(int(arg)) ljust.is_safe = True ljust = stringfilter(ljust) def rjust(value, arg): """ Right-aligns the value in a field of a given width. Argument: field size. """ return value.rjust(int(arg)) rjust.is_safe = True rjust = stringfilter(rjust) def center(value, arg): """Centers the value in a field of a given width.""" return value.center(int(arg)) center.is_safe = True center = stringfilter(center) def cut(value, arg): """ Removes all values of arg from the given string. """ safe = isinstance(value, SafeData) value = value.replace(arg, u'') if safe and arg != ';': return mark_safe(value) return value cut = stringfilter(cut) ################### # HTML STRINGS # ################### def escape(value): """ Marks the value as a string that should not be auto-escaped. """ from django.utils.safestring import mark_for_escaping return mark_for_escaping(value) escape.is_safe = True escape = stringfilter(escape) def force_escape(value): """ Escapes a string's HTML. This returns a new string containing the escaped characters (as opposed to "escape", which marks the content for later possible escaping). """ from django.utils.html import escape return mark_safe(escape(value)) force_escape = stringfilter(force_escape) force_escape.is_safe = True def linebreaks(value, autoescape=None): """ Replaces line breaks in plain text with appropriate HTML; a single newline becomes an HTML line break (``<br />``) and a new line followed by a blank line becomes a paragraph break (``</p>``). """ from django.utils.html import linebreaks autoescape = autoescape and not isinstance(value, SafeData) return mark_safe(linebreaks(value, autoescape)) linebreaks.is_safe = True linebreaks.needs_autoescape = True linebreaks = stringfilter(linebreaks) def linebreaksbr(value, autoescape=None): """ Converts all newlines in a piece of plain text to HTML line breaks (``<br />``). """ if autoescape and not isinstance(value, SafeData): from django.utils.html import escape value = escape(value) return mark_safe(value.replace('\n', '<br />')) linebreaksbr.is_safe = True linebreaksbr.needs_autoescape = True linebreaksbr = stringfilter(linebreaksbr) def safe(value): """ Marks the value as a string that should not be auto-escaped. """ return mark_safe(value) safe.is_safe = True safe = stringfilter(safe) def safeseq(value): """ A "safe" filter for sequences. Marks each element in the sequence, individually, as safe, after converting them to unicode. Returns a list with the results. """ return [mark_safe(force_unicode(obj)) for obj in value] safeseq.is_safe = True def removetags(value, tags): """Removes a space separated list of [X]HTML tags from the output.""" tags = [re.escape(tag) for tag in tags.split()] tags_re = u'(%s)' % u'|'.join(tags) starttag_re = re.compile(ur'<%s(/?>|(\s+[^>]*>))' % tags_re, re.U) endtag_re = re.compile(u'</%s>' % tags_re) value = starttag_re.sub(u'', value) value = endtag_re.sub(u'', value) return value removetags.is_safe = True removetags = stringfilter(removetags) def striptags(value): """Strips all [X]HTML tags.""" from django.utils.html import strip_tags return strip_tags(value) striptags.is_safe = True striptags = stringfilter(striptags) ################### # LISTS # ################### def dictsort(value, arg): """ Takes a list of dicts, returns that list sorted by the property given in the argument. """ return sorted(value, key=Variable(arg).resolve) dictsort.is_safe = False def dictsortreversed(value, arg): """ Takes a list of dicts, returns that list sorted in reverse order by the property given in the argument. """ return sorted(value, key=Variable(arg).resolve, reverse=True) dictsortreversed.is_safe = False def first(value): """Returns the first item in a list.""" try: return value[0] except IndexError: return u'' first.is_safe = False def join(value, arg, autoescape=None): """ Joins a list with a string, like Python's ``str.join(list)``. """ value = map(force_unicode, value) if autoescape: value = [conditional_escape(v) for v in value] try: data = conditional_escape(arg).join(value) except AttributeError: # fail silently but nicely return value return mark_safe(data) join.is_safe = True join.needs_autoescape = True def last(value): "Returns the last item in a list" try: return value[-1] except IndexError: return u'' last.is_safe = True def length(value): """Returns the length of the value - useful for lists.""" try: return len(value) except (ValueError, TypeError): return '' length.is_safe = True def length_is(value, arg): """Returns a boolean of whether the value's length is the argument.""" try: return len(value) == int(arg) except (ValueError, TypeError): return '' length_is.is_safe = False def random(value): """Returns a random item from the list.""" return random_module.choice(value) random.is_safe = True def slice_(value, arg): """ Returns a slice of the list. Uses the same syntax as Python's list slicing; see http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice for an introduction. """ try: bits = [] for x in arg.split(u':'): if len(x) == 0: bits.append(None) else: bits.append(int(x)) return value[slice(*bits)] except (ValueError, TypeError): return value # Fail silently. slice_.is_safe = True def unordered_list(value, autoescape=None): """ Recursively takes a self-nested list and returns an HTML unordered list -- WITHOUT opening and closing <ul> tags. The list is assumed to be in the proper format. For example, if ``var`` contains: ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then ``{{ var|unordered_list }}`` would return:: <li>States <ul> <li>Kansas <ul> <li>Lawrence</li> <li>Topeka</li> </ul> </li> <li>Illinois</li> </ul> </li> """ if autoescape: from django.utils.html import conditional_escape escaper = conditional_escape else: escaper = lambda x: x def convert_old_style_list(list_): """ Converts old style lists to the new easier to understand format. The old list format looked like: ['Item 1', [['Item 1.1', []], ['Item 1.2', []]] And it is converted to: ['Item 1', ['Item 1.1', 'Item 1.2]] """ if not isinstance(list_, (tuple, list)) or len(list_) != 2: return list_, False first_item, second_item = list_ if second_item == []: return [first_item], True try: it = iter(second_item) # see if second item is iterable except TypeError: return list_, False old_style_list = True new_second_item = [] for sublist in second_item: item, old_style_list = convert_old_style_list(sublist) if not old_style_list: break new_second_item.extend(item) if old_style_list: second_item = new_second_item return [first_item, second_item], old_style_list def _helper(list_, tabs=1): indent = u'\t' * tabs output = [] list_length = len(list_) i = 0 while i < list_length: title = list_[i] sublist = '' sublist_item = None if isinstance(title, (list, tuple)): sublist_item = title title = '' elif i < list_length - 1: next_item = list_[i+1] if next_item and isinstance(next_item, (list, tuple)): # The next item is a sub-list. sublist_item = next_item # We've processed the next item now too. i += 1 if sublist_item: sublist = _helper(sublist_item, tabs+1) sublist = '\n%s<ul>\n%s\n%s</ul>\n%s' % (indent, sublist, indent, indent) output.append('%s<li>%s%s</li>' % (indent, escaper(force_unicode(title)), sublist)) i += 1 return '\n'.join(output) value, converted = convert_old_style_list(value) return mark_safe(_helper(value)) unordered_list.is_safe = True unordered_list.needs_autoescape = True ################### # INTEGERS # ################### def add(value, arg): """Adds the arg to the value.""" try: return int(value) + int(arg) except (ValueError, TypeError): try: return value + arg except: return value add.is_safe = False def get_digit(value, arg): """ Given a whole number, returns the requested digit of it, where 1 is the right-most digit, 2 is the second-right-most digit, etc. Returns the original value for invalid input (if input or argument is not an integer, or if argument is less than 1). Otherwise, output is always an integer. """ try: arg = int(arg) value = int(value) except ValueError: return value # Fail silently for an invalid argument if arg < 1: return value try: return int(str(value)[-arg]) except IndexError: return 0 get_digit.is_safe = False ################### # DATES # ################### def date(value, arg=None): """Formats a date according to the given format.""" from django.utils.dateformat import format if not value: return u'' if arg is None: arg = settings.DATE_FORMAT try: return formats.date_format(value, arg) except AttributeError: try: return format(value, arg) except AttributeError: return '' date.is_safe = False def time(value, arg=None): """Formats a time according to the given format.""" from django.utils import dateformat if value in (None, u''): return u'' if arg is None: arg = settings.TIME_FORMAT try: return formats.time_format(value, arg) except AttributeError: try: return dateformat.time_format(value, arg) except AttributeError: return '' time.is_safe = False def timesince(value, arg=None): """Formats a date as the time since that date (i.e. "4 days, 6 hours").""" from django.utils.timesince import timesince if not value: return u'' try: if arg: return timesince(value, arg) return timesince(value) except (ValueError, TypeError): return u'' timesince.is_safe = False def timeuntil(value, arg=None): """Formats a date as the time until that date (i.e. "4 days, 6 hours").""" from django.utils.timesince import timeuntil if not value: return u'' try: return timeuntil(value, arg) except (ValueError, TypeError): return u'' timeuntil.is_safe = False ################### # LOGIC # ################### def default(value, arg): """If value is unavailable, use given default.""" return value or arg default.is_safe = False def default_if_none(value, arg): """If value is None, use given default.""" if value is None: return arg return value default_if_none.is_safe = False def divisibleby(value, arg): """Returns True if the value is devisible by the argument.""" return int(value) % int(arg) == 0 divisibleby.is_safe = False def yesno(value, arg=None): """ Given a string mapping values for true, false and (optionally) None, returns one of those strings accoding to the value: ========== ====================== ================================== Value Argument Outputs ========== ====================== ================================== ``True`` ``"yeah,no,maybe"`` ``yeah`` ``False`` ``"yeah,no,maybe"`` ``no`` ``None`` ``"yeah,no,maybe"`` ``maybe`` ``None`` ``"yeah,no"`` ``"no"`` (converts None to False if no mapping for None is given. ========== ====================== ================================== """ if arg is None: arg = ugettext('yes,no,maybe') bits = arg.split(u',') if len(bits) < 2: return value # Invalid arg. try: yes, no, maybe = bits except ValueError: # Unpack list of wrong size (no "maybe" value provided). yes, no, maybe = bits[0], bits[1], bits[1] if value is None: return maybe if value: return yes return no yesno.is_safe = False ################### # MISC # ################### def filesizeformat(bytes): """ Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc). """ try: bytes = float(bytes) except (TypeError,ValueError,UnicodeDecodeError): return ungettext("%(size)d byte", "%(size)d bytes", 0) % {'size': 0} filesize_number_format = lambda value: formats.number_format(round(value, 1), 1) if bytes < 1024: return ungettext("%(size)d byte", "%(size)d bytes", bytes) % {'size': bytes} if bytes < 1024 * 1024: return ugettext("%s KB") % filesize_number_format(bytes / 1024) if bytes < 1024 * 1024 * 1024: return ugettext("%s MB") % filesize_number_format(bytes / (1024 * 1024)) if bytes < 1024 * 1024 * 1024 * 1024: return ugettext("%s GB") % filesize_number_format(bytes / (1024 * 1024 * 1024)) if bytes < 1024 * 1024 * 1024 * 1024 * 1024: return ugettext("%s TB") % filesize_number_format(bytes / (1024 * 1024 * 1024 * 1024)) return ugettext("%s PB") % filesize_number_format(bytes / (1024 * 1024 * 1024 * 1024 * 1024)) filesizeformat.is_safe = True def pluralize(value, arg=u's'): """ Returns a plural suffix if the value is not 1. By default, 's' is used as the suffix: * If value is 0, vote{{ value|pluralize }} displays "0 votes". * If value is 1, vote{{ value|pluralize }} displays "1 vote". * If value is 2, vote{{ value|pluralize }} displays "2 votes". If an argument is provided, that string is used instead: * If value is 0, class{{ value|pluralize:"es" }} displays "0 classes". * If value is 1, class{{ value|pluralize:"es" }} displays "1 class". * If value is 2, class{{ value|pluralize:"es" }} displays "2 classes". If the provided argument contains a comma, the text before the comma is used for the singular case and the text after the comma is used for the plural case: * If value is 0, cand{{ value|pluralize:"y,ies" }} displays "0 candies". * If value is 1, cand{{ value|pluralize:"y,ies" }} displays "1 candy". * If value is 2, cand{{ value|pluralize:"y,ies" }} displays "2 candies". """ if not u',' in arg: arg = u',' + arg bits = arg.split(u',') if len(bits) > 2: return u'' singular_suffix, plural_suffix = bits[:2] try: if int(value) != 1: return plural_suffix except ValueError: # Invalid string that's not a number. pass except TypeError: # Value isn't a string or a number; maybe it's a list? try: if len(value) != 1: return plural_suffix except TypeError: # len() of unsized object. pass return singular_suffix pluralize.is_safe = False def phone2numeric(value): """Takes a phone number and converts it in to its numerical equivalent.""" from django.utils.text import phone2numeric return phone2numeric(value) phone2numeric.is_safe = True def pprint(value): """A wrapper around pprint.pprint -- for debugging, really.""" from pprint import pformat try: return pformat(value) except Exception, e: return u"Error in formatting: %s" % force_unicode(e, errors="replace") pprint.is_safe = True # Syntax: register.filter(name of filter, callback) register.filter(add) register.filter(addslashes) register.filter(capfirst) register.filter(center) register.filter(cut) register.filter(date) register.filter(default) register.filter(default_if_none) register.filter(dictsort) register.filter(dictsortreversed) register.filter(divisibleby) register.filter(escape) register.filter(escapejs) register.filter(filesizeformat) register.filter(first) register.filter(fix_ampersands) register.filter(floatformat) register.filter(force_escape) register.filter(get_digit) register.filter(iriencode) register.filter(join) register.filter(last) register.filter(length) register.filter(length_is) register.filter(linebreaks) register.filter(linebreaksbr) register.filter(linenumbers) register.filter(ljust) register.filter(lower) register.filter(make_list) register.filter(phone2numeric) register.filter(pluralize) register.filter(pprint) register.filter(removetags) register.filter(random) register.filter(rjust) register.filter(safe) register.filter(safeseq) register.filter('slice', slice_) register.filter(slugify) register.filter(stringformat) register.filter(striptags) register.filter(time) register.filter(timesince) register.filter(timeuntil) register.filter(title) register.filter(truncatewords) register.filter(truncatewords_html) register.filter(unordered_list) register.filter(upper) register.filter(urlencode) register.filter(urlize) register.filter(urlizetrunc) register.filter(wordcount) register.filter(wordwrap) register.filter(yesno)
29,467
Python
.py
827
30.182588
97
0.647354
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,859
filesystem.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/template/loaders/filesystem.py
""" Wrapper for loading templates from the filesystem. """ from django.conf import settings from django.template.base import TemplateDoesNotExist from django.template.loader import BaseLoader from django.utils._os import safe_join class Loader(BaseLoader): is_usable = True def get_template_sources(self, template_name, template_dirs=None): """ Returns the absolute paths to "template_name", when appended to each directory in "template_dirs". Any paths that don't lie inside one of the template dirs are excluded from the result set, for security reasons. """ if not template_dirs: template_dirs = settings.TEMPLATE_DIRS for template_dir in template_dirs: try: yield safe_join(template_dir, template_name) except UnicodeDecodeError: # The template dir name was a bytestring that wasn't valid UTF-8. raise except ValueError: # The joined path was located outside of this particular # template_dir (it might be inside another one, so this isn't # fatal). pass def load_template_source(self, template_name, template_dirs=None): tried = [] for filepath in self.get_template_sources(template_name, template_dirs): try: file = open(filepath) try: return (file.read().decode(settings.FILE_CHARSET), filepath) finally: file.close() except IOError: tried.append(filepath) if tried: error_msg = "Tried %s" % tried else: error_msg = "Your TEMPLATE_DIRS setting is empty. Change it to point to at least one template directory." raise TemplateDoesNotExist(error_msg) load_template_source.is_usable = True _loader = Loader() def load_template_source(template_name, template_dirs=None): # For backwards compatibility import warnings warnings.warn( "'django.template.loaders.filesystem.load_template_source' is deprecated; use 'django.template.loaders.filesystem.Loader' instead.", DeprecationWarning ) return _loader.load_template_source(template_name, template_dirs) load_template_source.is_usable = True
2,358
Python
.py
55
33.4
140
0.647366
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,860
app_directories.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/template/loaders/app_directories.py
""" Wrapper for loading templates from "templates" directories in INSTALLED_APPS packages. """ import os import sys from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.template.base import TemplateDoesNotExist from django.template.loader import BaseLoader from django.utils._os import safe_join from django.utils.importlib import import_module # At compile time, cache the directories to search. fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding() app_template_dirs = [] for app in settings.INSTALLED_APPS: try: mod = import_module(app) except ImportError, e: raise ImproperlyConfigured('ImportError %s: %s' % (app, e.args[0])) template_dir = os.path.join(os.path.dirname(mod.__file__), 'templates') if os.path.isdir(template_dir): app_template_dirs.append(template_dir.decode(fs_encoding)) # It won't change, so convert it to a tuple to save memory. app_template_dirs = tuple(app_template_dirs) class Loader(BaseLoader): is_usable = True def get_template_sources(self, template_name, template_dirs=None): """ Returns the absolute paths to "template_name", when appended to each directory in "template_dirs". Any paths that don't lie inside one of the template dirs are excluded from the result set, for security reasons. """ if not template_dirs: template_dirs = app_template_dirs for template_dir in template_dirs: try: yield safe_join(template_dir, template_name) except UnicodeDecodeError: # The template dir name was a bytestring that wasn't valid UTF-8. raise except ValueError: # The joined path was located outside of template_dir. pass def load_template_source(self, template_name, template_dirs=None): for filepath in self.get_template_sources(template_name, template_dirs): try: file = open(filepath) try: return (file.read().decode(settings.FILE_CHARSET), filepath) finally: file.close() except IOError: pass raise TemplateDoesNotExist(template_name) _loader = Loader() def load_template_source(template_name, template_dirs=None): # For backwards compatibility import warnings warnings.warn( "'django.template.loaders.app_directories.load_template_source' is deprecated; use 'django.template.loaders.app_directories.Loader' instead.", DeprecationWarning ) return _loader.load_template_source(template_name, template_dirs) load_template_source.is_usable = True
2,764
Python
.py
65
34.984615
150
0.685502
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,861
eggs.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/template/loaders/eggs.py
# Wrapper for loading templates from eggs via pkg_resources.resource_string. try: from pkg_resources import resource_string except ImportError: resource_string = None from django.template.base import TemplateDoesNotExist from django.template.loader import BaseLoader from django.conf import settings class Loader(BaseLoader): is_usable = resource_string is not None def load_template_source(self, template_name, template_dirs=None): """ Loads templates from Python eggs via pkg_resource.resource_string. For every installed app, it tries to get the resource (app, template_name). """ if resource_string is not None: pkg_name = 'templates/' + template_name for app in settings.INSTALLED_APPS: try: return (resource_string(app, pkg_name).decode(settings.FILE_CHARSET), 'egg:%s:%s' % (app, pkg_name)) except: pass raise TemplateDoesNotExist(template_name) _loader = Loader() def load_template_source(template_name, template_dirs=None): import warnings warnings.warn( "'django.template.loaders.eggs.load_template_source' is deprecated; use 'django.template.loaders.eggs.Loader' instead.", DeprecationWarning ) return _loader.load_template_source(template_name, template_dirs) load_template_source.is_usable = resource_string is not None
1,432
Python
.py
32
37.53125
128
0.702082
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,862
cached.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/template/loaders/cached.py
""" Wrapper class that takes a list of template loaders as an argument and attempts to load templates from them in order, caching the result. """ from django.core.exceptions import ImproperlyConfigured from django.template.base import TemplateDoesNotExist from django.template.loader import BaseLoader, get_template_from_string, find_template_loader, make_origin from django.utils.hashcompat import sha_constructor from django.utils.importlib import import_module class Loader(BaseLoader): is_usable = True def __init__(self, loaders): self.template_cache = {} self._loaders = loaders self._cached_loaders = [] @property def loaders(self): # Resolve loaders on demand to avoid circular imports if not self._cached_loaders: for loader in self._loaders: self._cached_loaders.append(find_template_loader(loader)) return self._cached_loaders def find_template(self, name, dirs=None): for loader in self.loaders: try: template, display_name = loader(name, dirs) return (template, make_origin(display_name, loader, name, dirs)) except TemplateDoesNotExist: pass raise TemplateDoesNotExist(name) def load_template(self, template_name, template_dirs=None): key = template_name if template_dirs: # If template directories were specified, use a hash to differentiate key = '-'.join([template_name, sha_constructor('|'.join(template_dirs)).hexdigest()]) if key not in self.template_cache: template, origin = self.find_template(template_name, template_dirs) if not hasattr(template, 'render'): try: template = get_template_from_string(template, origin, template_name) except TemplateDoesNotExist: # If compiling the template we found raises TemplateDoesNotExist, # back off to returning the source and display name for the template # we were asked to load. This allows for correct identification (later) # of the actual template that does not exist. return template, origin self.template_cache[key] = template return self.template_cache[key], None def reset(self): "Empty the template cache." self.template_cache.clear()
2,469
Python
.py
51
38.392157
106
0.656432
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,863
global_settings.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/global_settings.py
# Default Django settings. Override these with settings in the module # pointed-to by the DJANGO_SETTINGS_MODULE environment variable. # This is defined here as a do-nothing function because we can't import # django.utils.translation -- that module depends on the settings. gettext_noop = lambda s: s #################### # CORE # #################### DEBUG = False TEMPLATE_DEBUG = False # Whether the framework should propagate raw exceptions rather than catching # them. This is useful under some testing siutations and should never be used # on a live site. DEBUG_PROPAGATE_EXCEPTIONS = False # Whether to use the "Etag" header. This saves bandwidth but slows down performance. USE_ETAGS = False # People who get code error notifications. # In the format (('Full Name', '[email protected]'), ('Full Name', '[email protected]')) ADMINS = () # Tuple of IP addresses, as strings, that: # * See debug comments, when DEBUG is true # * Receive x-headers INTERNAL_IPS = () # Local time zone for this installation. All choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name (although not all # systems may support all possibilities). TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' # Languages we provide translations for, out of the box. The language name # should be the utf-8 encoded local name for the language. LANGUAGES = ( ('ar', gettext_noop('Arabic')), ('az', gettext_noop('Azerbaijani')), ('bg', gettext_noop('Bulgarian')), ('bn', gettext_noop('Bengali')), ('bs', gettext_noop('Bosnian')), ('ca', gettext_noop('Catalan')), ('cs', gettext_noop('Czech')), ('cy', gettext_noop('Welsh')), ('da', gettext_noop('Danish')), ('de', gettext_noop('German')), ('el', gettext_noop('Greek')), ('en', gettext_noop('English')), ('en-gb', gettext_noop('British English')), ('es', gettext_noop('Spanish')), ('es-ar', gettext_noop('Argentinian Spanish')), ('es-mx', gettext_noop('Mexican Spanish')), ('es-ni', gettext_noop('Nicaraguan Spanish')), ('et', gettext_noop('Estonian')), ('eu', gettext_noop('Basque')), ('fa', gettext_noop('Persian')), ('fi', gettext_noop('Finnish')), ('fr', gettext_noop('French')), ('fy-nl', gettext_noop('Frisian')), ('ga', gettext_noop('Irish')), ('gl', gettext_noop('Galician')), ('he', gettext_noop('Hebrew')), ('hi', gettext_noop('Hindi')), ('hr', gettext_noop('Croatian')), ('hu', gettext_noop('Hungarian')), ('id', gettext_noop('Indonesian')), ('is', gettext_noop('Icelandic')), ('it', gettext_noop('Italian')), ('ja', gettext_noop('Japanese')), ('ka', gettext_noop('Georgian')), ('km', gettext_noop('Khmer')), ('kn', gettext_noop('Kannada')), ('ko', gettext_noop('Korean')), ('lt', gettext_noop('Lithuanian')), ('lv', gettext_noop('Latvian')), ('mk', gettext_noop('Macedonian')), ('ml', gettext_noop('Malayalam')), ('mn', gettext_noop('Mongolian')), ('nl', gettext_noop('Dutch')), ('no', gettext_noop('Norwegian')), ('nb', gettext_noop('Norwegian Bokmal')), ('nn', gettext_noop('Norwegian Nynorsk')), ('pa', gettext_noop('Punjabi')), ('pl', gettext_noop('Polish')), ('pt', gettext_noop('Portuguese')), ('pt-br', gettext_noop('Brazilian Portuguese')), ('ro', gettext_noop('Romanian')), ('ru', gettext_noop('Russian')), ('sk', gettext_noop('Slovak')), ('sl', gettext_noop('Slovenian')), ('sq', gettext_noop('Albanian')), ('sr', gettext_noop('Serbian')), ('sr-latn', gettext_noop('Serbian Latin')), ('sv', gettext_noop('Swedish')), ('ta', gettext_noop('Tamil')), ('te', gettext_noop('Telugu')), ('th', gettext_noop('Thai')), ('tr', gettext_noop('Turkish')), ('uk', gettext_noop('Ukrainian')), ('ur', gettext_noop('Urdu')), ('vi', gettext_noop('Vietnamese')), ('zh-cn', gettext_noop('Simplified Chinese')), ('zh-tw', gettext_noop('Traditional Chinese')), ) # Languages using BiDi (right-to-left) layout LANGUAGES_BIDI = ("he", "ar", "fa") # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True LOCALE_PATHS = () LANGUAGE_COOKIE_NAME = 'django_language' # If you set this to True, Django will format dates, numbers and calendars # according to user current locale USE_L10N = False # Not-necessarily-technical managers of the site. They get broken link # notifications and other various e-mails. MANAGERS = ADMINS # Default content type and charset to use for all HttpResponse objects, if a # MIME type isn't manually specified. These are used to construct the # Content-Type header. DEFAULT_CONTENT_TYPE = 'text/html' DEFAULT_CHARSET = 'utf-8' # Encoding of files read from disk (template and initial SQL files). FILE_CHARSET = 'utf-8' # E-mail address that error messages come from. SERVER_EMAIL = 'root@localhost' # Whether to send broken-link e-mails. SEND_BROKEN_LINK_EMAILS = False # Database connection info. # Legacy format DATABASE_ENGINE = '' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = '' # Or path to database file if using sqlite3. DATABASE_USER = '' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. DATABASE_OPTIONS = {} # Set to empty dictionary for default. # New format DATABASES = { } # Classes used to implement db routing behaviour DATABASE_ROUTERS = [] # The email backend to use. For possible shortcuts see django.core.mail. # The default is to use the SMTP backend. # Third-party backends can be specified by providing a Python path # to a module that defines an EmailBackend class. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # Host for sending e-mail. EMAIL_HOST = 'localhost' # Port for sending e-mail. EMAIL_PORT = 25 # Optional SMTP authentication information for EMAIL_HOST. EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = False # List of strings representing installed apps. INSTALLED_APPS = () # List of locations of the template source files, in search order. TEMPLATE_DIRS = () # List of callables that know how to import templates from various sources. # See the comments in django/core/template/loader.py for interface # documentation. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) # List of processors used by RequestContext to populate the context. # Each one should be a callable that takes the request object as its # only parameter and returns a dictionary to add to the context. TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.static', # 'django.core.context_processors.request', 'django.contrib.messages.context_processors.messages', ) # Output to use in template system for invalid (e.g. misspelled) variables. TEMPLATE_STRING_IF_INVALID = '' # Default e-mail address to use for various automated correspondence from # the site managers. DEFAULT_FROM_EMAIL = 'webmaster@localhost' # Subject-line prefix for email messages send with django.core.mail.mail_admins # or ...mail_managers. Make sure to include the trailing space. EMAIL_SUBJECT_PREFIX = '[Django] ' # Whether to append trailing slashes to URLs. APPEND_SLASH = True # Whether to prepend the "www." subdomain to URLs that don't have it. PREPEND_WWW = False # Override the server-derived value of SCRIPT_NAME FORCE_SCRIPT_NAME = None # List of compiled regular expression objects representing User-Agent strings # that are not allowed to visit any page, systemwide. Use this for bad # robots/crawlers. Here are a few examples: # import re # DISALLOWED_USER_AGENTS = ( # re.compile(r'^NaverBot.*'), # re.compile(r'^EmailSiphon.*'), # re.compile(r'^SiteSucker.*'), # re.compile(r'^sohu-search') # ) DISALLOWED_USER_AGENTS = () ABSOLUTE_URL_OVERRIDES = {} # Tuple of strings representing allowed prefixes for the {% ssi %} tag. # Example: ('/home/html', '/var/www') ALLOWED_INCLUDE_ROOTS = () # If this is a admin settings module, this should be a list of # settings modules (in the format 'foo.bar.baz') for which this admin # is an admin. ADMIN_FOR = () # 404s that may be ignored. IGNORABLE_404_STARTS = ('/cgi-bin/', '/_vti_bin', '/_vti_inf') IGNORABLE_404_ENDS = ('mail.pl', 'mailform.pl', 'mail.cgi', 'mailform.cgi', 'favicon.ico', '.php') # A secret key for this particular Django installation. Used in secret-key # hashing algorithms. Set this in your settings, or Django will complain # loudly. SECRET_KEY = '' # Default file storage mechanism that holds media. DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage' # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. # Example: "http://media.lawrence.com/media/" MEDIA_URL = '' # Absolute path to the directory that holds static files. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = '' # URL that handles the static files served from STATIC_ROOT. # Example: "http://media.lawrence.com/static/" STATIC_URL = None # List of upload handler classes to be applied in order. FILE_UPLOAD_HANDLERS = ( 'django.core.files.uploadhandler.MemoryFileUploadHandler', 'django.core.files.uploadhandler.TemporaryFileUploadHandler', ) # Maximum size, in bytes, of a request before it will be streamed to the # file system instead of into memory. FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440 # i.e. 2.5 MB # Directory in which upload streamed files will be temporarily saved. A value of # `None` will make Django use the operating system's default temporary directory # (i.e. "/tmp" on *nix systems). FILE_UPLOAD_TEMP_DIR = None # The numeric mode to set newly-uploaded files to. The value should be a mode # you'd pass directly to os.chmod; see http://docs.python.org/lib/os-file-dir.html. FILE_UPLOAD_PERMISSIONS = None # Python module path where user will place custom format definition. # The directory where this setting is pointing should contain subdirectories # named as the locales, containing a formats.py file # (i.e. "myproject.locale" for myproject/locale/en/formats.py etc. use) FORMAT_MODULE_PATH = None # Default formatting for date objects. See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'N j, Y' # Default formatting for datetime objects. See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATETIME_FORMAT = 'N j, Y, P' # Default formatting for time objects. See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date TIME_FORMAT = 'P' # Default formatting for date objects when only the year and month are relevant. # See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date YEAR_MONTH_FORMAT = 'F Y' # Default formatting for date objects when only the month and day are relevant. # See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date MONTH_DAY_FORMAT = 'F j' # Default short formatting for date objects. See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date SHORT_DATE_FORMAT = 'm/d/Y' # Default short formatting for datetime objects. # See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date SHORT_DATETIME_FORMAT = 'm/d/Y P' # Default formats to be used when parsing dates from input boxes, in order # See all available format string here: # http://docs.python.org/library/datetime.html#strftime-behavior # * Note that these format strings are different from the ones to display dates DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06' '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006' '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006' '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006' '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' ) # Default formats to be used when parsing times from input boxes, in order # See all available format string here: # http://docs.python.org/library/datetime.html#strftime-behavior # * Note that these format strings are different from the ones to display dates TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) # Default formats to be used when parsing dates and times from input boxes, # in order # See all available format string here: # http://docs.python.org/library/datetime.html#strftime-behavior # * Note that these format strings are different from the ones to display dates DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' '%m/%d/%Y %H:%M', # '10/25/2006 14:30' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M', # '10/25/06 14:30' '%m/%d/%y', # '10/25/06' ) # First day of week, to be used on calendars # 0 means Sunday, 1 means Monday... FIRST_DAY_OF_WEEK = 0 # Decimal separator symbol DECIMAL_SEPARATOR = '.' # Boolean that sets whether to add thousand separator when formatting numbers USE_THOUSAND_SEPARATOR = False # Number of digits that will be together, when spliting them by # THOUSAND_SEPARATOR. 0 means no grouping, 3 means splitting by thousands... NUMBER_GROUPING = 0 # Thousand separator symbol THOUSAND_SEPARATOR = ',' # Do you want to manage transactions manually? # Hint: you really don't! TRANSACTIONS_MANAGED = False # The User-Agent string to use when checking for URL validity through the # isExistingURL validator. from django import get_version URL_VALIDATOR_USER_AGENT = "Django/%s (http://www.djangoproject.com)" % get_version() # The tablespaces to use for each model when not specified otherwise. DEFAULT_TABLESPACE = '' DEFAULT_INDEX_TABLESPACE = '' ############## # MIDDLEWARE # ############## # List of middleware classes to use. Order is important; in the request phase, # this middleware classes will be applied in the order given, and in the # response phase the middleware will be applied in reverse order. 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', # 'django.middleware.http.ConditionalGetMiddleware', # 'django.middleware.gzip.GZipMiddleware', ) ############ # SESSIONS # ############ SESSION_COOKIE_NAME = 'sessionid' # Cookie name. This can be whatever you want. SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2 # Age of cookie, in seconds (default: 2 weeks). SESSION_COOKIE_DOMAIN = None # A string like ".lawrence.com", or None for standard domain cookie. SESSION_COOKIE_SECURE = False # Whether the session cookie should be secure (https:// only). SESSION_COOKIE_PATH = '/' # The path of the session cookie. SESSION_COOKIE_HTTPONLY = False # Whether to use the non-RFC standard httpOnly flag (IE, FF3+, others) SESSION_SAVE_EVERY_REQUEST = False # Whether to save the session data on every request. SESSION_EXPIRE_AT_BROWSER_CLOSE = False # Whether a user's session cookie expires when the Web browser is closed. SESSION_ENGINE = 'django.contrib.sessions.backends.db' # The module to store session data SESSION_FILE_PATH = None # Directory to store session files if using the file session module. If None, the backend will use a sensible default. ######### # CACHE # ######### # New format CACHES = { } # The cache backend to use. See the docstring in django.core.cache for the # possible values. CACHE_MIDDLEWARE_KEY_PREFIX = '' CACHE_MIDDLEWARE_SECONDS = 600 CACHE_MIDDLEWARE_ALIAS = 'default' #################### # COMMENTS # #################### COMMENTS_ALLOW_PROFANITIES = False # The profanities that will trigger a validation error in the # 'hasNoProfanities' validator. All of these should be in lowercase. PROFANITIES_LIST = () # The group ID that designates which users are banned. # Set to None if you're not using it. COMMENTS_BANNED_USERS_GROUP = None # The group ID that designates which users can moderate comments. # Set to None if you're not using it. COMMENTS_MODERATORS_GROUP = None # The group ID that designates the users whose comments should be e-mailed to MANAGERS. # Set to None if you're not using it. COMMENTS_SKETCHY_USERS_GROUP = None # The system will e-mail MANAGERS the first COMMENTS_FIRST_FEW comments by each # user. Set this to 0 if you want to disable it. COMMENTS_FIRST_FEW = 0 # A tuple of IP addresses that have been banned from participating in various # Django-powered features. BANNED_IPS = () ################## # AUTHENTICATION # ################## AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',) LOGIN_URL = '/accounts/login/' LOGOUT_URL = '/accounts/logout/' LOGIN_REDIRECT_URL = '/accounts/profile/' # The number of days a password reset link is valid for PASSWORD_RESET_TIMEOUT_DAYS = 3 ######## # CSRF # ######## # Dotted path to callable to be used as view when a request is # rejected by the CSRF middleware. CSRF_FAILURE_VIEW = 'django.views.csrf.csrf_failure' # Name and domain for CSRF cookie. CSRF_COOKIE_NAME = 'csrftoken' CSRF_COOKIE_DOMAIN = None ############ # MESSAGES # ############ # Class to use as messges backend MESSAGE_STORAGE = 'django.contrib.messages.storage.user_messages.LegacyFallbackStorage' # Default values of MESSAGE_LEVEL and MESSAGE_TAGS are defined within # django.contrib.messages to avoid imports in this settings file. ########### # LOGGING # ########### # The callable to use to configure logging LOGGING_CONFIG = 'django.utils.log.dictConfig' # The default logging configuration. This sends an email to # the site admins on every HTTP 500 error. All other log # records are sent to the bit bucket. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } ########### # TESTING # ########### # The name of the class to use to run the test suite TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner' # The name of the database to use for testing purposes. # If None, a name of 'test_' + DATABASE_NAME will be assumed TEST_DATABASE_NAME = None # Strings used to set the character set and collation order for the test # database. These values are passed literally to the server, so they are # backend-dependent. If None, no special settings are sent (system defaults are # used). TEST_DATABASE_CHARSET = None TEST_DATABASE_COLLATION = None ############ # FIXTURES # ############ # The list of directories to search for fixtures FIXTURE_DIRS = () ############### # STATICFILES # ############### # A list of locations of additional static files STATICFILES_DIRS = () # The default file storage backend used during the build process STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # URL prefix for admin media -- CSS, JavaScript and images. # Make sure to use a trailing slash. # Examples: "http://foo.com/static/admin/", "/static/admin/". ADMIN_MEDIA_PREFIX = '/static/admin/'
21,089
Python
.py
479
41.722338
174
0.69982
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,864
__init__.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/__init__.py
""" Settings and configuration for Django. Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment variable, and then from django.conf.global_settings; see the global settings file for a list of all possible variables. """ import os import re import time # Needed for Windows import warnings from django.conf import global_settings from django.utils.functional import LazyObject from django.utils import importlib ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE" class LazySettings(LazyObject): """ A lazy proxy for either global Django settings or a custom settings object. The user can manually configure settings prior to using them. Otherwise, Django uses the settings module pointed to by DJANGO_SETTINGS_MODULE. """ def _setup(self): """ Load the settings module pointed to by the environment variable. This is used the first time we need any settings at all, if the user has not previously configured the settings manually. """ try: settings_module = os.environ[ENVIRONMENT_VARIABLE] if not settings_module: # If it's set but is an empty string. raise KeyError except KeyError: # NOTE: This is arguably an EnvironmentError, but that causes # problems with Python's interactive help. raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE) self._wrapped = Settings(settings_module) def configure(self, default_settings=global_settings, **options): """ Called to manually configure the settings. The 'default_settings' parameter sets where to retrieve any unspecified values from (its argument must support attribute access (__getattr__)). """ if self._wrapped != None: raise RuntimeError('Settings already configured.') holder = UserSettingsHolder(default_settings) for name, value in options.items(): setattr(holder, name, value) self._wrapped = holder def configured(self): """ Returns True if the settings have already been configured. """ return bool(self._wrapped) configured = property(configured) class BaseSettings(object): """ Common logic for settings whether set by a module or by the user. """ def __setattr__(self, name, value): if name in ("MEDIA_URL", "STATIC_URL") and value and not value.endswith('/'): warnings.warn('If set, %s must end with a slash' % name, PendingDeprecationWarning) object.__setattr__(self, name, value) class Settings(BaseSettings): def __init__(self, settings_module): # update this dict from global settings (but only for ALL_CAPS settings) for setting in dir(global_settings): if setting == setting.upper(): setattr(self, setting, getattr(global_settings, setting)) # store the settings module in case someone later cares self.SETTINGS_MODULE = settings_module try: mod = importlib.import_module(self.SETTINGS_MODULE) except ImportError, e: raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e)) # Settings that should be converted into tuples if they're mistakenly entered # as strings. tuple_settings = ("INSTALLED_APPS", "TEMPLATE_DIRS") for setting in dir(mod): if setting == setting.upper(): setting_value = getattr(mod, setting) if setting in tuple_settings and type(setting_value) == str: setting_value = (setting_value,) # In case the user forgot the comma. setattr(self, setting, setting_value) # Expand entries in INSTALLED_APPS like "django.contrib.*" to a list # of all those apps. new_installed_apps = [] for app in self.INSTALLED_APPS: if app.endswith('.*'): app_mod = importlib.import_module(app[:-2]) appdir = os.path.dirname(app_mod.__file__) app_subdirs = os.listdir(appdir) app_subdirs.sort() name_pattern = re.compile(r'[a-zA-Z]\w*') for d in app_subdirs: if name_pattern.match(d) and os.path.isdir(os.path.join(appdir, d)): new_installed_apps.append('%s.%s' % (app[:-2], d)) else: new_installed_apps.append(app) self.INSTALLED_APPS = new_installed_apps if hasattr(time, 'tzset') and self.TIME_ZONE: # When we can, attempt to validate the timezone. If we can't find # this file, no check happens and it's harmless. zoneinfo_root = '/usr/share/zoneinfo' if (os.path.exists(zoneinfo_root) and not os.path.exists(os.path.join(zoneinfo_root, *(self.TIME_ZONE.split('/'))))): raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE) # Move the time zone info into os.environ. See ticket #2315 for why # we don't do this unconditionally (breaks Windows). os.environ['TZ'] = self.TIME_ZONE time.tzset() # Settings are configured, so we can set up the logger if required if self.LOGGING_CONFIG: # First find the logging configuration function ... logging_config_path, logging_config_func_name = self.LOGGING_CONFIG.rsplit('.', 1) logging_config_module = importlib.import_module(logging_config_path) logging_config_func = getattr(logging_config_module, logging_config_func_name) # ... then invoke it with the logging settings logging_config_func(self.LOGGING) class UserSettingsHolder(BaseSettings): """ Holder for user configured settings. """ # SETTINGS_MODULE doesn't make much sense in the manually configured # (standalone) case. SETTINGS_MODULE = None def __init__(self, default_settings): """ Requests for configuration variables not in this class are satisfied from the module specified in default_settings (if possible). """ self.default_settings = default_settings def __getattr__(self, name): return getattr(self.default_settings, name) def __dir__(self): return self.__dict__.keys() + dir(self.default_settings) # For Python < 2.6: __members__ = property(lambda self: self.__dir__()) settings = LazySettings()
6,707
Python
.py
138
39.144928
130
0.641743
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,865
__init__.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/__init__.py
LANG_INFO = { 'ar': { 'bidi': True, 'code': 'ar', 'name': 'Arabic', 'name_local': u'\u0627\u0644\u0639\u0631\u0628\u064a\u0651\u0629', }, 'az': { 'bidi': True, 'code': 'az', 'name': 'Azerbaijani', 'name_local': u'az\u0259rbaycan dili', }, 'bg': { 'bidi': False, 'code': 'bg', 'name': 'Bulgarian', 'name_local': u'\u0431\u044a\u043b\u0433\u0430\u0440\u0441\u043a\u0438', }, 'bn': { 'bidi': False, 'code': 'bn', 'name': 'Bengali', 'name_local': u'\u09ac\u09be\u0982\u09b2\u09be', }, 'bs': { 'bidi': False, 'code': 'bs', 'name': 'Bosnian', 'name_local': u'bosanski', }, 'ca': { 'bidi': False, 'code': 'ca', 'name': 'Catalan', 'name_local': u'catal\xe0', }, 'cs': { 'bidi': False, 'code': 'cs', 'name': 'Czech', 'name_local': u'\u010desky', }, 'cy': { 'bidi': False, 'code': 'cy', 'name': 'Welsh', 'name_local': u'Cymraeg', }, 'da': { 'bidi': False, 'code': 'da', 'name': 'Danish', 'name_local': u'Dansk', }, 'de': { 'bidi': False, 'code': 'de', 'name': 'German', 'name_local': u'Deutsch', }, 'el': { 'bidi': False, 'code': 'el', 'name': 'Greek', 'name_local': u'\u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac', }, 'en': { 'bidi': False, 'code': 'en', 'name': 'English', 'name_local': u'English', }, 'en-gb': { 'bidi': False, 'code': 'en-gb', 'name': 'British English', 'name_local': u'British English', }, 'es': { 'bidi': False, 'code': 'es', 'name': 'Spanish', 'name_local': u'espa\xf1ol', }, 'es-ar': { 'bidi': False, 'code': 'es-ar', 'name': 'Argentinian Spanish', 'name_local': u'espa\xf1ol de Argentina', }, 'es-mx': { 'bidi': False, 'code': 'es-mx', 'name': 'Mexican Spanish', 'name_local': u'espa\xf1ol de Mexico', }, 'es-ni': { 'bidi': False, 'code': 'es-ni', 'name': 'Nicaraguan Spanish', 'name_local': u'espa\xf1ol de Nicaragua', }, 'et': { 'bidi': False, 'code': 'et', 'name': 'Estonian', 'name_local': u'eesti', }, 'eu': { 'bidi': False, 'code': 'eu', 'name': 'Basque', 'name_local': u'Basque', }, 'fa': { 'bidi': True, 'code': 'fa', 'name': 'Persian', 'name_local': u'\u0641\u0627\u0631\u0633\u06cc', }, 'fi': { 'bidi': False, 'code': 'fi', 'name': 'Finnish', 'name_local': u'suomi', }, 'fr': { 'bidi': False, 'code': 'fr', 'name': 'French', 'name_local': u'Fran\xe7ais', }, 'fy-nl': { 'bidi': False, 'code': 'fy-nl', 'name': 'Frisian', 'name_local': u'Frisian', }, 'ga': { 'bidi': False, 'code': 'ga', 'name': 'Irish', 'name_local': u'Gaeilge', }, 'gl': { 'bidi': False, 'code': 'gl', 'name': 'Galician', 'name_local': u'galego', }, 'he': { 'bidi': True, 'code': 'he', 'name': 'Hebrew', 'name_local': u'\u05e2\u05d1\u05e8\u05d9\u05ea', }, 'hi': { 'bidi': False, 'code': 'hi', 'name': 'Hindi', 'name_local': u'Hindi', }, 'hr': { 'bidi': False, 'code': 'hr', 'name': 'Croatian', 'name_local': u'Hrvatski', }, 'hu': { 'bidi': False, 'code': 'hu', 'name': 'Hungarian', 'name_local': u'Magyar', }, 'id': { 'bidi': False, 'code': 'id', 'name': 'Indonesian', 'name_local': u'Bahasa Indonesia', }, 'is': { 'bidi': False, 'code': 'is', 'name': 'Icelandic', 'name_local': u'\xcdslenska', }, 'it': { 'bidi': False, 'code': 'it', 'name': 'Italian', 'name_local': u'italiano', }, 'ja': { 'bidi': False, 'code': 'ja', 'name': 'Japanese', 'name_local': u'\u65e5\u672c\u8a9e', }, 'ka': { 'bidi': False, 'code': 'ka', 'name': 'Georgian', 'name_local': u'\u10e5\u10d0\u10e0\u10d7\u10e3\u10da\u10d8', }, 'km': { 'bidi': False, 'code': 'km', 'name': 'Khmer', 'name_local': u'Khmer', }, 'kn': { 'bidi': False, 'code': 'kn', 'name': 'Kannada', 'name_local': u'Kannada', }, 'ko': { 'bidi': False, 'code': 'ko', 'name': 'Korean', 'name_local': u'\ud55c\uad6d\uc5b4', }, 'lt': { 'bidi': False, 'code': 'lt', 'name': 'Lithuanian', 'name_local': u'Lithuanian', }, 'lv': { 'bidi': False, 'code': 'lv', 'name': 'Latvian', 'name_local': u'latvie\u0161u', }, 'mk': { 'bidi': False, 'code': 'mk', 'name': 'Macedonian', 'name_local': u'\u041c\u0430\u043a\u0435\u0434\u043e\u043d\u0441\u043a\u0438', }, 'ml': { 'bidi': False, 'code': 'ml', 'name': 'Malayalam', 'name_local': u'Malayalam', }, 'mn': { 'bidi': False, 'code': 'mn', 'name': 'Mongolian', 'name_local': u'Mongolian', }, 'nb': { 'bidi': False, 'code': 'nb', 'name': 'Norwegian Bokmal', 'name_local': u'Norsk (bokm\xe5l)', }, 'nl': { 'bidi': False, 'code': 'nl', 'name': 'Dutch', 'name_local': u'Nederlands', }, 'nn': { 'bidi': False, 'code': 'nn', 'name': 'Norwegian Nynorsk', 'name_local': u'Norsk (nynorsk)', }, 'no': { 'bidi': False, 'code': 'no', 'name': 'Norwegian', 'name_local': u'Norsk', }, 'pa': { 'bidi': False, 'code': 'pa', 'name': 'Punjabi', 'name_local': u'Punjabi', }, 'pl': { 'bidi': False, 'code': 'pl', 'name': 'Polish', 'name_local': u'polski', }, 'pt': { 'bidi': False, 'code': 'pt', 'name': 'Portuguese', 'name_local': u'Portugu\xeas', }, 'pt-br': { 'bidi': False, 'code': 'pt-br', 'name': 'Brazilian Portuguese', 'name_local': u'Portugu\xeas Brasileiro', }, 'ro': { 'bidi': False, 'code': 'ro', 'name': 'Romanian', 'name_local': u'Rom\xe2n\u0103', }, 'ru': { 'bidi': False, 'code': 'ru', 'name': 'Russian', 'name_local': u'\u0420\u0443\u0441\u0441\u043a\u0438\u0439', }, 'sk': { 'bidi': False, 'code': 'sk', 'name': 'Slovak', 'name_local': u'slovensk\xfd', }, 'sl': { 'bidi': False, 'code': 'sl', 'name': 'Slovenian', 'name_local': u'Sloven\u0161\u010dina', }, 'sq': { 'bidi': False, 'code': 'sq', 'name': 'Albanian', 'name_local': u'Albanian', }, 'sr': { 'bidi': False, 'code': 'sr', 'name': 'Serbian', 'name_local': u'\u0441\u0440\u043f\u0441\u043a\u0438', }, 'sr-latn': { 'bidi': False, 'code': 'sr-latn', 'name': 'Serbian Latin', 'name_local': u'srpski (latinica)', }, 'sv': { 'bidi': False, 'code': 'sv', 'name': 'Swedish', 'name_local': u'Svenska', }, 'ta': { 'bidi': False, 'code': 'ta', 'name': 'Tamil', 'name_local': u'\u0ba4\u0bae\u0bbf\u0bb4\u0bcd', }, 'te': { 'bidi': False, 'code': 'te', 'name': 'Telugu', 'name_local': u'\u0c24\u0c46\u0c32\u0c41\u0c17\u0c41', }, 'th': { 'bidi': False, 'code': 'th', 'name': 'Thai', 'name_local': u'Thai', }, 'tr': { 'bidi': False, 'code': 'tr', 'name': 'Turkish', 'name_local': u'T\xfcrk\xe7e', }, 'uk': { 'bidi': False, 'code': 'uk', 'name': 'Ukrainian', 'name_local': u'\u0423\u043a\u0440\u0430\u0457\u043d\u0441\u044c\u043a\u0430', }, 'ur': { 'bidi': False, 'code': 'ur', 'name': 'Urdu', 'name_local': u'\u0627\u0631\u062f\u0648', }, 'vi': { 'bidi': False, 'code': 'vi', 'name': 'Vietnamese', 'name_local': u'Vietnamese', }, 'zh-cn': { 'bidi': False, 'code': 'zh-cn', 'name': 'Simplified Chinese', 'name_local': u'\u7b80\u4f53\u4e2d\u6587', }, 'zh-tw': { 'bidi': False, 'code': 'zh-tw', 'name': 'Traditional Chinese', 'name_local': u'\u7e41\u9ad4\u4e2d\u6587', } }
9,257
Python
.py
404
15.279703
86
0.419519
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,866
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/es_NI/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = r'j \de F \de Y' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = r'j \de F \de Y \a \l\a\s H:i' YEAR_MONTH_FORMAT = r'F \de Y' MONTH_DAY_FORMAT = r'j \de F' SHORT_DATE_FORMAT = 'd/m/Y' SHORT_DATETIME_FORMAT = 'd/m/Y H:i' FIRST_DAY_OF_WEEK = 1 # Monday: ISO 8601 DATE_INPUT_FORMATS = ( '%d/%m/%Y', '%d/%m/%y', # '25/10/2006', '25/10/06' '%Y%m%d', # '20061025' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', '%H:%M', # '14:30:59', '14:30' ) DATETIME_INPUT_FORMATS = ( '%d/%m/%Y %H:%M:%S', '%d/%m/%Y %H:%M', '%d/%m/%y %H:%M:%S', '%d/%m/%y %H:%M', ) DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' NUMBER_GROUPING = 3
786
Python
.py
27
26.925926
72
0.537037
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,867
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/cs/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j. E Y' TIME_FORMAT = 'G:i:s' DATETIME_FORMAT = 'j. E Y G:i:s' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y G:i:s' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%d.%m.%Y', '%d.%m.%y', # '25.10.2006', '25.10.06' '%Y-%m-%d', '%y-%m-%d', # '2006-10-25', '06-10-25' # '%d. %B %Y', '%d. %b. %Y', # '25. October 2006', '25. Oct. 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%Y', # '25.10.2006' '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = ' ' NUMBER_GROUPING = 3
1,288
Python
.py
35
34.485714
77
0.566747
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,868
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/ca/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = r'j \de F \de Y' TIME_FORMAT = 'G:i:s' DATETIME_FORMAT = r'j \de F \de Y \a \le\s G:i' YEAR_MONTH_FORMAT = r'F \de\l Y' MONTH_DAY_FORMAT = r'j \de F' SHORT_DATE_FORMAT = 'd/m/Y' SHORT_DATETIME_FORMAT = 'd/m/Y G:i' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( # '31/12/2009', '31/12/09' '%d/%m/%Y', '%d/%m/%y' ) TIME_INPUT_FORMATS = ( # '14:30:59', '14:30' '%H:%M:%S', '%H:%M' ) DATETIME_INPUT_FORMATS = ( '%d/%m/%Y %H:%M:%S', '%d/%m/%Y %H:%M', '%d/%m/%y %H:%M:%S', '%d/%m/%y %H:%M', ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
990
Python
.py
32
28.84375
77
0.634555
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,869
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/ja/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'Y年n月j日' TIME_FORMAT = 'G:i:s' DATETIME_FORMAT = 'Y年n月j日G:i:s' YEAR_MONTH_FORMAT = 'Y年n月' MONTH_DAY_FORMAT = 'n月j日' SHORT_DATE_FORMAT = 'Y/m/d' SHORT_DATETIME_FORMAT = 'Y/m/d G:i:s' # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' # NUMBER_GROUPING =
765
Python
.py
21
34.142857
77
0.736842
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,870
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/sr/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j. F Y.' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j. F Y. H:i' YEAR_MONTH_FORMAT = 'F Y.' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'j.m.Y.' SHORT_DATETIME_FORMAT = 'j.m.Y. H:i' FIRST_DAY_OF_WEEK = 1 # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%d.%m.%Y.', '%d.%m.%y.', # '25.10.2006.', '25.10.06.' '%d. %m. %Y.', '%d. %m. %y.', # '25. 10. 2006.', '25. 10. 06.' '%Y-%m-%d', # '2006-10-25' # '%d. %b %y.', '%d. %B %y.', # '25. Oct 06.', '25. October 06.' # '%d. %b \'%y.', '%d. %B \'%y.', # '25. Oct '06.', '25. October '06.' # '%d. %b %Y.', '%d. %B %Y.', # '25. Oct 2006.', '25. October 2006.' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%d.%m.%Y. %H:%M:%S', # '25.10.2006. 14:30:59' '%d.%m.%Y. %H:%M', # '25.10.2006. 14:30' '%d.%m.%Y.', # '25.10.2006.' '%d.%m.%y. %H:%M:%S', # '25.10.06. 14:30:59' '%d.%m.%y. %H:%M', # '25.10.06. 14:30' '%d.%m.%y.', # '25.10.06.' '%d. %m. %Y. %H:%M:%S', # '25. 10. 2006. 14:30:59' '%d. %m. %Y. %H:%M', # '25. 10. 2006. 14:30' '%d. %m. %Y.', # '25. 10. 2006.' '%d. %m. %y. %H:%M:%S', # '25. 10. 06. 14:30:59' '%d. %m. %y. %H:%M', # '25. 10. 06. 14:30' '%d. %m. %y.', # '25. 10. 06.' '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
1,980
Python
.py
47
39.12766
77
0.461419
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,871
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/lt/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = r'Y \m. F j \d.' TIME_FORMAT = 'H:i:s' # DATETIME_FORMAT = # YEAR_MONTH_FORMAT = # MONTH_DAY_FORMAT = SHORT_DATE_FORMAT = 'Y.m.d' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' # NUMBER_GROUPING =
723
Python
.py
21
32.904762
77
0.727143
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,872
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/es/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = r'j \de F \de Y' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = r'j \de F \de Y \a \l\a\s H:i' YEAR_MONTH_FORMAT = r'F \de Y' MONTH_DAY_FORMAT = r'j \de F' SHORT_DATE_FORMAT = 'd/m/Y' SHORT_DATETIME_FORMAT = 'd/m/Y H:i' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( # '31/12/2009', '31/12/09' '%d/%m/%Y', '%d/%m/%y' ) TIME_INPUT_FORMATS = ( # '14:30:59', '14:30' '%H:%M:%S', '%H:%M' ) DATETIME_INPUT_FORMATS = ( '%d/%m/%Y %H:%M:%S', '%d/%m/%Y %H:%M', '%d/%m/%y %H:%M:%S', '%d/%m/%y %H:%M', ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
989
Python
.py
32
28.8125
77
0.634172
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,873
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/no/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j. F Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j. F Y H:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y H:i' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%d.%m.%Y', '%d.%m.%y', # '2006-10-25', '25.10.2006', '25.10.06' '%Y-%m-%d', # '2006-10-25', # '%d. %b %Y', '%d %b %Y', # '25. okt 2006', '25 okt 2006' # '%d. %b. %Y', '%d %b. %Y', # '25. okt. 2006', '25 okt. 2006' # '%d. %B %Y', '%d %B %Y', # '25. oktober 2006', '25 oktober 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%Y-%m-%d', # '2006-10-25' '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%Y', # '25.10.2006' '%d.%m.%y %H:%M:%S', # '25.10.06 14:30:59' '%d.%m.%y %H:%M', # '25.10.06 14:30' '%d.%m.%y', # '25.10.06' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = ' ' NUMBER_GROUPING = 3
1,657
Python
.py
41
37.707317
81
0.503717
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,874
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/sr_Latn/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j. F Y.' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j. F Y. H:i' YEAR_MONTH_FORMAT = 'F Y.' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'j.m.Y.' SHORT_DATETIME_FORMAT = 'j.m.Y. H:i' FIRST_DAY_OF_WEEK = 1 # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%d.%m.%Y.', '%d.%m.%y.', # '25.10.2006.', '25.10.06.' '%d. %m. %Y.', '%d. %m. %y.', # '25. 10. 2006.', '25. 10. 06.' '%Y-%m-%d', # '2006-10-25' # '%d. %b %y.', '%d. %B %y.', # '25. Oct 06.', '25. October 06.' # '%d. %b \'%y.', '%d. %B \'%y.', # '25. Oct '06.', '25. October '06.' # '%d. %b %Y.', '%d. %B %Y.', # '25. Oct 2006.', '25. October 2006.' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%d.%m.%Y. %H:%M:%S', # '25.10.2006. 14:30:59' '%d.%m.%Y. %H:%M', # '25.10.2006. 14:30' '%d.%m.%Y.', # '25.10.2006.' '%d.%m.%y. %H:%M:%S', # '25.10.06. 14:30:59' '%d.%m.%y. %H:%M', # '25.10.06. 14:30' '%d.%m.%y.', # '25.10.06.' '%d. %m. %Y. %H:%M:%S', # '25. 10. 2006. 14:30:59' '%d. %m. %Y. %H:%M', # '25. 10. 2006. 14:30' '%d. %m. %Y.', # '25. 10. 2006.' '%d. %m. %y. %H:%M:%S', # '25. 10. 06. 14:30:59' '%d. %m. %y. %H:%M', # '25. 10. 06. 14:30' '%d. %m. %y.', # '25. 10. 06.' '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
1,980
Python
.py
47
39.12766
77
0.461419
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,875
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/el/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'd E Y' TIME_FORMAT = 'g:i:s A' # DATETIME_FORMAT = YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'd M Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' # NUMBER_GROUPING =
722
Python
.py
21
32.952381
77
0.731044
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,876
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/nl/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j F Y' # '20 januari 2009' TIME_FORMAT = 'H:i' # '15:23' DATETIME_FORMAT = 'j F Y H:i' # '20 januari 2009 15:23' YEAR_MONTH_FORMAT = 'F Y' # 'januari 2009' MONTH_DAY_FORMAT = 'j F' # '20 januari' SHORT_DATE_FORMAT = 'j-n-Y' # '20-1-2009' SHORT_DATETIME_FORMAT = 'j-n-Y H:i' # '20-1-2009 15:23' FIRST_DAY_OF_WEEK = 1 # Monday (in Dutch 'maandag') # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%d-%m-%Y', '%d-%m-%y', '%Y-%m-%d', # '20-01-2009', '20-01-09', '2009-01-20' # '%d %b %Y', '%d %b %y', # '20 jan 2009', '20 jan 09' # '%d %B %Y', '%d %B %y', # '20 januari 2009', '20 januari 09' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '15:23:35' '%H.%M:%S', # '15.23:35' '%H.%M', # '15.23' '%H:%M', # '15:23' ) DATETIME_INPUT_FORMATS = ( # With time in %H:%M:%S : '%d-%m-%Y %H:%M:%S', '%d-%m-%y %H:%M:%S', '%Y-%m-%d %H:%M:%S', # '20-01-2009 15:23:35', '20-01-09 15:23:35', '2009-01-20 15:23:35' # '%d %b %Y %H:%M:%S', '%d %b %y %H:%M:%S', # '20 jan 2009 15:23:35', '20 jan 09 15:23:35' # '%d %B %Y %H:%M:%S', '%d %B %y %H:%M:%S', # '20 januari 2009 15:23:35', '20 januari 2009 15:23:35' # With time in %H.%M:%S : '%d-%m-%Y %H.%M:%S', '%d-%m-%y %H.%M:%S', # '20-01-2009 15.23:35', '20-01-09 15.23:35' # '%d %b %Y %H.%M:%S', '%d %b %y %H.%M:%S', # '20 jan 2009 15.23:35', '20 jan 09 15.23:35' # '%d %B %Y %H.%M:%S', '%d %B %y %H.%M:%S', # '20 januari 2009 15.23:35', '20 januari 2009 15.23:35' # With time in %H:%M : '%d-%m-%Y %H:%M', '%d-%m-%y %H:%M', '%Y-%m-%d %H:%M', # '20-01-2009 15:23', '20-01-09 15:23', '2009-01-20 15:23' # '%d %b %Y %H:%M', '%d %b %y %H:%M', # '20 jan 2009 15:23', '20 jan 09 15:23' # '%d %B %Y %H:%M', '%d %B %y %H:%M', # '20 januari 2009 15:23', '20 januari 2009 15:23' # With time in %H.%M : '%d-%m-%Y %H.%M', '%d-%m-%y %H.%M', # '20-01-2009 15.23', '20-01-09 15.23' # '%d %b %Y %H.%M', '%d %b %y %H.%M', # '20 jan 2009 15.23', '20 jan 09 15.23' # '%d %B %Y %H.%M', '%d %B %y %H.%M', # '20 januari 2009 15.23', '20 januari 2009 15.23' # Without time : '%d-%m-%Y', '%d-%m-%y', '%Y-%m-%d', # '20-01-2009', '20-01-09', '2009-01-20' # '%d %b %Y', '%d %b %y', # '20 jan 2009', '20 jan 09' # '%d %B %Y', '%d %B %y', # '20 januari 2009', '20 januari 2009' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
3,056
Python
.py
51
56.764706
135
0.461205
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,877
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/ta/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j F, Y' TIME_FORMAT = 'g:i:s A' # DATETIME_FORMAT = # YEAR_MONTH_FORMAT = MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j M, Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = # DECIMAL_SEPARATOR = # THOUSAND_SEPARATOR = # NUMBER_GROUPING =
719
Python
.py
21
32.666667
77
0.731322
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,878
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/te/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j F Y' TIME_FORMAT = 'g:i:s A' # DATETIME_FORMAT = # YEAR_MONTH_FORMAT = MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j M Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = # DECIMAL_SEPARATOR = # THOUSAND_SEPARATOR = # NUMBER_GROUPING =
717
Python
.py
21
32.571429
77
0.733429
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,879
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/ko/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'Y년 n월 j일' TIME_FORMAT = 'A g:i:s' DATETIME_FORMAT = 'Y년 n월 j일 g:i:s A' YEAR_MONTH_FORMAT = 'Y년 F월' MONTH_DAY_FORMAT = 'F월 j일' SHORT_DATE_FORMAT = 'Y-n-j.' SHORT_DATETIME_FORMAT = 'Y-n-j H:i' # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06' # '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006' # '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006' # '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006' # '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' '%Y년 %m월 %d일', # '2006년 10월 25일', with localized suffix. ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' '%H시 %M분 %S초', # '14시 30분 59초' '%H시 %M분', # '14시 30분' ) DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' '%m/%d/%Y %H:%M', # '10/25/2006 14:30' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M', # '10/25/06 14:30' '%m/%d/%y', # '10/25/06' '%Y년 %m월 %d일 %H시 %M분 %S초', # '2006년 10월 25일 14시 30분 59초' '%Y년 %m월 %d일 %H시 %M분', # '2006년 10월 25일 14시 30분' ) DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' NUMBER_GROUPING = 3
2,016
Python
.py
45
39.711111
81
0.50775
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,880
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/th/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j F Y' TIME_FORMAT = 'G:i:s' DATETIME_FORMAT = 'j F Y, G:i:s' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j M Y' SHORT_DATETIME_FORMAT = 'j M Y, G:i:s' # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' # NUMBER_GROUPING =
744
Python
.py
21
34.095238
77
0.723994
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,881
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/km/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j ខែ F ឆ្នាំ Y' TIME_FORMAT = 'G:i:s' DATETIME_FORMAT = 'j ខែ F ឆ្នាំ Y, G:i:s' # YEAR_MONTH_FORMAT = MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j M Y' SHORT_DATETIME_FORMAT = 'j M Y, G:i:s' # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' # NUMBER_GROUPING =
787
Python
.py
21
34.761905
77
0.714674
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,882
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/is/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j. F Y' TIME_FORMAT = 'H:i:s' # DATETIME_FORMAT = YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'j.n.Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' # NUMBER_GROUPING =
722
Python
.py
21
32.952381
77
0.729614
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,883
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/de/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j. F Y' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = 'j. F Y H:i:s' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y H:i:s' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%d.%m.%Y', '%d.%m.%y', # '25.10.2006', '25.10.06' '%Y-%m-%d', '%y-%m-%d', # '2006-10-25', '06-10-25' # '%d. %B %Y', '%d. %b. %Y', # '25. October 2006', '25. Oct. 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%Y', # '25.10.2006' '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
1,288
Python
.py
35
34.485714
77
0.566747
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,884
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/sl/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'd. F Y' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = 'j. F Y. H:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'j. M. Y' SHORT_DATETIME_FORMAT = 'j.n.Y. H:i' FIRST_DAY_OF_WEEK = 0 # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%d.%m.%Y', '%d.%m.%y', # '25.10.2006', '25.10.06' '%d-%m-%Y', # '25-10-2006' '%d. %m. %Y', '%d. %m. %y', # '25. 10. 2006', '25. 10. 06' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%Y', # '25.10.2006' '%d.%m.%y %H:%M:%S', # '25.10.06 14:30:59' '%d.%m.%y %H:%M', # '25.10.06 14:30' '%d.%m.%y', # '25.10.06' '%d-%m-%Y %H:%M:%S', # '25-10-2006 14:30:59' '%d-%m-%Y %H:%M', # '25-10-2006 14:30' '%d-%m-%Y', # '25-10-2006' '%d. %m. %Y %H:%M:%S', # '25. 10. 2006 14:30:59' '%d. %m. %Y %H:%M', # '25. 10. 2006 14:30' '%d. %m. %Y', # '25. 10. 2006' '%d. %m. %y %H:%M:%S', # '25. 10. 06 14:30:59' '%d. %m. %y %H:%M', # '25. 10. 06 14:30' '%d. %m. %y', # '25. 10. 06' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
1,834
Python
.py
44
38.75
77
0.457143
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,885
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/hu/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'Y. F j.' TIME_FORMAT = 'G:i:s' # DATETIME_FORMAT = # YEAR_MONTH_FORMAT = MONTH_DAY_FORMAT = 'F j.' SHORT_DATE_FORMAT = 'Y.m.d.' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = u' ' # Non-breaking space # NUMBER_GROUPING =
744
Python
.py
21
33.952381
77
0.729542
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,886
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/eu/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = r'Yeko M\re\n d\a' TIME_FORMAT = 'H:i:s' # DATETIME_FORMAT = # YEAR_MONTH_FORMAT = # MONTH_DAY_FORMAT = SHORT_DATE_FORMAT = 'Y M j' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' # NUMBER_GROUPING =
725
Python
.py
21
33
77
0.732194
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,887
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/ro/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j F Y' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = 'j F Y, H:i:s' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y, H:i:s' # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' # NUMBER_GROUPING =
744
Python
.py
21
34.095238
77
0.723994
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,888
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/ka/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'l, j F, Y' TIME_FORMAT = 'h:i:s a' DATETIME_FORMAT = 'j F, Y h:i:s a' YEAR_MONTH_FORMAT = 'F, Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j.M.Y' SHORT_DATETIME_FORMAT = 'j.M.Y H:i:s' FIRST_DAY_OF_WEEK = 1 # (Monday) # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06' # '%d %b %Y', '%d %b, %Y', '%d %b. %Y', # '25 Oct 2006', '25 Oct, 2006', '25 Oct. 2006' # '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' # '%d.%m.%Y', '%d.%m.%y', # '25.10.2006', '25.10.06' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%Y', # '25.10.2006' '%d.%m.%y %H:%M:%S', # '25.10.06 14:30:59' '%d.%m.%y %H:%M', # '25.10.06 14:30' '%d.%m.%y', # '25.10.06' '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' '%m/%d/%Y %H:%M', # '10/25/2006 14:30' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M', # '10/25/06 14:30' '%m/%d/%y', # '10/25/06' ) DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = " " NUMBER_GROUPING = 3
1,888
Python
.py
45
39.044444
93
0.486149
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,889
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/fy_NL/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date # DATE_FORMAT = # TIME_FORMAT = # DATETIME_FORMAT = # YEAR_MONTH_FORMAT = # MONTH_DAY_FORMAT = # SHORT_DATE_FORMAT = # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = # DECIMAL_SEPARATOR = # THOUSAND_SEPARATOR = # NUMBER_GROUPING =
697
Python
.py
21
31.428571
77
0.737389
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,890
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/gl/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'd F Y' TIME_FORMAT = 'H:i:s' # DATETIME_FORMAT = YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j M, Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' # NUMBER_GROUPING =
721
Python
.py
21
32.904762
77
0.730659
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,891
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/pl/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j E Y' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = 'j E Y H:i:s' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'd-m-Y' SHORT_DATETIME_FORMAT = 'd-m-Y H:i:s' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%d.%m.%Y', '%d.%m.%y', # '25.10.2006', '25.10.06' '%Y-%m-%d', '%y-%m-%d', # '2006-10-25', '06-10-25' # '%d. %B %Y', '%d. %b. %Y', # '25. October 2006', '25. Oct. 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%Y', # '25.10.2006' '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = u' ' NUMBER_GROUPING = 3
1,288
Python
.py
35
34.485714
77
0.568345
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,892
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/zh_CN/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date # DATE_FORMAT = # TIME_FORMAT = # DATETIME_FORMAT = # YEAR_MONTH_FORMAT = # MONTH_DAY_FORMAT = # SHORT_DATE_FORMAT = # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = # DECIMAL_SEPARATOR = # THOUSAND_SEPARATOR = # NUMBER_GROUPING =
697
Python
.py
21
31.428571
77
0.737389
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,893
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/hr/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j. E Y.' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = 'j. E Y. H:i' YEAR_MONTH_FORMAT = 'F Y.' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'j.m.Y.' SHORT_DATETIME_FORMAT = 'j.m.Y. H:i' FIRST_DAY_OF_WEEK = 1 # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%Y-%m-%d', # '2006-10-25' '%d.%m.%Y.', '%d.%m.%y.', # '25.10.2006.', '25.10.06.' '%d. %m. %Y.', '%d. %m. %y.', # '25. 10. 2006.', '25. 10. 06.' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%d.%m.%Y. %H:%M:%S', # '25.10.2006. 14:30:59' '%d.%m.%Y. %H:%M', # '25.10.2006. 14:30' '%d.%m.%Y.', # '25.10.2006.' '%d.%m.%y. %H:%M:%S', # '25.10.06. 14:30:59' '%d.%m.%y. %H:%M', # '25.10.06. 14:30' '%d.%m.%y.', # '25.10.06.' '%d. %m. %Y. %H:%M:%S', # '25. 10. 2006. 14:30:59' '%d. %m. %Y. %H:%M', # '25. 10. 2006. 14:30' '%d. %m. %Y.', # '25. 10. 2006.' '%d. %m. %y. %H:%M:%S', # '25. 10. 06. 14:30:59' '%d. %m. %y. %H:%M', # '25. 10. 06. 14:30' '%d. %m. %y.', # '25. 10. 06.' ) DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' NUMBER_GROUPING = 3
1,758
Python
.py
44
37.068182
77
0.476914
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,894
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/es_MX/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = r'j \de F \de Y' TIME_FORMAT = 'H:i:s' DATETIME_FORMAT = r'j \de F \de Y \a \l\a\s H:i' YEAR_MONTH_FORMAT = r'F \de Y' MONTH_DAY_FORMAT = r'j \de F' SHORT_DATE_FORMAT = 'd/m/Y' SHORT_DATETIME_FORMAT = 'd/m/Y H:i' FIRST_DAY_OF_WEEK = 1 # Monday: ISO 8601 DATE_INPUT_FORMATS = ( '%d/%m/%Y', '%d/%m/%y', # '25/10/2006', '25/10/06' '%Y%m%d', # '20061025' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', '%H:%M', # '14:30:59', '14:30' ) DATETIME_INPUT_FORMATS = ( '%d/%m/%Y %H:%M:%S', '%d/%m/%Y %H:%M', '%d/%m/%y %H:%M:%S', '%d/%m/%y %H:%M', ) DECIMAL_SEPARATOR = '.' # ',' is also official (less common): NOM-008-SCFI-2002 THOUSAND_SEPARATOR = ' ' # white space NUMBER_GROUPING = 3
859
Python
.py
27
29.62963
81
0.547648
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,895
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/ru/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j E Y г.' TIME_FORMAT = 'G:i:s' DATETIME_FORMAT = 'j E Y г. G:i:s' YEAR_MONTH_FORMAT = 'F Y г.' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y H:i' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%d.%m.%Y', # '25.10.2006' '%d.%m.%y', # '25.10.06' '%Y-%m-%d', # '2006-10-25' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%Y', # '25.10.2006' '%d.%m.%y %H:%M:%S', # '25.10.06 14:30:59' '%d.%m.%y %H:%M', # '25.10.06 14:30' '%d.%m.%y', # '25.10.06' '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = ' ' NUMBER_GROUPING = 3
1,323
Python
.py
38
32.184211
77
0.559375
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,896
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/en/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'N j, Y' TIME_FORMAT = 'P' DATETIME_FORMAT = 'N j, Y, P' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'F j' SHORT_DATE_FORMAT = 'm/d/Y' SHORT_DATETIME_FORMAT = 'm/d/Y P' FIRST_DAY_OF_WEEK = 0 # Sunday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06' # '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006' # '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006' # '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006' # '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' '%m/%d/%Y %H:%M', # '10/25/2006 14:30' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M', # '10/25/06 14:30' '%m/%d/%y', # '10/25/06' ) DECIMAL_SEPARATOR = u'.' THOUSAND_SEPARATOR = u',' NUMBER_GROUPING = 3
1,637
Python
.py
40
38.25
81
0.515684
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,897
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/et/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j F Y' TIME_FORMAT = 'G:i:s' # DATETIME_FORMAT = # YEAR_MONTH_FORMAT = MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'd.m.Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = u' ' # Non-breaking space # NUMBER_GROUPING =
740
Python
.py
21
33.761905
77
0.733612
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,898
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/bg/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'd F Y' TIME_FORMAT = 'H:i:s' # DATETIME_FORMAT = # YEAR_MONTH_FORMAT = MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'd.m.Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = u' ' # Non-breaking space # NUMBER_GROUPING =
740
Python
.py
21
33.761905
77
0.733612
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
2,899
formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/conf/locale/fi/formats.py
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j. E Y' TIME_FORMAT = 'G.i.s' # DATETIME_FORMAT = YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'j.n.Y' # SHORT_DATETIME_FORMAT = # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = u' ' # Non-breaking space # NUMBER_GROUPING =
745
Python
.py
21
34.047619
77
0.731302
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)