code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
"""Statistics analyzer for HotShot."""
import profile
import pstats
import hotshot.log
from hotshot.log import ENTER, EXIT
def load(filename):
return StatsLoader(filename).load()
class StatsLoader:
def __init__(self, logfn):
self._logfn = logfn
self._code = {}
self._stack = []
self.pop_frame = self._stack.pop
def load(self):
# The timer selected by the profiler should never be used, so make
# sure it doesn't work:
p = Profile()
p.get_time = _brokentimer
log = hotshot.log.LogReader(self._logfn)
taccum = 0
for event in log:
what, (filename, lineno, funcname), tdelta = event
if tdelta > 0:
taccum += tdelta
# We multiply taccum to convert from the microseconds we
# have to the seconds that the profile/pstats module work
# with; this allows the numbers to have some basis in
# reality (ignoring calibration issues for now).
if what == ENTER:
frame = self.new_frame(filename, lineno, funcname)
p.trace_dispatch_call(frame, taccum * .000001)
taccum = 0
elif what == EXIT:
frame = self.pop_frame()
p.trace_dispatch_return(frame, taccum * .000001)
taccum = 0
# no further work for line events
assert not self._stack
return pstats.Stats(p)
def new_frame(self, *args):
# args must be filename, firstlineno, funcname
# our code objects are cached since we don't need to create
# new ones every time
try:
code = self._code[args]
except KeyError:
code = FakeCode(*args)
self._code[args] = code
# frame objects are create fresh, since the back pointer will
# vary considerably
if self._stack:
back = self._stack[-1]
else:
back = None
frame = FakeFrame(code, back)
self._stack.append(frame)
return frame
class Profile(profile.Profile):
def simulate_cmd_complete(self):
pass
class FakeCode:
def __init__(self, filename, firstlineno, funcname):
self.co_filename = filename
self.co_firstlineno = firstlineno
self.co_name = self.__name__ = funcname
class FakeFrame:
def __init__(self, code, back):
self.f_back = back
self.f_code = code
def _brokentimer():
raise RuntimeError, "this timer should not be called"
| Python |
import _hotshot
import os.path
import parser
import symbol
from _hotshot import \
WHAT_ENTER, \
WHAT_EXIT, \
WHAT_LINENO, \
WHAT_DEFINE_FILE, \
WHAT_DEFINE_FUNC, \
WHAT_ADD_INFO
__all__ = ["LogReader", "ENTER", "EXIT", "LINE"]
ENTER = WHAT_ENTER
EXIT = WHAT_EXIT
LINE = WHAT_LINENO
class LogReader:
def __init__(self, logfn):
# fileno -> filename
self._filemap = {}
# (fileno, lineno) -> filename, funcname
self._funcmap = {}
self._reader = _hotshot.logreader(logfn)
self._nextitem = self._reader.next
self._info = self._reader.info
if 'current-directory' in self._info:
self.cwd = self._info['current-directory']
else:
self.cwd = None
# This mirrors the call stack of the profiled code as the log
# is read back in. It contains tuples of the form:
#
# (file name, line number of function def, function name)
#
self._stack = []
self._append = self._stack.append
self._pop = self._stack.pop
def close(self):
self._reader.close()
def fileno(self):
"""Return the file descriptor of the log reader's log file."""
return self._reader.fileno()
def addinfo(self, key, value):
"""This method is called for each additional ADD_INFO record.
This can be overridden by applications that want to receive
these events. The default implementation does not need to be
called by alternate implementations.
The initial set of ADD_INFO records do not pass through this
mechanism; this is only needed to receive notification when
new values are added. Subclasses can inspect self._info after
calling LogReader.__init__().
"""
pass
def get_filename(self, fileno):
try:
return self._filemap[fileno]
except KeyError:
raise ValueError, "unknown fileno"
def get_filenames(self):
return self._filemap.values()
def get_fileno(self, filename):
filename = os.path.normcase(os.path.normpath(filename))
for fileno, name in self._filemap.items():
if name == filename:
return fileno
raise ValueError, "unknown filename"
def get_funcname(self, fileno, lineno):
try:
return self._funcmap[(fileno, lineno)]
except KeyError:
raise ValueError, "unknown function location"
# Iteration support:
# This adds an optional (& ignored) parameter to next() so that the
# same bound method can be used as the __getitem__() method -- this
# avoids using an additional method call which kills the performance.
def next(self, index=0):
while 1:
# This call may raise StopIteration:
what, tdelta, fileno, lineno = self._nextitem()
# handle the most common cases first
if what == WHAT_ENTER:
filename, funcname = self._decode_location(fileno, lineno)
t = (filename, lineno, funcname)
self._append(t)
return what, t, tdelta
if what == WHAT_EXIT:
try:
return what, self._pop(), tdelta
except IndexError:
raise StopIteration
if what == WHAT_LINENO:
filename, firstlineno, funcname = self._stack[-1]
return what, (filename, lineno, funcname), tdelta
if what == WHAT_DEFINE_FILE:
filename = os.path.normcase(os.path.normpath(tdelta))
self._filemap[fileno] = filename
elif what == WHAT_DEFINE_FUNC:
filename = self._filemap[fileno]
self._funcmap[(fileno, lineno)] = (filename, tdelta)
elif what == WHAT_ADD_INFO:
# value already loaded into self.info; call the
# overridable addinfo() handler so higher-level code
# can pick up the new value
if tdelta == 'current-directory':
self.cwd = lineno
self.addinfo(tdelta, lineno)
else:
raise ValueError, "unknown event type"
def __iter__(self):
return self
#
# helpers
#
def _decode_location(self, fileno, lineno):
try:
return self._funcmap[(fileno, lineno)]
except KeyError:
#
# This should only be needed when the log file does not
# contain all the DEFINE_FUNC records needed to allow the
# function name to be retrieved from the log file.
#
if self._loadfile(fileno):
filename = funcname = None
try:
filename, funcname = self._funcmap[(fileno, lineno)]
except KeyError:
filename = self._filemap.get(fileno)
funcname = None
self._funcmap[(fileno, lineno)] = (filename, funcname)
return filename, funcname
def _loadfile(self, fileno):
try:
filename = self._filemap[fileno]
except KeyError:
print "Could not identify fileId", fileno
return 1
if filename is None:
return 1
absname = os.path.normcase(os.path.join(self.cwd, filename))
try:
fp = open(absname)
except IOError:
return
st = parser.suite(fp.read())
fp.close()
# Scan the tree looking for def and lambda nodes, filling in
# self._funcmap with all the available information.
funcdef = symbol.funcdef
lambdef = symbol.lambdef
stack = [st.totuple(1)]
while stack:
tree = stack.pop()
try:
sym = tree[0]
except (IndexError, TypeError):
continue
if sym == funcdef:
self._funcmap[(fileno, tree[2][2])] = filename, tree[2][1]
elif sym == lambdef:
self._funcmap[(fileno, tree[1][2])] = filename, "<lambda>"
stack.extend(list(tree[1:]))
| Python |
"""High-perfomance logging profiler, mostly written in C."""
import _hotshot
from _hotshot import ProfilerError
from warnings import warnpy3k as _warnpy3k
_warnpy3k("The 'hotshot' module is not supported in 3.x, "
"use the 'profile' module instead.", stacklevel=2)
class Profile:
def __init__(self, logfn, lineevents=0, linetimings=1):
self.lineevents = lineevents and 1 or 0
self.linetimings = (linetimings and lineevents) and 1 or 0
self._prof = p = _hotshot.profiler(
logfn, self.lineevents, self.linetimings)
# Attempt to avoid confusing results caused by the presence of
# Python wrappers around these functions, but only if we can
# be sure the methods have not been overridden or extended.
if self.__class__ is Profile:
self.close = p.close
self.start = p.start
self.stop = p.stop
self.addinfo = p.addinfo
def close(self):
"""Close the logfile and terminate the profiler."""
self._prof.close()
def fileno(self):
"""Return the file descriptor of the profiler's log file."""
return self._prof.fileno()
def start(self):
"""Start the profiler."""
self._prof.start()
def stop(self):
"""Stop the profiler."""
self._prof.stop()
def addinfo(self, key, value):
"""Add an arbitrary labelled value to the profile log."""
self._prof.addinfo(key, value)
# These methods offer the same interface as the profile.Profile class,
# but delegate most of the work to the C implementation underneath.
def run(self, cmd):
"""Profile an exec-compatible string in the script
environment.
The globals from the __main__ module are used as both the
globals and locals for the script.
"""
import __main__
dict = __main__.__dict__
return self.runctx(cmd, dict, dict)
def runctx(self, cmd, globals, locals):
"""Evaluate an exec-compatible string in a specific
environment.
The string is compiled before profiling begins.
"""
code = compile(cmd, "<string>", "exec")
self._prof.runcode(code, globals, locals)
return self
def runcall(self, func, *args, **kw):
"""Profile a single call of a callable.
Additional positional and keyword arguments may be passed
along; the result of the call is returned, and exceptions are
allowed to propogate cleanly, while ensuring that profiling is
disabled on the way out.
"""
return self._prof.runcall(func, args, kw)
| Python |
import errno
import hotshot
import hotshot.stats
import sys
import test.pystone
def main(logfile):
p = hotshot.Profile(logfile)
benchtime, stones = p.runcall(test.pystone.pystones)
p.close()
print "Pystone(%s) time for %d passes = %g" % \
(test.pystone.__version__, test.pystone.LOOPS, benchtime)
print "This machine benchmarks at %g pystones/second" % stones
stats = hotshot.stats.load(logfile)
stats.strip_dirs()
stats.sort_stats('time', 'calls')
try:
stats.print_stats(20)
except IOError, e:
if e.errno != errno.EPIPE:
raise
if __name__ == '__main__':
if sys.argv[1:]:
main(sys.argv[1])
else:
import tempfile
main(tempfile.NamedTemporaryFile().name)
| Python |
# Author: Steven J. Bethard <steven.bethard@gmail.com>.
"""Command-line parsing library
This module is an optparse-inspired command-line parsing library that:
- handles both optional and positional arguments
- produces highly informative usage messages
- supports parsers that dispatch to sub-parsers
The following is a simple usage example that sums integers from the
command-line and writes the result to a file::
parser = argparse.ArgumentParser(
description='sum the integers at the command line')
parser.add_argument(
'integers', metavar='int', nargs='+', type=int,
help='an integer to be summed')
parser.add_argument(
'--log', default=sys.stdout, type=argparse.FileType('w'),
help='the file where the sum should be written')
args = parser.parse_args()
args.log.write('%s' % sum(args.integers))
args.log.close()
The module contains the following public classes:
- ArgumentParser -- The main entry point for command-line parsing. As the
example above shows, the add_argument() method is used to populate
the parser with actions for optional and positional arguments. Then
the parse_args() method is invoked to convert the args at the
command-line into an object with attributes.
- ArgumentError -- The exception raised by ArgumentParser objects when
there are errors with the parser's actions. Errors raised while
parsing the command-line are caught by ArgumentParser and emitted
as command-line messages.
- FileType -- A factory for defining types of files to be created. As the
example above shows, instances of FileType are typically passed as
the type= argument of add_argument() calls.
- Action -- The base class for parser actions. Typically actions are
selected by passing strings like 'store_true' or 'append_const' to
the action= argument of add_argument(). However, for greater
customization of ArgumentParser actions, subclasses of Action may
be defined and passed as the action= argument.
- HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,
ArgumentDefaultsHelpFormatter -- Formatter classes which
may be passed as the formatter_class= argument to the
ArgumentParser constructor. HelpFormatter is the default,
RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser
not to change the formatting for help text, and
ArgumentDefaultsHelpFormatter adds information about argument defaults
to the help.
All other classes in this module are considered implementation details.
(Also note that HelpFormatter and RawDescriptionHelpFormatter are only
considered public as object names -- the API of the formatter objects is
still considered an implementation detail.)
"""
__version__ = '1.1'
__all__ = [
'ArgumentParser',
'ArgumentError',
'ArgumentTypeError',
'FileType',
'HelpFormatter',
'ArgumentDefaultsHelpFormatter',
'RawDescriptionHelpFormatter',
'RawTextHelpFormatter',
'Namespace',
'Action',
'ONE_OR_MORE',
'OPTIONAL',
'PARSER',
'REMAINDER',
'SUPPRESS',
'ZERO_OR_MORE',
]
import copy as _copy
import os as _os
import re as _re
import sys as _sys
import textwrap as _textwrap
from gettext import gettext as _
def _callable(obj):
return hasattr(obj, '__call__') or hasattr(obj, '__bases__')
SUPPRESS = '==SUPPRESS=='
OPTIONAL = '?'
ZERO_OR_MORE = '*'
ONE_OR_MORE = '+'
PARSER = 'A...'
REMAINDER = '...'
_UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args'
# =============================
# Utility functions and classes
# =============================
class _AttributeHolder(object):
"""Abstract base class that provides __repr__.
The __repr__ method returns a string in the format::
ClassName(attr=name, attr=name, ...)
The attributes are determined either by a class-level attribute,
'_kwarg_names', or by inspecting the instance __dict__.
"""
def __repr__(self):
type_name = type(self).__name__
arg_strings = []
for arg in self._get_args():
arg_strings.append(repr(arg))
for name, value in self._get_kwargs():
arg_strings.append('%s=%r' % (name, value))
return '%s(%s)' % (type_name, ', '.join(arg_strings))
def _get_kwargs(self):
return sorted(self.__dict__.items())
def _get_args(self):
return []
def _ensure_value(namespace, name, value):
if getattr(namespace, name, None) is None:
setattr(namespace, name, value)
return getattr(namespace, name)
# ===============
# Formatting Help
# ===============
class HelpFormatter(object):
"""Formatter for generating usage messages and argument help strings.
Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail.
"""
def __init__(self,
prog,
indent_increment=2,
max_help_position=24,
width=None):
# default setting for width
if width is None:
try:
width = int(_os.environ['COLUMNS'])
except (KeyError, ValueError):
width = 80
width -= 2
self._prog = prog
self._indent_increment = indent_increment
self._max_help_position = max_help_position
self._width = width
self._current_indent = 0
self._level = 0
self._action_max_length = 0
self._root_section = self._Section(self, None)
self._current_section = self._root_section
self._whitespace_matcher = _re.compile(r'\s+')
self._long_break_matcher = _re.compile(r'\n\n\n+')
# ===============================
# Section and indentation methods
# ===============================
def _indent(self):
self._current_indent += self._indent_increment
self._level += 1
def _dedent(self):
self._current_indent -= self._indent_increment
assert self._current_indent >= 0, 'Indent decreased below 0.'
self._level -= 1
class _Section(object):
def __init__(self, formatter, parent, heading=None):
self.formatter = formatter
self.parent = parent
self.heading = heading
self.items = []
def format_help(self):
# format the indented section
if self.parent is not None:
self.formatter._indent()
join = self.formatter._join_parts
for func, args in self.items:
func(*args)
item_help = join([func(*args) for func, args in self.items])
if self.parent is not None:
self.formatter._dedent()
# return nothing if the section was empty
if not item_help:
return ''
# add the heading if the section was non-empty
if self.heading is not SUPPRESS and self.heading is not None:
current_indent = self.formatter._current_indent
heading = '%*s%s:\n' % (current_indent, '', self.heading)
else:
heading = ''
# join the section-initial newline, the heading and the help
return join(['\n', heading, item_help, '\n'])
def _add_item(self, func, args):
self._current_section.items.append((func, args))
# ========================
# Message building methods
# ========================
def start_section(self, heading):
self._indent()
section = self._Section(self, self._current_section, heading)
self._add_item(section.format_help, [])
self._current_section = section
def end_section(self):
self._current_section = self._current_section.parent
self._dedent()
def add_text(self, text):
if text is not SUPPRESS and text is not None:
self._add_item(self._format_text, [text])
def add_usage(self, usage, actions, groups, prefix=None):
if usage is not SUPPRESS:
args = usage, actions, groups, prefix
self._add_item(self._format_usage, args)
def add_argument(self, action):
if action.help is not SUPPRESS:
# find all invocations
get_invocation = self._format_action_invocation
invocations = [get_invocation(action)]
for subaction in self._iter_indented_subactions(action):
invocations.append(get_invocation(subaction))
# update the maximum item length
invocation_length = max([len(s) for s in invocations])
action_length = invocation_length + self._current_indent
self._action_max_length = max(self._action_max_length,
action_length)
# add the item to the list
self._add_item(self._format_action, [action])
def add_arguments(self, actions):
for action in actions:
self.add_argument(action)
# =======================
# Help-formatting methods
# =======================
def format_help(self):
help = self._root_section.format_help()
if help:
help = self._long_break_matcher.sub('\n\n', help)
help = help.strip('\n') + '\n'
return help
def _join_parts(self, part_strings):
return ''.join([part
for part in part_strings
if part and part is not SUPPRESS])
def _format_usage(self, usage, actions, groups, prefix):
if prefix is None:
prefix = _('usage: ')
# if usage is specified, use that
if usage is not None:
usage = usage % dict(prog=self._prog)
# if no optionals or positionals are available, usage is just prog
elif usage is None and not actions:
usage = '%(prog)s' % dict(prog=self._prog)
# if optionals and positionals are available, calculate usage
elif usage is None:
prog = '%(prog)s' % dict(prog=self._prog)
# split optionals from positionals
optionals = []
positionals = []
for action in actions:
if action.option_strings:
optionals.append(action)
else:
positionals.append(action)
# build full usage string
format = self._format_actions_usage
action_usage = format(optionals + positionals, groups)
usage = ' '.join([s for s in [prog, action_usage] if s])
# wrap the usage parts if it's too long
text_width = self._width - self._current_indent
if len(prefix) + len(usage) > text_width:
# break usage into wrappable parts
part_regexp = r'\(.*?\)+|\[.*?\]+|\S+'
opt_usage = format(optionals, groups)
pos_usage = format(positionals, groups)
opt_parts = _re.findall(part_regexp, opt_usage)
pos_parts = _re.findall(part_regexp, pos_usage)
assert ' '.join(opt_parts) == opt_usage
assert ' '.join(pos_parts) == pos_usage
# helper for wrapping lines
def get_lines(parts, indent, prefix=None):
lines = []
line = []
if prefix is not None:
line_len = len(prefix) - 1
else:
line_len = len(indent) - 1
for part in parts:
if line_len + 1 + len(part) > text_width:
lines.append(indent + ' '.join(line))
line = []
line_len = len(indent) - 1
line.append(part)
line_len += len(part) + 1
if line:
lines.append(indent + ' '.join(line))
if prefix is not None:
lines[0] = lines[0][len(indent):]
return lines
# if prog is short, follow it with optionals or positionals
if len(prefix) + len(prog) <= 0.75 * text_width:
indent = ' ' * (len(prefix) + len(prog) + 1)
if opt_parts:
lines = get_lines([prog] + opt_parts, indent, prefix)
lines.extend(get_lines(pos_parts, indent))
elif pos_parts:
lines = get_lines([prog] + pos_parts, indent, prefix)
else:
lines = [prog]
# if prog is long, put it on its own line
else:
indent = ' ' * len(prefix)
parts = opt_parts + pos_parts
lines = get_lines(parts, indent)
if len(lines) > 1:
lines = []
lines.extend(get_lines(opt_parts, indent))
lines.extend(get_lines(pos_parts, indent))
lines = [prog] + lines
# join lines into usage
usage = '\n'.join(lines)
# prefix with 'usage:'
return '%s%s\n\n' % (prefix, usage)
def _format_actions_usage(self, actions, groups):
# find group indices and identify actions in groups
group_actions = set()
inserts = {}
for group in groups:
try:
start = actions.index(group._group_actions[0])
except ValueError:
continue
else:
end = start + len(group._group_actions)
if actions[start:end] == group._group_actions:
for action in group._group_actions:
group_actions.add(action)
if not group.required:
if start in inserts:
inserts[start] += ' ['
else:
inserts[start] = '['
inserts[end] = ']'
else:
if start in inserts:
inserts[start] += ' ('
else:
inserts[start] = '('
inserts[end] = ')'
for i in range(start + 1, end):
inserts[i] = '|'
# collect all actions format strings
parts = []
for i, action in enumerate(actions):
# suppressed arguments are marked with None
# remove | separators for suppressed arguments
if action.help is SUPPRESS:
parts.append(None)
if inserts.get(i) == '|':
inserts.pop(i)
elif inserts.get(i + 1) == '|':
inserts.pop(i + 1)
# produce all arg strings
elif not action.option_strings:
part = self._format_args(action, action.dest)
# if it's in a group, strip the outer []
if action in group_actions:
if part[0] == '[' and part[-1] == ']':
part = part[1:-1]
# add the action string to the list
parts.append(part)
# produce the first way to invoke the option in brackets
else:
option_string = action.option_strings[0]
# if the Optional doesn't take a value, format is:
# -s or --long
if action.nargs == 0:
part = '%s' % option_string
# if the Optional takes a value, format is:
# -s ARGS or --long ARGS
else:
default = action.dest.upper()
args_string = self._format_args(action, default)
part = '%s %s' % (option_string, args_string)
# make it look optional if it's not required or in a group
if not action.required and action not in group_actions:
part = '[%s]' % part
# add the action string to the list
parts.append(part)
# insert things at the necessary indices
for i in sorted(inserts, reverse=True):
parts[i:i] = [inserts[i]]
# join all the action items with spaces
text = ' '.join([item for item in parts if item is not None])
# clean up separators for mutually exclusive groups
open = r'[\[(]'
close = r'[\])]'
text = _re.sub(r'(%s) ' % open, r'\1', text)
text = _re.sub(r' (%s)' % close, r'\1', text)
text = _re.sub(r'%s *%s' % (open, close), r'', text)
text = _re.sub(r'\(([^|]*)\)', r'\1', text)
text = text.strip()
# return the text
return text
def _format_text(self, text):
if '%(prog)' in text:
text = text % dict(prog=self._prog)
text_width = self._width - self._current_indent
indent = ' ' * self._current_indent
return self._fill_text(text, text_width, indent) + '\n\n'
def _format_action(self, action):
# determine the required width and the entry label
help_position = min(self._action_max_length + 2,
self._max_help_position)
help_width = self._width - help_position
action_width = help_position - self._current_indent - 2
action_header = self._format_action_invocation(action)
# ho nelp; start on same line and add a final newline
if not action.help:
tup = self._current_indent, '', action_header
action_header = '%*s%s\n' % tup
# short action name; start on the same line and pad two spaces
elif len(action_header) <= action_width:
tup = self._current_indent, '', action_width, action_header
action_header = '%*s%-*s ' % tup
indent_first = 0
# long action name; start on the next line
else:
tup = self._current_indent, '', action_header
action_header = '%*s%s\n' % tup
indent_first = help_position
# collect the pieces of the action help
parts = [action_header]
# if there was help for the action, add lines of help text
if action.help:
help_text = self._expand_help(action)
help_lines = self._split_lines(help_text, help_width)
parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
for line in help_lines[1:]:
parts.append('%*s%s\n' % (help_position, '', line))
# or add a newline if the description doesn't end with one
elif not action_header.endswith('\n'):
parts.append('\n')
# if there are any sub-actions, add their help as well
for subaction in self._iter_indented_subactions(action):
parts.append(self._format_action(subaction))
# return a single string
return self._join_parts(parts)
def _format_action_invocation(self, action):
if not action.option_strings:
metavar, = self._metavar_formatter(action, action.dest)(1)
return metavar
else:
parts = []
# if the Optional doesn't take a value, format is:
# -s, --long
if action.nargs == 0:
parts.extend(action.option_strings)
# if the Optional takes a value, format is:
# -s ARGS, --long ARGS
else:
default = action.dest.upper()
args_string = self._format_args(action, default)
for option_string in action.option_strings:
parts.append('%s %s' % (option_string, args_string))
return ', '.join(parts)
def _metavar_formatter(self, action, default_metavar):
if action.metavar is not None:
result = action.metavar
elif action.choices is not None:
choice_strs = [str(choice) for choice in action.choices]
result = '{%s}' % ','.join(choice_strs)
else:
result = default_metavar
def format(tuple_size):
if isinstance(result, tuple):
return result
else:
return (result, ) * tuple_size
return format
def _format_args(self, action, default_metavar):
get_metavar = self._metavar_formatter(action, default_metavar)
if action.nargs is None:
result = '%s' % get_metavar(1)
elif action.nargs == OPTIONAL:
result = '[%s]' % get_metavar(1)
elif action.nargs == ZERO_OR_MORE:
result = '[%s [%s ...]]' % get_metavar(2)
elif action.nargs == ONE_OR_MORE:
result = '%s [%s ...]' % get_metavar(2)
elif action.nargs == REMAINDER:
result = '...'
elif action.nargs == PARSER:
result = '%s ...' % get_metavar(1)
else:
formats = ['%s' for _ in range(action.nargs)]
result = ' '.join(formats) % get_metavar(action.nargs)
return result
def _expand_help(self, action):
params = dict(vars(action), prog=self._prog)
for name in list(params):
if params[name] is SUPPRESS:
del params[name]
for name in list(params):
if hasattr(params[name], '__name__'):
params[name] = params[name].__name__
if params.get('choices') is not None:
choices_str = ', '.join([str(c) for c in params['choices']])
params['choices'] = choices_str
return self._get_help_string(action) % params
def _iter_indented_subactions(self, action):
try:
get_subactions = action._get_subactions
except AttributeError:
pass
else:
self._indent()
for subaction in get_subactions():
yield subaction
self._dedent()
def _split_lines(self, text, width):
text = self._whitespace_matcher.sub(' ', text).strip()
return _textwrap.wrap(text, width)
def _fill_text(self, text, width, indent):
text = self._whitespace_matcher.sub(' ', text).strip()
return _textwrap.fill(text, width, initial_indent=indent,
subsequent_indent=indent)
def _get_help_string(self, action):
return action.help
class RawDescriptionHelpFormatter(HelpFormatter):
"""Help message formatter which retains any formatting in descriptions.
Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail.
"""
def _fill_text(self, text, width, indent):
return ''.join([indent + line for line in text.splitlines(True)])
class RawTextHelpFormatter(RawDescriptionHelpFormatter):
"""Help message formatter which retains formatting of all help text.
Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail.
"""
def _split_lines(self, text, width):
return text.splitlines()
class ArgumentDefaultsHelpFormatter(HelpFormatter):
"""Help message formatter which adds default values to argument help.
Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail.
"""
def _get_help_string(self, action):
help = action.help
if '%(default)' not in action.help:
if action.default is not SUPPRESS:
defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
if action.option_strings or action.nargs in defaulting_nargs:
help += ' (default: %(default)s)'
return help
# =====================
# Options and Arguments
# =====================
def _get_action_name(argument):
if argument is None:
return None
elif argument.option_strings:
return '/'.join(argument.option_strings)
elif argument.metavar not in (None, SUPPRESS):
return argument.metavar
elif argument.dest not in (None, SUPPRESS):
return argument.dest
else:
return None
class ArgumentError(Exception):
"""An error from creating or using an argument (optional or positional).
The string value of this exception is the message, augmented with
information about the argument that caused it.
"""
def __init__(self, argument, message):
self.argument_name = _get_action_name(argument)
self.message = message
def __str__(self):
if self.argument_name is None:
format = '%(message)s'
else:
format = 'argument %(argument_name)s: %(message)s'
return format % dict(message=self.message,
argument_name=self.argument_name)
class ArgumentTypeError(Exception):
"""An error from trying to convert a command line string to a type."""
pass
# ==============
# Action classes
# ==============
class Action(_AttributeHolder):
"""Information about how to convert command line strings to Python objects.
Action objects are used by an ArgumentParser to represent the information
needed to parse a single argument from one or more strings from the
command line. The keyword arguments to the Action constructor are also
all attributes of Action instances.
Keyword Arguments:
- option_strings -- A list of command-line option strings which
should be associated with this action.
- dest -- The name of the attribute to hold the created object(s)
- nargs -- The number of command-line arguments that should be
consumed. By default, one argument will be consumed and a single
value will be produced. Other values include:
- N (an integer) consumes N arguments (and produces a list)
- '?' consumes zero or one arguments
- '*' consumes zero or more arguments (and produces a list)
- '+' consumes one or more arguments (and produces a list)
Note that the difference between the default and nargs=1 is that
with the default, a single value will be produced, while with
nargs=1, a list containing a single value will be produced.
- const -- The value to be produced if the option is specified and the
option uses an action that takes no values.
- default -- The value to be produced if the option is not specified.
- type -- The type which the command-line arguments should be converted
to, should be one of 'string', 'int', 'float', 'complex' or a
callable object that accepts a single string argument. If None,
'string' is assumed.
- choices -- A container of values that should be allowed. If not None,
after a command-line argument has been converted to the appropriate
type, an exception will be raised if it is not a member of this
collection.
- required -- True if the action must always be specified at the
command line. This is only meaningful for optional command-line
arguments.
- help -- The help string describing the argument.
- metavar -- The name to be used for the option's argument with the
help string. If None, the 'dest' value will be used as the name.
"""
def __init__(self,
option_strings,
dest,
nargs=None,
const=None,
default=None,
type=None,
choices=None,
required=False,
help=None,
metavar=None):
self.option_strings = option_strings
self.dest = dest
self.nargs = nargs
self.const = const
self.default = default
self.type = type
self.choices = choices
self.required = required
self.help = help
self.metavar = metavar
def _get_kwargs(self):
names = [
'option_strings',
'dest',
'nargs',
'const',
'default',
'type',
'choices',
'help',
'metavar',
]
return [(name, getattr(self, name)) for name in names]
def __call__(self, parser, namespace, values, option_string=None):
raise NotImplementedError(_('.__call__() not defined'))
class _StoreAction(Action):
def __init__(self,
option_strings,
dest,
nargs=None,
const=None,
default=None,
type=None,
choices=None,
required=False,
help=None,
metavar=None):
if nargs == 0:
raise ValueError('nargs for store actions must be > 0; if you '
'have nothing to store, actions such as store '
'true or store const may be more appropriate')
if const is not None and nargs != OPTIONAL:
raise ValueError('nargs must be %r to supply const' % OPTIONAL)
super(_StoreAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=nargs,
const=const,
default=default,
type=type,
choices=choices,
required=required,
help=help,
metavar=metavar)
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, values)
class _StoreConstAction(Action):
def __init__(self,
option_strings,
dest,
const,
default=None,
required=False,
help=None,
metavar=None):
super(_StoreConstAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=0,
const=const,
default=default,
required=required,
help=help)
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, self.const)
class _StoreTrueAction(_StoreConstAction):
def __init__(self,
option_strings,
dest,
default=False,
required=False,
help=None):
super(_StoreTrueAction, self).__init__(
option_strings=option_strings,
dest=dest,
const=True,
default=default,
required=required,
help=help)
class _StoreFalseAction(_StoreConstAction):
def __init__(self,
option_strings,
dest,
default=True,
required=False,
help=None):
super(_StoreFalseAction, self).__init__(
option_strings=option_strings,
dest=dest,
const=False,
default=default,
required=required,
help=help)
class _AppendAction(Action):
def __init__(self,
option_strings,
dest,
nargs=None,
const=None,
default=None,
type=None,
choices=None,
required=False,
help=None,
metavar=None):
if nargs == 0:
raise ValueError('nargs for append actions must be > 0; if arg '
'strings are not supplying the value to append, '
'the append const action may be more appropriate')
if const is not None and nargs != OPTIONAL:
raise ValueError('nargs must be %r to supply const' % OPTIONAL)
super(_AppendAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=nargs,
const=const,
default=default,
type=type,
choices=choices,
required=required,
help=help,
metavar=metavar)
def __call__(self, parser, namespace, values, option_string=None):
items = _copy.copy(_ensure_value(namespace, self.dest, []))
items.append(values)
setattr(namespace, self.dest, items)
class _AppendConstAction(Action):
def __init__(self,
option_strings,
dest,
const,
default=None,
required=False,
help=None,
metavar=None):
super(_AppendConstAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=0,
const=const,
default=default,
required=required,
help=help,
metavar=metavar)
def __call__(self, parser, namespace, values, option_string=None):
items = _copy.copy(_ensure_value(namespace, self.dest, []))
items.append(self.const)
setattr(namespace, self.dest, items)
class _CountAction(Action):
def __init__(self,
option_strings,
dest,
default=None,
required=False,
help=None):
super(_CountAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=0,
default=default,
required=required,
help=help)
def __call__(self, parser, namespace, values, option_string=None):
new_count = _ensure_value(namespace, self.dest, 0) + 1
setattr(namespace, self.dest, new_count)
class _HelpAction(Action):
def __init__(self,
option_strings,
dest=SUPPRESS,
default=SUPPRESS,
help=None):
super(_HelpAction, self).__init__(
option_strings=option_strings,
dest=dest,
default=default,
nargs=0,
help=help)
def __call__(self, parser, namespace, values, option_string=None):
parser.print_help()
parser.exit()
class _VersionAction(Action):
def __init__(self,
option_strings,
version=None,
dest=SUPPRESS,
default=SUPPRESS,
help="show program's version number and exit"):
super(_VersionAction, self).__init__(
option_strings=option_strings,
dest=dest,
default=default,
nargs=0,
help=help)
self.version = version
def __call__(self, parser, namespace, values, option_string=None):
version = self.version
if version is None:
version = parser.version
formatter = parser._get_formatter()
formatter.add_text(version)
parser.exit(message=formatter.format_help())
class _SubParsersAction(Action):
class _ChoicesPseudoAction(Action):
def __init__(self, name, help):
sup = super(_SubParsersAction._ChoicesPseudoAction, self)
sup.__init__(option_strings=[], dest=name, help=help)
def __init__(self,
option_strings,
prog,
parser_class,
dest=SUPPRESS,
help=None,
metavar=None):
self._prog_prefix = prog
self._parser_class = parser_class
self._name_parser_map = {}
self._choices_actions = []
super(_SubParsersAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=PARSER,
choices=self._name_parser_map,
help=help,
metavar=metavar)
def add_parser(self, name, **kwargs):
# set prog from the existing prefix
if kwargs.get('prog') is None:
kwargs['prog'] = '%s %s' % (self._prog_prefix, name)
# create a pseudo-action to hold the choice help
if 'help' in kwargs:
help = kwargs.pop('help')
choice_action = self._ChoicesPseudoAction(name, help)
self._choices_actions.append(choice_action)
# create the parser and add it to the map
parser = self._parser_class(**kwargs)
self._name_parser_map[name] = parser
return parser
def _get_subactions(self):
return self._choices_actions
def __call__(self, parser, namespace, values, option_string=None):
parser_name = values[0]
arg_strings = values[1:]
# set the parser name if requested
if self.dest is not SUPPRESS:
setattr(namespace, self.dest, parser_name)
# select the parser
try:
parser = self._name_parser_map[parser_name]
except KeyError:
tup = parser_name, ', '.join(self._name_parser_map)
msg = _('unknown parser %r (choices: %s)' % tup)
raise ArgumentError(self, msg)
# parse all the remaining options into the namespace
# store any unrecognized options on the object, so that the top
# level parser can decide what to do with them
namespace, arg_strings = parser.parse_known_args(arg_strings, namespace)
if arg_strings:
vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])
getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)
# ==============
# Type classes
# ==============
class FileType(object):
"""Factory for creating file object types
Instances of FileType are typically passed as type= arguments to the
ArgumentParser add_argument() method.
Keyword Arguments:
- mode -- A string indicating how the file is to be opened. Accepts the
same values as the builtin open() function.
- bufsize -- The file's desired buffer size. Accepts the same values as
the builtin open() function.
"""
def __init__(self, mode='r', bufsize=None):
self._mode = mode
self._bufsize = bufsize
def __call__(self, string):
# the special argument "-" means sys.std{in,out}
if string == '-':
if 'r' in self._mode:
return _sys.stdin
elif 'w' in self._mode:
return _sys.stdout
else:
msg = _('argument "-" with mode %r' % self._mode)
raise ValueError(msg)
# all other arguments are used as file names
if self._bufsize:
return open(string, self._mode, self._bufsize)
else:
return open(string, self._mode)
def __repr__(self):
args = [self._mode, self._bufsize]
args_str = ', '.join([repr(arg) for arg in args if arg is not None])
return '%s(%s)' % (type(self).__name__, args_str)
# ===========================
# Optional and Positional Parsing
# ===========================
class Namespace(_AttributeHolder):
"""Simple object for storing attributes.
Implements equality by attribute names and values, and provides a simple
string representation.
"""
def __init__(self, **kwargs):
for name in kwargs:
setattr(self, name, kwargs[name])
__hash__ = None
def __eq__(self, other):
return vars(self) == vars(other)
def __ne__(self, other):
return not (self == other)
def __contains__(self, key):
return key in self.__dict__
class _ActionsContainer(object):
def __init__(self,
description,
prefix_chars,
argument_default,
conflict_handler):
super(_ActionsContainer, self).__init__()
self.description = description
self.argument_default = argument_default
self.prefix_chars = prefix_chars
self.conflict_handler = conflict_handler
# set up registries
self._registries = {}
# register actions
self.register('action', None, _StoreAction)
self.register('action', 'store', _StoreAction)
self.register('action', 'store_const', _StoreConstAction)
self.register('action', 'store_true', _StoreTrueAction)
self.register('action', 'store_false', _StoreFalseAction)
self.register('action', 'append', _AppendAction)
self.register('action', 'append_const', _AppendConstAction)
self.register('action', 'count', _CountAction)
self.register('action', 'help', _HelpAction)
self.register('action', 'version', _VersionAction)
self.register('action', 'parsers', _SubParsersAction)
# raise an exception if the conflict handler is invalid
self._get_handler()
# action storage
self._actions = []
self._option_string_actions = {}
# groups
self._action_groups = []
self._mutually_exclusive_groups = []
# defaults storage
self._defaults = {}
# determines whether an "option" looks like a negative number
self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$')
# whether or not there are any optionals that look like negative
# numbers -- uses a list so it can be shared and edited
self._has_negative_number_optionals = []
# ====================
# Registration methods
# ====================
def register(self, registry_name, value, object):
registry = self._registries.setdefault(registry_name, {})
registry[value] = object
def _registry_get(self, registry_name, value, default=None):
return self._registries[registry_name].get(value, default)
# ==================================
# Namespace default accessor methods
# ==================================
def set_defaults(self, **kwargs):
self._defaults.update(kwargs)
# if these defaults match any existing arguments, replace
# the previous default on the object with the new one
for action in self._actions:
if action.dest in kwargs:
action.default = kwargs[action.dest]
def get_default(self, dest):
for action in self._actions:
if action.dest == dest and action.default is not None:
return action.default
return self._defaults.get(dest, None)
# =======================
# Adding argument actions
# =======================
def add_argument(self, *args, **kwargs):
"""
add_argument(dest, ..., name=value, ...)
add_argument(option_string, option_string, ..., name=value, ...)
"""
# if no positional args are supplied or only one is supplied and
# it doesn't look like an option string, parse a positional
# argument
chars = self.prefix_chars
if not args or len(args) == 1 and args[0][0] not in chars:
if args and 'dest' in kwargs:
raise ValueError('dest supplied twice for positional argument')
kwargs = self._get_positional_kwargs(*args, **kwargs)
# otherwise, we're adding an optional argument
else:
kwargs = self._get_optional_kwargs(*args, **kwargs)
# if no default was supplied, use the parser-level default
if 'default' not in kwargs:
dest = kwargs['dest']
if dest in self._defaults:
kwargs['default'] = self._defaults[dest]
elif self.argument_default is not None:
kwargs['default'] = self.argument_default
# create the action object, and add it to the parser
action_class = self._pop_action_class(kwargs)
if not _callable(action_class):
raise ValueError('unknown action "%s"' % action_class)
action = action_class(**kwargs)
# raise an error if the action type is not callable
type_func = self._registry_get('type', action.type, action.type)
if not _callable(type_func):
raise ValueError('%r is not callable' % type_func)
return self._add_action(action)
def add_argument_group(self, *args, **kwargs):
group = _ArgumentGroup(self, *args, **kwargs)
self._action_groups.append(group)
return group
def add_mutually_exclusive_group(self, **kwargs):
group = _MutuallyExclusiveGroup(self, **kwargs)
self._mutually_exclusive_groups.append(group)
return group
def _add_action(self, action):
# resolve any conflicts
self._check_conflict(action)
# add to actions list
self._actions.append(action)
action.container = self
# index the action by any option strings it has
for option_string in action.option_strings:
self._option_string_actions[option_string] = action
# set the flag if any option strings look like negative numbers
for option_string in action.option_strings:
if self._negative_number_matcher.match(option_string):
if not self._has_negative_number_optionals:
self._has_negative_number_optionals.append(True)
# return the created action
return action
def _remove_action(self, action):
self._actions.remove(action)
def _add_container_actions(self, container):
# collect groups by titles
title_group_map = {}
for group in self._action_groups:
if group.title in title_group_map:
msg = _('cannot merge actions - two groups are named %r')
raise ValueError(msg % (group.title))
title_group_map[group.title] = group
# map each action to its group
group_map = {}
for group in container._action_groups:
# if a group with the title exists, use that, otherwise
# create a new group matching the container's group
if group.title not in title_group_map:
title_group_map[group.title] = self.add_argument_group(
title=group.title,
description=group.description,
conflict_handler=group.conflict_handler)
# map the actions to their new group
for action in group._group_actions:
group_map[action] = title_group_map[group.title]
# add container's mutually exclusive groups
# NOTE: if add_mutually_exclusive_group ever gains title= and
# description= then this code will need to be expanded as above
for group in container._mutually_exclusive_groups:
mutex_group = self.add_mutually_exclusive_group(
required=group.required)
# map the actions to their new mutex group
for action in group._group_actions:
group_map[action] = mutex_group
# add all actions to this container or their group
for action in container._actions:
group_map.get(action, self)._add_action(action)
def _get_positional_kwargs(self, dest, **kwargs):
# make sure required is not specified
if 'required' in kwargs:
msg = _("'required' is an invalid argument for positionals")
raise TypeError(msg)
# mark positional arguments as required if at least one is
# always required
if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:
kwargs['required'] = True
if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:
kwargs['required'] = True
# return the keyword arguments with no option strings
return dict(kwargs, dest=dest, option_strings=[])
def _get_optional_kwargs(self, *args, **kwargs):
# determine short and long option strings
option_strings = []
long_option_strings = []
for option_string in args:
# error on strings that don't start with an appropriate prefix
if not option_string[0] in self.prefix_chars:
msg = _('invalid option string %r: '
'must start with a character %r')
tup = option_string, self.prefix_chars
raise ValueError(msg % tup)
# strings starting with two prefix characters are long options
option_strings.append(option_string)
if option_string[0] in self.prefix_chars:
if len(option_string) > 1:
if option_string[1] in self.prefix_chars:
long_option_strings.append(option_string)
# infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
dest = kwargs.pop('dest', None)
if dest is None:
if long_option_strings:
dest_option_string = long_option_strings[0]
else:
dest_option_string = option_strings[0]
dest = dest_option_string.lstrip(self.prefix_chars)
if not dest:
msg = _('dest= is required for options like %r')
raise ValueError(msg % option_string)
dest = dest.replace('-', '_')
# return the updated keyword arguments
return dict(kwargs, dest=dest, option_strings=option_strings)
def _pop_action_class(self, kwargs, default=None):
action = kwargs.pop('action', default)
return self._registry_get('action', action, action)
def _get_handler(self):
# determine function from conflict handler string
handler_func_name = '_handle_conflict_%s' % self.conflict_handler
try:
return getattr(self, handler_func_name)
except AttributeError:
msg = _('invalid conflict_resolution value: %r')
raise ValueError(msg % self.conflict_handler)
def _check_conflict(self, action):
# find all options that conflict with this option
confl_optionals = []
for option_string in action.option_strings:
if option_string in self._option_string_actions:
confl_optional = self._option_string_actions[option_string]
confl_optionals.append((option_string, confl_optional))
# resolve any conflicts
if confl_optionals:
conflict_handler = self._get_handler()
conflict_handler(action, confl_optionals)
def _handle_conflict_error(self, action, conflicting_actions):
message = _('conflicting option string(s): %s')
conflict_string = ', '.join([option_string
for option_string, action
in conflicting_actions])
raise ArgumentError(action, message % conflict_string)
def _handle_conflict_resolve(self, action, conflicting_actions):
# remove all conflicting options
for option_string, action in conflicting_actions:
# remove the conflicting option
action.option_strings.remove(option_string)
self._option_string_actions.pop(option_string, None)
# if the option now has no option string, remove it from the
# container holding it
if not action.option_strings:
action.container._remove_action(action)
class _ArgumentGroup(_ActionsContainer):
def __init__(self, container, title=None, description=None, **kwargs):
# add any missing keyword arguments by checking the container
update = kwargs.setdefault
update('conflict_handler', container.conflict_handler)
update('prefix_chars', container.prefix_chars)
update('argument_default', container.argument_default)
super_init = super(_ArgumentGroup, self).__init__
super_init(description=description, **kwargs)
# group attributes
self.title = title
self._group_actions = []
# share most attributes with the container
self._registries = container._registries
self._actions = container._actions
self._option_string_actions = container._option_string_actions
self._defaults = container._defaults
self._has_negative_number_optionals = \
container._has_negative_number_optionals
def _add_action(self, action):
action = super(_ArgumentGroup, self)._add_action(action)
self._group_actions.append(action)
return action
def _remove_action(self, action):
super(_ArgumentGroup, self)._remove_action(action)
self._group_actions.remove(action)
class _MutuallyExclusiveGroup(_ArgumentGroup):
def __init__(self, container, required=False):
super(_MutuallyExclusiveGroup, self).__init__(container)
self.required = required
self._container = container
def _add_action(self, action):
if action.required:
msg = _('mutually exclusive arguments must be optional')
raise ValueError(msg)
action = self._container._add_action(action)
self._group_actions.append(action)
return action
def _remove_action(self, action):
self._container._remove_action(action)
self._group_actions.remove(action)
class ArgumentParser(_AttributeHolder, _ActionsContainer):
"""Object for parsing command line strings into Python objects.
Keyword Arguments:
- prog -- The name of the program (default: sys.argv[0])
- usage -- A usage message (default: auto-generated from arguments)
- description -- A description of what the program does
- epilog -- Text following the argument descriptions
- parents -- Parsers whose arguments should be copied into this one
- formatter_class -- HelpFormatter class for printing help messages
- prefix_chars -- Characters that prefix optional arguments
- fromfile_prefix_chars -- Characters that prefix files containing
additional arguments
- argument_default -- The default value for all arguments
- conflict_handler -- String indicating how to handle conflicts
- add_help -- Add a -h/-help option
"""
def __init__(self,
prog=None,
usage=None,
description=None,
epilog=None,
version=None,
parents=[],
formatter_class=HelpFormatter,
prefix_chars='-',
fromfile_prefix_chars=None,
argument_default=None,
conflict_handler='error',
add_help=True):
if version is not None:
import warnings
warnings.warn(
"""The "version" argument to ArgumentParser is deprecated. """
"""Please use """
""""add_argument(..., action='version', version="N", ...)" """
"""instead""", DeprecationWarning)
superinit = super(ArgumentParser, self).__init__
superinit(description=description,
prefix_chars=prefix_chars,
argument_default=argument_default,
conflict_handler=conflict_handler)
# default setting for prog
if prog is None:
prog = _os.path.basename(_sys.argv[0])
self.prog = prog
self.usage = usage
self.epilog = epilog
self.version = version
self.formatter_class = formatter_class
self.fromfile_prefix_chars = fromfile_prefix_chars
self.add_help = add_help
add_group = self.add_argument_group
self._positionals = add_group(_('positional arguments'))
self._optionals = add_group(_('optional arguments'))
self._subparsers = None
# register types
def identity(string):
return string
self.register('type', None, identity)
# add help and version arguments if necessary
# (using explicit default to override global argument_default)
default_prefix = '-' if '-' in prefix_chars else prefix_chars[0]
if self.add_help:
self.add_argument(
default_prefix+'h', default_prefix*2+'help',
action='help', default=SUPPRESS,
help=_('show this help message and exit'))
if self.version:
self.add_argument(
default_prefix+'v', default_prefix*2+'version',
action='version', default=SUPPRESS,
version=self.version,
help=_("show program's version number and exit"))
# add parent arguments and defaults
for parent in parents:
self._add_container_actions(parent)
try:
defaults = parent._defaults
except AttributeError:
pass
else:
self._defaults.update(defaults)
# =======================
# Pretty __repr__ methods
# =======================
def _get_kwargs(self):
names = [
'prog',
'usage',
'description',
'version',
'formatter_class',
'conflict_handler',
'add_help',
]
return [(name, getattr(self, name)) for name in names]
# ==================================
# Optional/Positional adding methods
# ==================================
def add_subparsers(self, **kwargs):
if self._subparsers is not None:
self.error(_('cannot have multiple subparser arguments'))
# add the parser class to the arguments if it's not present
kwargs.setdefault('parser_class', type(self))
if 'title' in kwargs or 'description' in kwargs:
title = _(kwargs.pop('title', 'subcommands'))
description = _(kwargs.pop('description', None))
self._subparsers = self.add_argument_group(title, description)
else:
self._subparsers = self._positionals
# prog defaults to the usage message of this parser, skipping
# optional arguments and with no "usage:" prefix
if kwargs.get('prog') is None:
formatter = self._get_formatter()
positionals = self._get_positional_actions()
groups = self._mutually_exclusive_groups
formatter.add_usage(self.usage, positionals, groups, '')
kwargs['prog'] = formatter.format_help().strip()
# create the parsers action and add it to the positionals list
parsers_class = self._pop_action_class(kwargs, 'parsers')
action = parsers_class(option_strings=[], **kwargs)
self._subparsers._add_action(action)
# return the created parsers action
return action
def _add_action(self, action):
if action.option_strings:
self._optionals._add_action(action)
else:
self._positionals._add_action(action)
return action
def _get_optional_actions(self):
return [action
for action in self._actions
if action.option_strings]
def _get_positional_actions(self):
return [action
for action in self._actions
if not action.option_strings]
# =====================================
# Command line argument parsing methods
# =====================================
def parse_args(self, args=None, namespace=None):
args, argv = self.parse_known_args(args, namespace)
if argv:
msg = _('unrecognized arguments: %s')
self.error(msg % ' '.join(argv))
return args
def parse_known_args(self, args=None, namespace=None):
# args default to the system args
if args is None:
args = _sys.argv[1:]
# default Namespace built from parser defaults
if namespace is None:
namespace = Namespace()
# add any action defaults that aren't present
for action in self._actions:
if action.dest is not SUPPRESS:
if not hasattr(namespace, action.dest):
if action.default is not SUPPRESS:
default = action.default
if isinstance(action.default, basestring):
default = self._get_value(action, default)
setattr(namespace, action.dest, default)
# add any parser defaults that aren't present
for dest in self._defaults:
if not hasattr(namespace, dest):
setattr(namespace, dest, self._defaults[dest])
# parse the arguments and exit if there are any errors
try:
namespace, args = self._parse_known_args(args, namespace)
if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
return namespace, args
except ArgumentError:
err = _sys.exc_info()[1]
self.error(str(err))
def _parse_known_args(self, arg_strings, namespace):
# replace arg strings that are file references
if self.fromfile_prefix_chars is not None:
arg_strings = self._read_args_from_files(arg_strings)
# map all mutually exclusive arguments to the other arguments
# they can't occur with
action_conflicts = {}
for mutex_group in self._mutually_exclusive_groups:
group_actions = mutex_group._group_actions
for i, mutex_action in enumerate(mutex_group._group_actions):
conflicts = action_conflicts.setdefault(mutex_action, [])
conflicts.extend(group_actions[:i])
conflicts.extend(group_actions[i + 1:])
# find all option indices, and determine the arg_string_pattern
# which has an 'O' if there is an option at an index,
# an 'A' if there is an argument, or a '-' if there is a '--'
option_string_indices = {}
arg_string_pattern_parts = []
arg_strings_iter = iter(arg_strings)
for i, arg_string in enumerate(arg_strings_iter):
# all args after -- are non-options
if arg_string == '--':
arg_string_pattern_parts.append('-')
for arg_string in arg_strings_iter:
arg_string_pattern_parts.append('A')
# otherwise, add the arg to the arg strings
# and note the index if it was an option
else:
option_tuple = self._parse_optional(arg_string)
if option_tuple is None:
pattern = 'A'
else:
option_string_indices[i] = option_tuple
pattern = 'O'
arg_string_pattern_parts.append(pattern)
# join the pieces together to form the pattern
arg_strings_pattern = ''.join(arg_string_pattern_parts)
# converts arg strings to the appropriate and then takes the action
seen_actions = set()
seen_non_default_actions = set()
def take_action(action, argument_strings, option_string=None):
seen_actions.add(action)
argument_values = self._get_values(action, argument_strings)
# error if this argument is not allowed with other previously
# seen arguments, assuming that actions that use the default
# value don't really count as "present"
if argument_values is not action.default:
seen_non_default_actions.add(action)
for conflict_action in action_conflicts.get(action, []):
if conflict_action in seen_non_default_actions:
msg = _('not allowed with argument %s')
action_name = _get_action_name(conflict_action)
raise ArgumentError(action, msg % action_name)
# take the action if we didn't receive a SUPPRESS value
# (e.g. from a default)
if argument_values is not SUPPRESS:
action(self, namespace, argument_values, option_string)
# function to convert arg_strings into an optional action
def consume_optional(start_index):
# get the optional identified at this index
option_tuple = option_string_indices[start_index]
action, option_string, explicit_arg = option_tuple
# identify additional optionals in the same arg string
# (e.g. -xyz is the same as -x -y -z if no args are required)
match_argument = self._match_argument
action_tuples = []
while True:
# if we found no optional action, skip it
if action is None:
extras.append(arg_strings[start_index])
return start_index + 1
# if there is an explicit argument, try to match the
# optional's string arguments to only this
if explicit_arg is not None:
arg_count = match_argument(action, 'A')
# if the action is a single-dash option and takes no
# arguments, try to parse more single-dash options out
# of the tail of the option string
chars = self.prefix_chars
if arg_count == 0 and option_string[1] not in chars:
action_tuples.append((action, [], option_string))
char = option_string[0]
option_string = char + explicit_arg[0]
new_explicit_arg = explicit_arg[1:] or None
optionals_map = self._option_string_actions
if option_string in optionals_map:
action = optionals_map[option_string]
explicit_arg = new_explicit_arg
else:
msg = _('ignored explicit argument %r')
raise ArgumentError(action, msg % explicit_arg)
# if the action expect exactly one argument, we've
# successfully matched the option; exit the loop
elif arg_count == 1:
stop = start_index + 1
args = [explicit_arg]
action_tuples.append((action, args, option_string))
break
# error if a double-dash option did not use the
# explicit argument
else:
msg = _('ignored explicit argument %r')
raise ArgumentError(action, msg % explicit_arg)
# if there is no explicit argument, try to match the
# optional's string arguments with the following strings
# if successful, exit the loop
else:
start = start_index + 1
selected_patterns = arg_strings_pattern[start:]
arg_count = match_argument(action, selected_patterns)
stop = start + arg_count
args = arg_strings[start:stop]
action_tuples.append((action, args, option_string))
break
# add the Optional to the list and return the index at which
# the Optional's string args stopped
assert action_tuples
for action, args, option_string in action_tuples:
take_action(action, args, option_string)
return stop
# the list of Positionals left to be parsed; this is modified
# by consume_positionals()
positionals = self._get_positional_actions()
# function to convert arg_strings into positional actions
def consume_positionals(start_index):
# match as many Positionals as possible
match_partial = self._match_arguments_partial
selected_pattern = arg_strings_pattern[start_index:]
arg_counts = match_partial(positionals, selected_pattern)
# slice off the appropriate arg strings for each Positional
# and add the Positional and its args to the list
for action, arg_count in zip(positionals, arg_counts):
args = arg_strings[start_index: start_index + arg_count]
start_index += arg_count
take_action(action, args)
# slice off the Positionals that we just parsed and return the
# index at which the Positionals' string args stopped
positionals[:] = positionals[len(arg_counts):]
return start_index
# consume Positionals and Optionals alternately, until we have
# passed the last option string
extras = []
start_index = 0
if option_string_indices:
max_option_string_index = max(option_string_indices)
else:
max_option_string_index = -1
while start_index <= max_option_string_index:
# consume any Positionals preceding the next option
next_option_string_index = min([
index
for index in option_string_indices
if index >= start_index])
if start_index != next_option_string_index:
positionals_end_index = consume_positionals(start_index)
# only try to parse the next optional if we didn't consume
# the option string during the positionals parsing
if positionals_end_index > start_index:
start_index = positionals_end_index
continue
else:
start_index = positionals_end_index
# if we consumed all the positionals we could and we're not
# at the index of an option string, there were extra arguments
if start_index not in option_string_indices:
strings = arg_strings[start_index:next_option_string_index]
extras.extend(strings)
start_index = next_option_string_index
# consume the next optional and any arguments for it
start_index = consume_optional(start_index)
# consume any positionals following the last Optional
stop_index = consume_positionals(start_index)
# if we didn't consume all the argument strings, there were extras
extras.extend(arg_strings[stop_index:])
# if we didn't use all the Positional objects, there were too few
# arg strings supplied.
if positionals:
self.error(_('too few arguments'))
# make sure all required actions were present
for action in self._actions:
if action.required:
if action not in seen_actions:
name = _get_action_name(action)
self.error(_('argument %s is required') % name)
# make sure all required groups had one option present
for group in self._mutually_exclusive_groups:
if group.required:
for action in group._group_actions:
if action in seen_non_default_actions:
break
# if no actions were used, report the error
else:
names = [_get_action_name(action)
for action in group._group_actions
if action.help is not SUPPRESS]
msg = _('one of the arguments %s is required')
self.error(msg % ' '.join(names))
# return the updated namespace and the extra arguments
return namespace, extras
def _read_args_from_files(self, arg_strings):
# expand arguments referencing files
new_arg_strings = []
for arg_string in arg_strings:
# for regular arguments, just add them back into the list
if arg_string[0] not in self.fromfile_prefix_chars:
new_arg_strings.append(arg_string)
# replace arguments referencing files with the file content
else:
try:
args_file = open(arg_string[1:])
try:
arg_strings = []
for arg_line in args_file.read().splitlines():
for arg in self.convert_arg_line_to_args(arg_line):
arg_strings.append(arg)
arg_strings = self._read_args_from_files(arg_strings)
new_arg_strings.extend(arg_strings)
finally:
args_file.close()
except IOError:
err = _sys.exc_info()[1]
self.error(str(err))
# return the modified argument list
return new_arg_strings
def convert_arg_line_to_args(self, arg_line):
return [arg_line]
def _match_argument(self, action, arg_strings_pattern):
# match the pattern for this action to the arg strings
nargs_pattern = self._get_nargs_pattern(action)
match = _re.match(nargs_pattern, arg_strings_pattern)
# raise an exception if we weren't able to find a match
if match is None:
nargs_errors = {
None: _('expected one argument'),
OPTIONAL: _('expected at most one argument'),
ONE_OR_MORE: _('expected at least one argument'),
}
default = _('expected %s argument(s)') % action.nargs
msg = nargs_errors.get(action.nargs, default)
raise ArgumentError(action, msg)
# return the number of arguments matched
return len(match.group(1))
def _match_arguments_partial(self, actions, arg_strings_pattern):
# progressively shorten the actions list by slicing off the
# final actions until we find a match
result = []
for i in range(len(actions), 0, -1):
actions_slice = actions[:i]
pattern = ''.join([self._get_nargs_pattern(action)
for action in actions_slice])
match = _re.match(pattern, arg_strings_pattern)
if match is not None:
result.extend([len(string) for string in match.groups()])
break
# return the list of arg string counts
return result
def _parse_optional(self, arg_string):
# if it's an empty string, it was meant to be a positional
if not arg_string:
return None
# if it doesn't start with a prefix, it was meant to be positional
if not arg_string[0] in self.prefix_chars:
return None
# if the option string is present in the parser, return the action
if arg_string in self._option_string_actions:
action = self._option_string_actions[arg_string]
return action, arg_string, None
# if it's just a single character, it was meant to be positional
if len(arg_string) == 1:
return None
# if the option string before the "=" is present, return the action
if '=' in arg_string:
option_string, explicit_arg = arg_string.split('=', 1)
if option_string in self._option_string_actions:
action = self._option_string_actions[option_string]
return action, option_string, explicit_arg
# search through all possible prefixes of the option string
# and all actions in the parser for possible interpretations
option_tuples = self._get_option_tuples(arg_string)
# if multiple actions match, the option string was ambiguous
if len(option_tuples) > 1:
options = ', '.join([option_string
for action, option_string, explicit_arg in option_tuples])
tup = arg_string, options
self.error(_('ambiguous option: %s could match %s') % tup)
# if exactly one action matched, this segmentation is good,
# so return the parsed action
elif len(option_tuples) == 1:
option_tuple, = option_tuples
return option_tuple
# if it was not found as an option, but it looks like a negative
# number, it was meant to be positional
# unless there are negative-number-like options
if self._negative_number_matcher.match(arg_string):
if not self._has_negative_number_optionals:
return None
# if it contains a space, it was meant to be a positional
if ' ' in arg_string:
return None
# it was meant to be an optional but there is no such option
# in this parser (though it might be a valid option in a subparser)
return None, arg_string, None
def _get_option_tuples(self, option_string):
result = []
# option strings starting with two prefix characters are only
# split at the '='
chars = self.prefix_chars
if option_string[0] in chars and option_string[1] in chars:
if '=' in option_string:
option_prefix, explicit_arg = option_string.split('=', 1)
else:
option_prefix = option_string
explicit_arg = None
for option_string in self._option_string_actions:
if option_string.startswith(option_prefix):
action = self._option_string_actions[option_string]
tup = action, option_string, explicit_arg
result.append(tup)
# single character options can be concatenated with their arguments
# but multiple character options always have to have their argument
# separate
elif option_string[0] in chars and option_string[1] not in chars:
option_prefix = option_string
explicit_arg = None
short_option_prefix = option_string[:2]
short_explicit_arg = option_string[2:]
for option_string in self._option_string_actions:
if option_string == short_option_prefix:
action = self._option_string_actions[option_string]
tup = action, option_string, short_explicit_arg
result.append(tup)
elif option_string.startswith(option_prefix):
action = self._option_string_actions[option_string]
tup = action, option_string, explicit_arg
result.append(tup)
# shouldn't ever get here
else:
self.error(_('unexpected option string: %s') % option_string)
# return the collected option tuples
return result
def _get_nargs_pattern(self, action):
# in all examples below, we have to allow for '--' args
# which are represented as '-' in the pattern
nargs = action.nargs
# the default (None) is assumed to be a single argument
if nargs is None:
nargs_pattern = '(-*A-*)'
# allow zero or one arguments
elif nargs == OPTIONAL:
nargs_pattern = '(-*A?-*)'
# allow zero or more arguments
elif nargs == ZERO_OR_MORE:
nargs_pattern = '(-*[A-]*)'
# allow one or more arguments
elif nargs == ONE_OR_MORE:
nargs_pattern = '(-*A[A-]*)'
# allow any number of options or arguments
elif nargs == REMAINDER:
nargs_pattern = '([-AO]*)'
# allow one argument followed by any number of options or arguments
elif nargs == PARSER:
nargs_pattern = '(-*A[-AO]*)'
# all others should be integers
else:
nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
# if this is an optional action, -- is not allowed
if action.option_strings:
nargs_pattern = nargs_pattern.replace('-*', '')
nargs_pattern = nargs_pattern.replace('-', '')
# return the pattern
return nargs_pattern
# ========================
# Value conversion methods
# ========================
def _get_values(self, action, arg_strings):
# for everything but PARSER args, strip out '--'
if action.nargs not in [PARSER, REMAINDER]:
arg_strings = [s for s in arg_strings if s != '--']
# optional argument produces a default when not present
if not arg_strings and action.nargs == OPTIONAL:
if action.option_strings:
value = action.const
else:
value = action.default
if isinstance(value, basestring):
value = self._get_value(action, value)
self._check_value(action, value)
# when nargs='*' on a positional, if there were no command-line
# args, use the default if it is anything other than None
elif (not arg_strings and action.nargs == ZERO_OR_MORE and
not action.option_strings):
if action.default is not None:
value = action.default
else:
value = arg_strings
self._check_value(action, value)
# single argument or optional argument produces a single value
elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:
arg_string, = arg_strings
value = self._get_value(action, arg_string)
self._check_value(action, value)
# REMAINDER arguments convert all values, checking none
elif action.nargs == REMAINDER:
value = [self._get_value(action, v) for v in arg_strings]
# PARSER arguments convert all values, but check only the first
elif action.nargs == PARSER:
value = [self._get_value(action, v) for v in arg_strings]
self._check_value(action, value[0])
# all other types of nargs produce a list
else:
value = [self._get_value(action, v) for v in arg_strings]
for v in value:
self._check_value(action, v)
# return the converted value
return value
def _get_value(self, action, arg_string):
type_func = self._registry_get('type', action.type, action.type)
if not _callable(type_func):
msg = _('%r is not callable')
raise ArgumentError(action, msg % type_func)
# convert the value to the appropriate type
try:
result = type_func(arg_string)
# ArgumentTypeErrors indicate errors
except ArgumentTypeError:
name = getattr(action.type, '__name__', repr(action.type))
msg = str(_sys.exc_info()[1])
raise ArgumentError(action, msg)
# TypeErrors or ValueErrors also indicate errors
except (TypeError, ValueError):
name = getattr(action.type, '__name__', repr(action.type))
msg = _('invalid %s value: %r')
raise ArgumentError(action, msg % (name, arg_string))
# return the converted value
return result
def _check_value(self, action, value):
# converted value must be one of the choices (if specified)
if action.choices is not None and value not in action.choices:
tup = value, ', '.join(map(repr, action.choices))
msg = _('invalid choice: %r (choose from %s)') % tup
raise ArgumentError(action, msg)
# =======================
# Help-formatting methods
# =======================
def format_usage(self):
formatter = self._get_formatter()
formatter.add_usage(self.usage, self._actions,
self._mutually_exclusive_groups)
return formatter.format_help()
def format_help(self):
formatter = self._get_formatter()
# usage
formatter.add_usage(self.usage, self._actions,
self._mutually_exclusive_groups)
# description
formatter.add_text(self.description)
# positionals, optionals and user-defined groups
for action_group in self._action_groups:
formatter.start_section(action_group.title)
formatter.add_text(action_group.description)
formatter.add_arguments(action_group._group_actions)
formatter.end_section()
# epilog
formatter.add_text(self.epilog)
# determine help from format above
return formatter.format_help()
def format_version(self):
import warnings
warnings.warn(
'The format_version method is deprecated -- the "version" '
'argument to ArgumentParser is no longer supported.',
DeprecationWarning)
formatter = self._get_formatter()
formatter.add_text(self.version)
return formatter.format_help()
def _get_formatter(self):
return self.formatter_class(prog=self.prog)
# =====================
# Help-printing methods
# =====================
def print_usage(self, file=None):
if file is None:
file = _sys.stdout
self._print_message(self.format_usage(), file)
def print_help(self, file=None):
if file is None:
file = _sys.stdout
self._print_message(self.format_help(), file)
def print_version(self, file=None):
import warnings
warnings.warn(
'The print_version method is deprecated -- the "version" '
'argument to ArgumentParser is no longer supported.',
DeprecationWarning)
self._print_message(self.format_version(), file)
def _print_message(self, message, file=None):
if message:
if file is None:
file = _sys.stderr
file.write(message)
# ===============
# Exiting methods
# ===============
def exit(self, status=0, message=None):
if message:
self._print_message(message, _sys.stderr)
_sys.exit(status)
def error(self, message):
"""error(message: string)
Prints a usage message incorporating the message to stderr and
exits.
If you override this in a subclass, it should not return -- it
should either exit or raise an exception.
"""
self.print_usage(_sys.stderr)
self.exit(2, _('%s: error: %s\n') % (self.prog, message))
| Python |
"""Read and cache directory listings.
The listdir() routine returns a sorted list of the files in a directory,
using a cache to avoid reading the directory more often than necessary.
The annotate() routine appends slashes to directories."""
from warnings import warnpy3k
warnpy3k("the dircache module has been removed in Python 3.0", stacklevel=2)
del warnpy3k
import os
__all__ = ["listdir", "opendir", "annotate", "reset"]
cache = {}
def reset():
"""Reset the cache completely."""
global cache
cache = {}
def listdir(path):
"""List directory contents, using cache."""
try:
cached_mtime, list = cache[path]
del cache[path]
except KeyError:
cached_mtime, list = -1, []
mtime = os.stat(path).st_mtime
if mtime != cached_mtime:
list = os.listdir(path)
list.sort()
cache[path] = mtime, list
return list
opendir = listdir # XXX backward compatibility
def annotate(head, list):
"""Add '/' suffixes to directories."""
for i in range(len(list)):
if os.path.isdir(os.path.join(head, list[i])):
list[i] = list[i] + '/'
| Python |
"""Backport of importlib.import_module from 3.x."""
# While not critical (and in no way guaranteed!), it would be nice to keep this
# code compatible with Python 2.3.
import sys
def _resolve_name(name, package, level):
"""Return the absolute name of the module to be imported."""
if not hasattr(package, 'rindex'):
raise ValueError("'package' not set to a string")
dot = len(package)
for x in xrange(level, 1, -1):
try:
dot = package.rindex('.', 0, dot)
except ValueError:
raise ValueError("attempted relative import beyond top-level "
"package")
return "%s.%s" % (package[:dot], name)
def import_module(name, package=None):
"""Import a module.
The 'package' argument is required when performing a relative import. It
specifies the package to use as the anchor point from which to resolve the
relative import to an absolute import.
"""
if name.startswith('.'):
if not package:
raise TypeError("relative imports require the 'package' argument")
level = 0
for character in name:
if character != '.':
break
level += 1
name = _resolve_name(name[level:], package, level)
__import__(name)
return sys.modules[name]
| Python |
# Access WeakSet through the weakref module.
# This code is separated-out because it is needed
# by abc.py to load everything else at startup.
from _weakref import ref
__all__ = ['WeakSet']
class _IterationGuard(object):
# This context manager registers itself in the current iterators of the
# weak container, such as to delay all removals until the context manager
# exits.
# This technique should be relatively thread-safe (since sets are).
def __init__(self, weakcontainer):
# Don't create cycles
self.weakcontainer = ref(weakcontainer)
def __enter__(self):
w = self.weakcontainer()
if w is not None:
w._iterating.add(self)
return self
def __exit__(self, e, t, b):
w = self.weakcontainer()
if w is not None:
s = w._iterating
s.remove(self)
if not s:
w._commit_removals()
class WeakSet(object):
def __init__(self, data=None):
self.data = set()
def _remove(item, selfref=ref(self)):
self = selfref()
if self is not None:
if self._iterating:
self._pending_removals.append(item)
else:
self.data.discard(item)
self._remove = _remove
# A list of keys to be removed
self._pending_removals = []
self._iterating = set()
if data is not None:
self.update(data)
def _commit_removals(self):
l = self._pending_removals
discard = self.data.discard
while l:
discard(l.pop())
def __iter__(self):
with _IterationGuard(self):
for itemref in self.data:
item = itemref()
if item is not None:
yield item
def __len__(self):
return sum(x() is not None for x in self.data)
def __contains__(self, item):
return ref(item) in self.data
def __reduce__(self):
return (self.__class__, (list(self),),
getattr(self, '__dict__', None))
__hash__ = None
def add(self, item):
if self._pending_removals:
self._commit_removals()
self.data.add(ref(item, self._remove))
def clear(self):
if self._pending_removals:
self._commit_removals()
self.data.clear()
def copy(self):
return self.__class__(self)
def pop(self):
if self._pending_removals:
self._commit_removals()
while True:
try:
itemref = self.data.pop()
except KeyError:
raise KeyError('pop from empty WeakSet')
item = itemref()
if item is not None:
return item
def remove(self, item):
if self._pending_removals:
self._commit_removals()
self.data.remove(ref(item))
def discard(self, item):
if self._pending_removals:
self._commit_removals()
self.data.discard(ref(item))
def update(self, other):
if self._pending_removals:
self._commit_removals()
if isinstance(other, self.__class__):
self.data.update(other.data)
else:
for element in other:
self.add(element)
def __ior__(self, other):
self.update(other)
return self
# Helper functions for simple delegating methods.
def _apply(self, other, method):
if not isinstance(other, self.__class__):
other = self.__class__(other)
newdata = method(other.data)
newset = self.__class__()
newset.data = newdata
return newset
def difference(self, other):
return self._apply(other, self.data.difference)
__sub__ = difference
def difference_update(self, other):
if self._pending_removals:
self._commit_removals()
if self is other:
self.data.clear()
else:
self.data.difference_update(ref(item) for item in other)
def __isub__(self, other):
if self._pending_removals:
self._commit_removals()
if self is other:
self.data.clear()
else:
self.data.difference_update(ref(item) for item in other)
return self
def intersection(self, other):
return self._apply(other, self.data.intersection)
__and__ = intersection
def intersection_update(self, other):
if self._pending_removals:
self._commit_removals()
self.data.intersection_update(ref(item) for item in other)
def __iand__(self, other):
if self._pending_removals:
self._commit_removals()
self.data.intersection_update(ref(item) for item in other)
return self
def issubset(self, other):
return self.data.issubset(ref(item) for item in other)
__lt__ = issubset
def __le__(self, other):
return self.data <= set(ref(item) for item in other)
def issuperset(self, other):
return self.data.issuperset(ref(item) for item in other)
__gt__ = issuperset
def __ge__(self, other):
return self.data >= set(ref(item) for item in other)
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return self.data == set(ref(item) for item in other)
def symmetric_difference(self, other):
return self._apply(other, self.data.symmetric_difference)
__xor__ = symmetric_difference
def symmetric_difference_update(self, other):
if self._pending_removals:
self._commit_removals()
if self is other:
self.data.clear()
else:
self.data.symmetric_difference_update(ref(item) for item in other)
def __ixor__(self, other):
if self._pending_removals:
self._commit_removals()
if self is other:
self.data.clear()
else:
self.data.symmetric_difference_update(ref(item) for item in other)
return self
def union(self, other):
return self._apply(other, self.data.union)
__or__ = union
def isdisjoint(self, other):
return len(self.intersection(other)) == 0
| Python |
import kf_lib_v2_2 as lib
import gzip
import urllib2
import thread
import time
WX_base = "http://aviationweather.gov/adds/dataserver_current/current/%s.cache.csv.gz"
WX_ADDRESSES = dict(metar="metars", pirep="aircraftreports",
taf="tafs", airmet="airsigmets")
class weather:
def __init__(self, forceDownload=True):
self.avWeather={}
print "Downloading weather: "
for wxType, addy in WX_ADDRESSES.iteritems():
thread.start_new_thread(self._download_and_unpack, (wxType, addy))
while set(WX_ADDRESSES.keys()) - set(self.avWeather.keys()):
time.sleep(.5)
print "Done"
def _download_and_unpack(self, wxType, addy):
#print "Downloading:", wxType,
f_gz = urllib2.urlopen(WX_base % addy)
lib.write_file_and_save("wx/" + addy + ".csv", f_gz.read(), 'wb')
f = gzip.open("wx/" + addy + ".csv", 'rb')
lib.write_file_and_save("wx/" + addy + ".csv", f.read(), 'wb')
xl=lib.readExcelTable("wx/" + addy + ".csv")
self.avWeather[wxType] = xl.readSheet('', 5)
print wxType + ", ", | Python |
"""*****************************************************************************
WARNING
Copyright 2012 Hamilton Sundstrand Corporation. This document is the
property of Hamilton Sundstrand Corporation ("HSC"). You may not possess,
use, copy or disclose this document or any information in it, for any
purpose, including without limitation, to design, manufacture or repair
parts, or obtain any government approval to do so, without HSC's express
written permission. Neither receipt nor possession of this document
alone, from any source, constitutes such permission. Possession, use,
copying or disclosure by anyone without HSC's express written permission
is not authorized and may result in criminal and/or civil liability.
********************************************************************************
********************************
* *
* kf_lib *
* *
********************************
Author(s): Kevin Fritz
********************************************************************************
Description:
kf_lib provides a set of common functions and classes to simplify Scripting in
Python . The main purpose for this library is to enhance and simplify the lower-level
interface to excel through the readExcelTable and createExcelTable classes. These
classes require the installation of the common libraries: xlrd and xlwt.
********************************************************************************
Revision History
*******************************************************************************/
Rev Author Date Description
-------------------------------------------------------------------------------
v1.7 Kevin Fritz 1/12/11 Base
v1.8 Kevin Fritz 3/11/11 Added CSV support, Modified readExcelTable
v2.0 Kevin Fritz 6/14/11 Added obj support for read/write to excel
Added transpose function
Added sort function
Removed numArraySort function
v2.1 Kevin Fritz 5/23/12 Modified BufferTypeRW to allow more input types
Modified Obj to accommodate list of obj conversion
Added XMl_node function for easily creating xml data
Modified readExcelTable, bugfix on colstart
Modified createExcelTable formula and merge support
read/write file added error and check_path support
/***************************************************************************"""
__version__ = 2.2
import struct,copy,binascii, time, re #import standard python libraries
import xml.dom.minidom as XML
#---------------------------------------------------------------------------------------------------
#General
def trim(string): #removes leading and trailing spaces from a string
if len(string)>0:
if string[0] in [' ','\n']: return trim(string[1:])
elif string[-1] in [' ','\n']: return trim(string[:-1])
return string
#---------------------------------------------------------------------------------------------------
#Interface to Windows OS
def getWin32ClipboardText():
import win32clipboard as w
import win32con
w.OpenClipboard()
d=w.GetClipboardData(win32con.CF_TEXT)
w.CloseClipboard()
return d
def setWin32ClipboardText(aType,aString):
import win32clipboard as w
import win32con
w.OpenClipboard()
w.EmptyClipboard()
w.SetClipboardData(aType,aString)
w.CloseClipboard()
def checkpath(filename): #simple utility which checks if all folders are created for a path
import os
if filename.rfind("\\") != (-1) :
folder=filename[:filename.rfind("\\")]
if os.access(folder, os.F_OK) :
#print 1, filename
return filename
else:
try:
os.mkdir(folder)
return filename
except:
a=checkpath(folder[:folder.rfind("\\")] + "\\") #edit by Udit
#print 2, filename
#print folder+" p "
return checkpath(filename) #edit by Udit
#return filename #edit by Udit
else:
return filename
def findFiles(path, option):
#This function recursively scans through the directory structure to find all
# files or folders matching the criteria of the variable option, as defined below
# if option = a list of strings: return a list of all files with these extensions
# if option = a string with "." in it, return a list of all files with that extension
# if option = "All_Folders": return a list of the paths for all folders and subfolders
# if option = "Leaf_Folders": return a list of the paths for folders which do not contain folders
# returns a list of the file paths
import os
if path[-1] == "\\": path = path[:-1] #strip off the last backslash
result=[] # a list containing all file paths found during execution
filetypes=[] # a list containing all extension being looked for (in lowercase)
if type(option)==list: # if searching for folders, make list case-insensitive
for ext in option: # iterate over all extensions passed in
filetypes+= [ext.lower()] # convert to lowercase
elif type(option)==str and "." in option: # if option is a string and contains a period
filetypes = [option] # convert option to a single-element list of string
if "*.*" in filetypes: # if searching for all files
filetypes=["."] # then just look for a "."
for filex in os.listdir(path): # iterate over every file or folder in current directory
if len(filetypes) > 0: # if option specifies a list of extensions then:
if filex[filex.rfind("."):] in filetypes: # if current entry is a file whose extension is in filetypes:
result+=[path+"\\"+filex] # add the full path to the results list
elif "." not in filex: # if this is a folder
result += findFiles(path+"\\"+filex, option) # get list of all elements in subfolder
elif option.lower() == "all_folders": # option specifies all folders
if "." not in filex: # filex is a folder
result += [path+"\\"+filex] + findFiles(path+"\\"+filex, option) # add current path and all sub-folders
elif option.lower() =="leaf_folders": # option specifying only folders that contain only files
if "." not in filex: # filex is a folder
nestedfolders = findFiles(path+"\\"+filex, option) # get list of all sub folders
# IF there are no sub-folders, add current path, ELSE add all sub-folders to result
result+= nestedfolders if nestedfolders != [] else [path+"\\"+filex]
return result
#---------------------------------------------------------------------------------------------------
#Data Types
class obj(): #Creates an empty data structure, adds attributes
#credit: http://mail.python.org/pipermail/python-bugs-list/2007-January/036866.html
def __init__(self,*args,**kwargs):
for arg in args:
arg = copy.copy(arg)
if type(arg) == dict: kwargs.update(arg) #argument is dictionary, convert
elif type(arg) == obj: kwargs.update(arg.dict()) #argument is obj, copy to self
elif type(arg) == list and len(args) == 1: #argument is list with one entry
return [obj(x) for x in arg] #return list, recursivly calling self on each element
self.__dict__=kwargs #append all keyword argument(s) to self, if any
def __str__(self): return "lib.obj(%r)" % self.__dict__
def __repr__(self): return "lib.obj(%r)" % self.__dict__
def dict(self): #return a dictionary version of self
return self.__dict__
#---------------------------------------------------------------------------------------------------
#Log and Console interface
class printBoth():
#provides a class for printing to both console and log at once
def __init__(self, logfn):
self.txt=""
self.logfn=logfn
def bprint(self,*text):
for x in list(text) + ["\n"]: print x,
self.txt+= "%s\n" % "\t".join([str(x) for x in text])
def bp(self,*text): self.bprint(*text)
def close(self):
l=open(self.logfn,'w')
l.flush()
l.write(self.txt)
l.close()
#---------------------------------------------------------------------------------------------------
#code algorithms for working with lists
def createNDarray(dims, default=None): # creates an N-dimensional array, given an array of the dims
#creates an N-dimensional array of type default
if dims==[] or type(dims) != list:
return default
else:
result=[]
for i in range(dims[0]): result+=[createNDarray(dims[1:], default)]
return result
def chunk(array, interval, combine_fnc=lambda x:x): #breaks a list into chunks of size interval
#array must be list or string type
if type(array) not in [list, str]: return None
superset=[]
subset=[]
for i,x in enumerate(array):
subset.append(x)
if len(subset) == interval or i+1 == len(array) :
superset.append(subset)
subset=[]
return [combine_fnc(element) for element in superset]
def unique_list(iterable): #reduces a list into a list of every unique value it contains
return reduce(lambda ulist, val: ulist + ([val] if val not in ulist else []), iterable, [])
def make_hierarchial_dict(dataset, keys): #converts list of dict into hierarchial dict
#dataset is list of dict, keys refers to attributes within each dict.
#This function creates a structure where data is sorted first by key[0]
error_msg='"dataset" must be list of dict, and "keys" must be list of keys from that dict'
if type(dataset) != list or type(keys) != list: raise NameError(error_msg)
if len(keys) == 0: return dataset #termination point of recursion
result={} #construct first level of hiearchy
for row in dataset: #linear scan through dataset, make dict from first search param
if type(row) != dict and keys[0] in row.keys(): raise NameError(error_msg) #row must be type dict
if row[keys[0]] not in result.keys(): result[row[keys[0]]] = []
result[row[keys[0]]].append(row) #place row in dict
#recursively construct lower levels of hierarchy
for key, val in result.iteritems(): result[key]=make_hierarchial_dict(val, keys[1:])
return result
def transpose(#transposes a list of lists
matrix, # list of lists being transposed
filler = []): #
if type(matrix) != list and len(matrix) and unique_list(map(type, matrix)) == [list]:
raise NameError("matrix parameter must be list of lists")
if type(filler) != list: filler = [filler]
return map(list, zip(*(filler + matrix)))
def sort(dataset, #list data structure to be sorted. may be list of dict or list of obj
keys): #list of sort keys, prefix key with "!" for descending order
#sorts a data set by one or more attributes, in ascending or descending for each
if type(keys) != list or not len(keys): return dataset #termination point of recursion
if unique_list(map(type, keys)) != [str] : raise NameError("keys must be list of strings")
if type(dataset) != list or unique_list(map(type, dataset)) not in [[dict], [obj]]:
raise NameError("dataset must be of type: list of dict, or list of obj")
#exclamation flag reverses sort order
if keys[0].startswith("!"): reverse = True; keys[0] = keys[0][1:]
else: reverse = False
entrytype = unique_list(map(type, dataset))[0]
dataset = make_hierarchial_dict(map(dict, dataset), keys[:1]) #convert to list of dict, hash
sorted_keys = sorted(dataset.keys(), reverse=reverse)
sorted_dataset = [sort(dataset[key], keys[1:]) for key in sorted_keys]
return map(entrytype, reduce(list.__add__, sorted_dataset, [])) # convert to orig type & concatenate
#---------------------------------------------------------------------------------------------------
#Functions for working with xml files
def XMl_node(_name, _attr = {}, _txt = None, _parent=None, _children=[], **kwargs):
if isinstance(_name, XML.Node): node = _name #update an already supplied node
else: node = XML.Document().createElement(_name)
if _txt:
node.appendChild(XML.Document().createTextNode(_txt))
if type(_attr) == dict:
for param, value in _attr.iteritems():
node.setAttribute(param, str(value))
for param, value in kwargs.iteritems():
node.setAttribute(param, str(value))
if isinstance(_parent, XML.Node): _parent.appendChild(node)
if type(_children) == list:
for child in _children:
if isinstance(child, XML.Node): node.appendChild(child)
return node
#---------------------------------------------------------------------------------------------------
#Functions and Classes for working with Binary files
def asc2hex(ascval): # converts each byte from 0x45 to "45", and place in array
return ["%02X" % ord(x) for x in ascval]
def vals2hex(vals):
result=""
for row in chunk(vals,16): #16 bytes per row
for val in row: result+=hex(val)[2:].rjust(2,"0").upper() + " "
result+="\n"
return result[:-2] #strip off last space and carriage return
class BufferType_RW (): #a class for creating and interpretting binary data from python data types
def __init__(self, val="", bigend=True, start=0):
if type(bigend) != bool: raise NameError('endianness type is not a boolean')
self.rw_index = 0
self.end=">" if bigend else "<"
self.start=start
#inputs
if type(val) == str:
if re.match("\A([0-9A-F]{2}\s)+[0-9A-F]{2}\Z", trim(val)): #whitespace delimited hex bytes
val = "".join([chr(eval("0x" + byte)) for byte in re.split("\s+", trim(val))])
self.val = str(val)
elif isinstance(val, BufferType_RW): #user passed in an instance of BufferTypeRW
self = val # copy instance to self
elif type(val) == list and type(val[0]) == int:
try: self.val = "".join([chr(x) for x in val])
except: raise NameError('Initialization Value is not a String')
else: raise NameError('Initialization Value is not a String')
self.end=">" if bigend else "<"
self.start=start
self.KnownVarTypes=set('Uint8,Uint16,Uint32,Int8,Int16,Int32,String,\
Enum,Bool,Pad,Float32,Float64'.split(","))
# add methods for basic python functions
def __len__(self): return len(self.val) #allows for len(self)
def __str__(self): return self.val #allows for str(self)
def __repr__(self): return repr(self.val) #allows for repr(self)
#def __getattr__(self, name): return self.val[name] #allows for x= self[name]
#def __setattr__(self, name, value): self.val[name] = value #allows for self[name]=value
# overload '+' operator
def __add__(self,other): # allow for concatenation of buffers
result = copy.copy(self)
result.val += str(other)
result.rw_index=result.length()
return result
# internal-use only methods
def __packunpack(self, fmt, value=None, insert = True):
if value != None: #pack
if type(value) == list: #if argument is list, iterate over each element
for x in value: self.__packunpack(fmt, x)
else:
packedresult="".join(list(struct.pack(self.end + fmt, value)))
before, after = self.val[:self.rw_index], self.val[self.rw_index:]
if insert: self.val = before + packedresult + after #insert packedresult
else: self.val = before + packedresult + after[len(packedresult):]#insert as an overwrite
if insert: self.rw_index+=len(packedresult) #else don't move ptr
else: #unpack
return list(struct.unpack(self.end + fmt, self.GetVals(struct.calcsize(fmt))))[0]
#External methods
def GetVals(self, num_bytes): #returns a string of length num_bytes, start at ptr
if self.rw_index + num_bytes <= self.length:
result=self.val[self.rw_index: self.rw_index+num_bytes]
self.rw_index+=num_bytes
return result
else: return None
def String(self, arg, null_bytes = 1):
if type(arg) == str:#write to self
self.val +=arg + "\0"*null_bytes
self.rw_index+=len(arg) + null_bytes
elif type(arg) == int: #read from self
self.rw_index+=arg
return self.val[self.rw_index- arg:self.rw_index]
else: raise NameError("String Method needs int to unpack chars, or string to pack")
def Buffer(self, num_bytes, offset=0):
self.rw_index+=offset
start=self.start + self.rw_index
endtypeconv={">":True, "<":False}
return BufferType_RW(self.GetVals(num_bytes), endtypeconv[self.end], start)
def align(self,numbytes): self.val+= "\0" * (self.length() % numbytes)
def consume_pad(self, alignment): #skips ptr ahead to consume pad bytes
if self.rw_index % alignment:
self.rw_index += alignment - self.rw_index % alignment
#Get info about buffer
def ptr(self): return self.start+self.rw_index #current memory position
def length(self): return len(self.val)
def num_Bytes_Left(self): return self.length() - (self.rw_index)
def Leftover_Bytes(self): return self.String(self.num_Bytes_Left(),0)
def HexDump(self, num_bytes = None, include_header = True, bytes_per_row = 16):
if include_header:
result = "Offset: " + " ".join(["%02X" % x for x in range(bytes_per_row)])
result += "\n" + "0x".center(8," ") + "-"*(3*bytes_per_row) + "\n"
else: result = ""
start = self.rw_index
if num_bytes and type(num_bytes) == int:
bytes_to_print = self.String(num_bytes, 0)
elif num_bytes == None: bytes_to_print = self.String(self.num_Bytes_Left(),0)
else: raise NameError("num_bytes param must be int or None")
for i,row in enumerate(chunk(bytes_to_print, bytes_per_row)):
result+= "%06X" % (start + i*bytes_per_row) + ": "
for char in row: result += "%02X " % ord(char)
result+="\n"
return result
def Pad24(self, *args): return self.String("\0\0\0" if len(args) else 3, null_bytes = 0)
#add stubs for some basic varible types
def Uint8(self, value=None, insert = True): return self.__packunpack("B", value, insert = insert)
def Uint16(self, value=None, insert = True): return self.__packunpack("H", value, insert = insert)
def Uint32(self, value=None, insert = True): return self.__packunpack("I", value, insert = insert)
def Int8(self, value=None, insert = True): return self.__packunpack("b", value, insert = insert)
def Int16(self, value=None, insert = True): return self.__packunpack("h", value, insert = insert)
def Int32(self, value=None, insert = True): return self.__packunpack("i", value, insert = insert)
def Float32(self, value=None, insert = True): return self.__packunpack("f", value, insert = insert)
def Float64(self, value=None, insert = True): return self.__packunpack("d", value, insert = insert)
def Bool(self, value=None, insert = True): return self.__packunpack("?", value, insert = insert)
def BitField(self, value = None, insert=True): #converts list of bool to/from buf
if type(value) == list: #array of bits to pack
#value = [False] * (len(value) % 8) + value
for byte in lib.chunk(value, 8):
self.Uint8(sum([2**i if bit else 0 for i, bit in enumerate(byte)]))
elif type(value) == int: #number of bytes to unpack
all_bits = []
for i in range(value):
bits = [int(bit) for bit in bin(self.Uint8())[2:]]
all_bits += [0] * (8 - len(bits) % 8) + bits #left-pad, push
return all_bits
def By_VarType(self, var_type, value=None): #calls a var method using a variable
# ie: self.By_VarType("Uint32") is the same as self.Uint32()
if var_type in self.KnownVarTypes: return getattr(self, var_type)(value)
else: raise NameError("%s")
def HexString(self, num): return "0x" + "".join(["%02X"%ord(x) for x in self.GetVals(num)])
def CRC16(self, polynomial):
crc=reduce(self.val, lambda x,y: x^polynomial(y))
#crc=binascii.crc32(self.val) & 0xFFFFFFFF #get CRC32
self.Uint16(crc) # insert CRC32 at position of rw_index
return "0x%08X" % crc #return CRC in hex string format
def CRC32(self):
crc=binascii.crc32(self.val) & 0xFFFFFFFF #get CRC32, uses Ethernet standard for CRC
self.Uint32(crc) # insert CRC32 at position of rw_index
return "0x%08X" % crc #return CRC in hex string format
def floatstrip(x):
return str(int(x)) if float(x) == int(float(x)) else str(x)
#---------------------------------------------------------------------------------------------------
#Code for working with Excel Files
def convXLRowColRef(XLref): #converts the excel row/col notation to integers for each
#Reads in a cell reference in the format of a letter(s) then numbers, as is used in excel
#returns a dictionary object
[row,col]=[0,0] #initialize values
for x in XLref.lower():
if str.isalpha(x): col = col * 26 + (ord(x) - 96)
elif str.isdigit(x): row = row * 10 + int(x)
#row/col is a 1-based reference and row0/col0 being 0-based
return {'row':row, 'col':col, 'row0':row-1, 'col0':col-1}
class libcsv:
def __init__(self,filename, method, suffix=""):
import csv
self.suffix=("-" + suffix) if len(suffix) else suffix
self.filename=".".join(filename.split(".")[:-1]) + self.suffix + "." + filename.split(".")[-1]
self.method=method
self.delim={'csv':',', 'tsv':'\t'}.get(filename.lower().split(".")[-1], ',')
self.ws = [[""]]
if type(method) == str and 'r' in method: #if using read method
try:
self.ws = list(csv.reader(open(self.filename, 'r'), delimiter=self.delim)) #see if file exists, read text
self.filefound = True
except: self.filefound = False
self.nrows = len(self.ws) # the num of rows
self.ncols = sorted([len(row) for row in self.ws])[-1] # the largest num of cols
for iR, row in enumerate(self.ws): # iterate over every row
for iC, cell in enumerate(row): # iterate over every cell in the row
try: self.ws[iR][iC]=eval(cell, {}, {}) #convert string to python types if possible
except: pass #leave cell as-is, for string and unicode types
self.wb={} #place sheet into wb collection
def sheet_by_name(self, sheetname): return self.add_sheet(sheetname) #for reading
def add_sheet(self, sheet_name): #for writing
self.wb[sheet_name] = libcsv(self.filename, self.method, sheet_name)
return self.wb[sheet_name]
def cell_value(self, row, col):
if not self.filefound: raise NameError("File Not Found: %s" % self.filename)
if row < len(self.ws) and col < len(self.ws[row]): return self.ws[row][col]
else: return ''
def write(self, row, col, value,fmt=None):
if row >= len(self.ws): self.ws += [[''] for x in range(row - len(self.ws) + 1)]
if col >= len(self.ws[row]): self.ws[row] += ['' for x in range(col - len(self.ws[row]) + 1)]
self.ws[row][col] = value
def save(self, filename=''):
filename = self.filename
if self.ws != [['']]:
delim={'csv':',', 'tsv':'\t'}.get(filename.lower().split(".")[-1], ',')
for iR, row in enumerate(self.ws): # iterate over every row
for iC, cell in enumerate(row): # iterate over every cell in the row
if type(cell) not in [str, unicode]: #if not string or unicode
self.ws[iR][iC] = repr(cell) #convert python types -> string
elif cell != '': self.ws[iR][iC] = '"%s"' % cell # leave as string
#convert 2D table to string and encode to ascii file
write_file_and_save(filename, "\n".join([self.delim.join(row) for row in self.ws]), 'w')
for name, sheet in self.wb.iteritems():
sheet.save()
class readExcelTable: #reads the rows in excel files as dictionary objects based on filename and sheet name
def __init__(self,filename):#initializes class
if filename.lower().split(".")[-1] in ['xls']:
import xlrd
self.wb=xlrd.open_workbook(filename) #open an excel workbook
else: self.wb=libcsv(filename, 'r') #to read CSV files
self.iR={}#row read pointer
self.ws={}#stores the worksheet
self.info={}#contains sheet info (nrows, ncols, rowstart, colstart, colheads)
self.data={}#stores an (list of dict) for each sheetEPC
self.objdata={} #a dictionary by sheet of a list of objects
self.array={} # a dictionary by sheet of a 2D array of the sheet's data.
def listOfSheets(self): return map(str, self.wb.sheet_names()) #returns a list of all the sheet names
def readSheet(self,sn,rowstart=0,colstart=0, row_type=dict): #reads in a sheet into self.data
if row_type not in [dict, list, obj, object]: raise NameError("row_type may only be list, dict, or obj")
if row_type == object: row_type = obj # obj and object are synonymous here.
self.ws[sn]=self.wb.sheet_by_name(sn)#get worksheet from xlrd
self.info[sn]={}
self.info[sn]['rowstart']=rowstart
self.info[sn]['colstart']=colstart
info=self.getInfo(sn)
self.data[sn]=[]
self.array[sn]=[]
#extract in list of lists format
for iR in range(rowstart,info['rows']):
#construct 2D array of data
self.array[sn].append([self.ws[sn].cell_value(iR,iC) for iC in range(info['cols'])])
#extract in list of dict format
if row_type in [obj, dict]:
for iR in range(rowstart + 1,info['rows']):
line={}#store a dict of each element
for iC in range(info['cols']):
if info['colheads'][iC] != "":
line[info['colheads'][iC]]=self.ws[sn].cell_value(iR,iC)
self.data[sn]+=[line]#add line to data
self.objdata[sn]=map(obj, self.data[sn]) #create list of obj format
self.iR[sn]=1#initialize read pointer to first row
return {list: self.array[sn], dict: self.data[sn], obj: self.objdata[sn]}[row_type]
def readCell(self, sn, *args): #read a cell or multiple cells using a couple different methods
if sn not in self.info.keys(): self.readSheet(sn) #read sheet if hasn't been yet
def is_row_col(row, col): return (type(row) == int and type(col) == int)
#if args == (row, col); return value
if len(args)==2 and is_row_col(*args):
return self.ws[sn].cell_value(*args)
#or if args[0] == (row, col); return value
elif len(args)==1 and type(args[0]) == tuple and is_row_col(*args[0]):
return self.readCell(sn, *args[0])
#or if args[0] == {key1: (row1,col1), etc...}; return {key1: value1, etc...}
elif len(args)==1 and type(args[0]) == dict:
return dict([(key,self.readCell(sn, *RwCl)) for key, RwCl in args[0].iteritems()])
# or if args[0] == list of rows #'s and args[1] == col ; return list of values
elif len(args) == 2 and type(args[0]) == list and type(args[1]) == int:
return [self.readCell(sn, row, args[1]) for row in args[0]]
# or if args[0] == row and args[1] == list of col #'s ; return list of values
elif len(args) == 2 and type(args[0]) == int and type(args[1]) == list:
return [self.readCell(sn, args[0], col) for col in args[1]]
# or if args[0] == list of row #'s and args[1] == list of col #'s ; return 2D list of values
elif len(args) == 2 and type(args[0]) == list and type(args[1]) == list:
return [self.readCell(sn, row, args[1]) for row in args[0]]
def getInfo(self,sn):#returns a dict of the sheet's info
info=self.info[sn]
info['rows']=self.ws[sn].nrows
info['cols']=self.ws[sn].ncols
info['colheads']=[]
for iC in range(info['colstart'], info['cols']):
info['colheads']+=[str(self.ws[sn].cell_value(info['rowstart'],iC))]
self.info[sn].update(info)
return info
def readLine(self,sn):#returns dict at read pointer, post increment
line=self.data[sn][self.iR[sn]]
self.iR[sn]+=1
return line
def findLine(self,sn,params,findall=False): #finds a line that matches certain params, returns dict
results=[]
for line in self.data[sn]:
paramsMatchesLine=True
for key,val in params.iteritems():
if line[key] != val: paramsMatchesLine=False
if paramsMatchesLine==True:
results+=[line]
if findall==False: return line
return results if findall else {}
class createExcelTable: #creates an Excel table
def __init__(self,filename): #initialize workbook
try: self.filename=checkpath(filename) #checks path and stores the filename for later
except: raise NameError("Invalid Path")
self.iR={}#store the write pointer
self.iRstart={} #dict of integer
self.ws={}#the collection of worksheets
self.cols={}#
self.col_fmts={}
self.formats={} #dict of formats, key is sorted lower-case easyxf text of format
self.zebra_fmt={} #dict of list of formats, assignes zebra pattern to data area
if filename.lower().split(".")[-1] in ['xls']:
import xlwt
self.wb=xlwt.Workbook() #creates a workbook
self.filetype = 'xls'
else:
self.wb=libcsv(filename, 'w') #to handle CSV files
self.filetype = 'sv'
def newSheet(self,sn,colheads=None, iRstart=0, zebra_fmt=[""], col_formats={},
header_fmt="font: bold on; pattern: pattern solid, fore-colour light-green; align: wrap on"):
self.iRstart[sn]=iRstart
self.col_fmts[sn]=col_formats
for i,val in enumerate(zebra_fmt):
zebra_fmt[i]=("pattern: pattern solid, fore-colour " + val) if len(val) else ""
self.zebra_fmt[sn]=zebra_fmt
#create a new sheet, named sn, with colheads in row 0
self.ws[sn]=self.wb.add_sheet(sn)#adds a new sheet
self.cols[sn]={}#container for column heading indecies
if colheads != None:
for i, colhead in enumerate(colheads):
self.cols[sn][colhead]=i
if colhead not in self.col_fmts[sn]: self.col_fmts[sn][colhead] = ""
self.writeCell(sn, iRstart,i, colhead, #write the column headings in row 0
self.__combine_fmts(header_fmt, self.col_fmts[sn][colhead]))
if self.filetype == 'xls':
self.ws[sn].row(iRstart).set_style(self.__formatting(header_fmt))
self.iR[sn]=iRstart+1#initialize the write pointer
return self
def writeLine(self,sn,data,formatting=""): #writes a line of data given a dict, the keys match those in colheads
if type(formatting) != str: raise NameError("formatting param may only be a string")
if type(data) == dict:
row_fmt_str=self.zebra_fmt[sn][(self.iR[sn] - self.iRstart[sn] - 1) % len(self.zebra_fmt[sn])]
if self.filetype == 'xls':
self.ws[sn].row(self.iR[sn]).set_style(self.__formatting(row_fmt_str))
formatting=self.__combine_fmts(row_fmt_str, formatting)#concatenate row and supplied formats
for key, val in data.iteritems(): #write each value to its corresponding col
if key in self.cols[sn]:
if key in self.col_fmts[sn]:
cell_formatting=self.__combine_fmts(formatting, self.col_fmts[sn][key])
else: cell_formatting=formatting
self.writeCell(sn, self.iR[sn],self.cols[sn][key],val,cell_formatting)
self.iR[sn]+=1 #increment the write pointer
elif type(data) in [obj, object]: #is lib.obj type
self.writeLine(sn, line, dict(data), formatting)
elif type(data) == list:
for line in data: self.writeLine(sn, line,formatting)
else: raise NameError("Invalid data type for data parameter")
return self
def writeCell(self,sn,row,col,val,formatting="", rowspan=1, colspan=1):
#writes a cell/row/table given a sheet, row, & col
if type(formatting) != str: raise NameError("formatting param may only be a string")
if type(rowspan) != int or rowspan < 1: rowspan = 1
if type(colspan) != int or colspan < 1: colspan = 1
if type(val) == tuple: #val is tuple, style is val = (value_to_write, formatting)
val,cell_fmt = val #unpack format string from tuple
cell_fmt=self.__combine_fmts(formatting, cell_fmt)
self.writeCell(sn,row,col,val,cell_fmt) #unpack tuple through recursion
elif type(val)==list: #val is list
if unique_list(map(type, val)) != [list]: #val is 1D list, interpret as table
for i,v in zip(range(len(val)),val): self.writeCell(sn,row,col+i,v,formatting)
else: #val is 2D list, interpret as row
for i,v in zip(range(len(val)),val): self.writeCell(sn,row+i,col,v,formatting)
elif type(val) in [unicode,str, int, float, bool]: #val is string, int, float, or bool
if type(val) in [unicode, str] and val.startswith('=') and self.filetype == 'xls': #if this is a text formula
import xlwt
val=xlwt.Formula(val[1:]) #convert to formula type
if rowspan > 1 or colspan > 1:
self.ws[sn].write_merge(row, row + rowspan - 1, #a rowspan of 1 means 1 row
col, col + colspan - 1, #a colspan of 1 means 1 col
val, self.__formatting(formatting)) #make call to xlwt layer
else:
self.ws[sn].write(row,col,val, self.__formatting(formatting)) #make call to xlwt layer
elif type(val)==type(None): pass #don't write to the cell
elif type(val)==dict: #val is dictionary, coder was dumb and used wrong class method
raise NameError("use writeLine instead of writeCell method when passing a dict object")
else: raise NameError("Could not recognize Val parameter")
return self
def __combine_fmts(self,*args):
fmt_list=[]
for x in args:
for y in x.split(";"):
if len(trim(y)): fmt_list+=[trim(y)]
return "; ".join(fmt_list)
def __formatting(self,fmt_string):
if self.filetype == 'sv': return object()
from xlwt import easyxf, Style
if isinstance(fmt_string, Style.XFStyle): return fmt_string
elif type(fmt_string) == str:
#check to see if formatting has been used before
if fmt_string not in self.formats.keys(): #add formatting object to dictionary
self.formats[fmt_string]= easyxf(fmt_string)
return self.formats[fmt_string]
else: raise NameError("fmt_string param couldn't be recognized")
def ColWidth(self, sn, widths):
if sn not in self.ws.keys(): raise NameError("Sheet not Found")
if not isinstance(widths, dict): raise NameError("Widths param not dict")
for col,width in widths.iteritems():
if type(col) == str: col=self.cols[sn][col]
if self.filetype == 'xls': self.ws[sn].col(col).width=int(width*36.3)
def GetWSobject(self, sn): return self.ws[sn] # returns ws object for any optional xlwt formatting
def List_Colors(self):
if self.filetype == 'sv': return []
import xlwt
return sorted(xlwt.Style.colour_map.keys())
def close(self): #save and close the workbook
import time
try: self.wb.save(self.filename)
except:
print "Could not save %s." % self.filename
print "Is this file open somewhere? Close to continue"
while True:
try:
self.wb.save(self.filename)
break
except: time.sleep(.1) #slow the app down to checking every 100ms to conserve CPU
#---------------------------------------------------------------------------------------------------
#File I/O
headertxt="""/*
********************************************************************************
WARNING
Copyright %s Hamilton Sundstrand Corporation. This document is the
property of Hamilton Sundstrand Corporation ("HSC"). You may not possess,
use, copy or disclose this document or any information in it, for any
purpose, including without limitation, to design, manufacture or repair
parts, or obtain any government approval to do so, without HSC's express
written permission. Neither receipt nor possession of this document
alone, from any source, constitutes such permission. Possession, use,
copying or disclosure by anyone without HSC's express written permission
is not authorized and may result in criminal and/or civil liability.
********************************************************************************
********************************
* *
*%s*
* *
********************************
Author(s): %s
********************************************************************************
Description:
%s
********************************************************************************
Revision History
*******************************************************************************/
/*$Log:$ */
/******************************************************************************/\n\n\n
""" # C-code header
def write_file_and_save(filename, data, write_method = 'w'):
filename = filename.replace("/", "\\")
try:
f=open(checkpath(filename), write_method)
f.write(str(data))
f.close()
return True
except: return False
def read_file_and_close(filename, read_method = 'r'):
filename = filename.replace("/", "\\")
try: return open(filename, read_method).read()
except: return False
def C_header(filename, author, desc, content=""):
module = filename.lower().split(".")[0].upper()
result = headertxt % (time.strftime("%Y"), filename.center(30), author, desc) #add header
if filename.lower().split(".")[-1] == 'h': #if this is a header file, add macro
result += "#ifndef %s\n#define %s\n\n" % (module, module) + content + "\n#endif"
else: result += content
return result
#written by Josh Deblon
def file_is_empty(path):
import os
return os.stat(path).st_size==0
| Python |
# -*- coding: iso-8859-15 -*-
import vue
import flocking
import SETTINGS
class Controleur(object):
def __init__(self):
self.modele = flocking.Modele(self)
self.vue = vue.Vue(self)
self.loopControle()
self.vue.root.mainloop()
def loopControle(self):
self.modele.animate()
self.vue.afficher()
self.vue.root.after(SETTINGS.VITESSE_LOOP,self.loopControle)
def getFlock(self):
return self.modele.flock.flock
def getPredateurs(self):
return self.modele.predateurs
if __name__ == "__main__":
ctrl = Controleur() | Python |
# -*- coding: iso-8859-15 -*-
import moteur
import SETTINGS
from Tkinter import *
class Vue(object):
def __init__(self, ctrl):
self.ctrl = ctrl
self.root = Tk()
self.frameSettings()
self.canvas = Canvas(self.root, width=SETTINGS.LARGEUR, height=SETTINGS.HAUTEUR, bd=2, relief=GROOVE)
self.canvas.pack()
self.camera = moteur.Camera(SETTINGS.XCAM,SETTINGS.YCAM,SETTINGS.ZCAM)
self.camera.centrerOeil(SETTINGS.HAUTEUR, SETTINGS.LARGEUR)
self.camera.milieu.x = SETTINGS.DISPERSION/2
self.camera.milieu.y = SETTINGS.DISPERSION/2
self.camera.milieu.z = SETTINGS.DISPERSION/2
self.root.bind("<Key-+>", self.zoomIn)
self.root.bind("<Key-->", self.zoomOut)
self.canvas.bind("<B3-Motion>", self.rotate)
self.canvas.bind("<B1-Motion>", self.bouger)
self.mouseX = 0
self.mouseY = 0
def frameSettings(self):
settings = Frame(self.root)
lperception = Label(settings, text="Distance de perception:").grid(row=0, column=0)
self.tperception = Entry(settings)
self.tperception.grid(row=0, column=1)
ldistanceConfort = Label(settings, text="Distance de confort:").grid(row=1, column=0)
self.tdistanceConfort = Entry(settings)
self.tdistanceConfort.grid(row=1, column=1)
lmilieu = Label(settings, text="Ajustement vers milieu:").grid(row=2, column=0)
self.tmilieu = Entry(settings)
self.tmilieu.grid(row=2, column=1)
lajustementDirection = Label(settings, text="Ajustement de direction:").grid(row=3, column=0)
self.tajustementDirection = Entry(settings)
self.tajustementDirection.grid(row=3, column=1)
lajustementConfort = Label(settings, text="Ajustement de confort:").grid(row=4, column=0)
self.tajustementConfort = Entry(settings)
self.tajustementConfort.grid(row=4, column=1)
lvitesse = Label(settings, text="Vitesse:").grid(row=5, column=0)
self.tvitesse = Entry(settings)
self.tvitesse.grid(row=5, column=1)
self.tperception.bind("<Return>", self.perception)
self.tperception.insert(0, str(SETTINGS.PERCEPTION_INDIVIDUS))
self.tdistanceConfort.bind("<Return>",self.distanceConfort)
self.tdistanceConfort.insert(0, str(SETTINGS.DISTANCE_CONFORT))
self.tmilieu.bind("<Return>",self.milieu)
self.tmilieu.insert(0, str(SETTINGS.AJUSTEMENT_MILIEU))
self.tajustementDirection.bind("<Return>",self.ajustementDirection)
self.tajustementDirection.insert(0, str(SETTINGS.AJUSTEMENT_DIRECTION))
self.tajustementConfort.bind("<Return>",self.ajustementConfort)
self.tajustementConfort.insert(0, str(SETTINGS.AJUSTEMENT_CONFORT))
self.tvitesse.bind("<Return>",self.vitesse)
self.tvitesse.insert(0, str(SETTINGS.VITESSE_INDIVIDUS))
settings.pack()
def perception(self, event):
SETTINGS.PERCEPTION_INDIVIDUS = int(self.tperception.get())
self.root.focus()
def distanceConfort(self, event):
SETTINGS.DISTANCE_CONFORT = int(self.tdistanceConfort.get())
self.root.focus()
def milieu(self, event):
SETTINGS.AJUSTEMENT_MILIEU = float(self.tmilieu.get())
self.root.focus()
def ajustementDirection(self, event):
SETTINGS.AJUSTEMENT_DIRECTION = float(self.tajustementDirection.get())
self.root.focus()
def ajustementConfort(self, event):
SETTINGS.AJUSTEMENT_CONFORT = float(self.tajustementConfort.get())
self.root.focus()
def vitesse(self, event):
SETTINGS.VITESSE_INDIVIDUS = int(self.tvitesse.get())
self.root.focus()
def zoomOut(self, event):
self.camera.bougerZ(-100)
def zoomIn(self, event):
self.camera.bougerZ(100)
def rotate(self, event):
if event.x > self.mouseX+2:
self.camera.yawer(-0.02)
elif event.x < self.mouseX-2:
self.camera.yawer(0.02)
if event.y > self.mouseY+2:
self.camera.pitcher(-0.02)
elif event.y < self.mouseY-2:
self.camera.pitcher(0.02)
self.mouseX = event.x
self.mouseY = event.y
def bouger(self, event):
if event.x > self.mouseX+2:
self.camera.bougerX(-20)
elif event.x < self.mouseX-2:
self.camera.bougerX(20)
if event.y > self.mouseY+2:
self.camera.bougerY(20)
elif event.y < self.mouseY-2:
self.camera.bougerY(-20)
self.mouseX = event.x
self.mouseY = event.y
def afficher(self):
self.canvas.delete(ALL)
flock = self.ctrl.getFlock()
liste = moteur.toEcran(self.camera, flock)
for individu in liste:
distance = self.camera.z - individu.z
if distance <> 0:
self.canvas.create_rectangle(individu.x, individu.y, individu.x+(1000/-distance)+2, individu.y+(1000/-distance)+2, fill = SETTINGS.COULEUR)
liste = self.ctrl.getPredateurs()
liste = moteur.toEcran(self.camera, liste)
#for pred in liste:
# self.canvas.create_oval(pred.x, pred.y, pred.x+pred.z/50+5, pred.y+pred.z/50+5) | Python |
# -*- coding: iso-8859-15 -*-
"@author: Benoit L.-Dufresne"
import random
import math
class Camera(object):
def __init__(self,x=0,y=0,z=-200, roll=0, yaw=0, pitch=0):
self.x = x
self.y = y
self.z = z
self.roll = roll #Roll: tourner autour de l'axe z (se toucher l'epaule avec les oreilles
self.yaw = yaw #Yaw: tourner autour de l'axe y (faire non avec la tete)
self.pitch = pitch #Pitch: tourner autour de l'axe x (regarder en haut, regarder en bas)
self.oeil = Point(200,200,300)
self.milieu = Point(0,0,0)
##L'oeil sert de reference pour la transposition des coordonnees sur l'ecran
def centrerOeil(self, hauteur, largeur):
self.oeil.x = largeur/2
self.oeil.y = hauteur/2
def rouler(self, angle):
self.roll += angle
##Axe des Z -> Ne devrait pas etre utile pour galax, on devrait pouvoir se contenter de pitch et yaw
def pitcher(self, angle):
x2 = self.x - self.milieu.x
y2 = self.y - self.milieu.y
z2 = self.z - self.milieu.z
# x = math.sin(angle)*z + math.cos(angle)*x
# z = math.cos(angle)*z - math.sin(angle)*x
x = x2
y = y2 * math.cos(-angle) - z2 * math.sin(-angle)
z = y2 * math.sin(-angle) + z2 * math.cos(-angle)
x2 = z * math.sin(0) + x * math.cos(0)
y2 = y
z2 = z * math.cos(0) - x * math.sin(0)
x = y2 * math.sin(0) + x2 * math.cos(0)
y = y2 * math.cos(0) - x2 * math.sin(0)
z = z2;
self.x = x+self.milieu.x
self.y = y+self.milieu.y
self.z = z+self.milieu.z
self.pitch += angle
##Axe des X
def yawer(self, angle):
#On applique ensuite les rotations sur les points pour avoir leur position relative
#a la camera qui a peut-etre effectue une rotation
x2 = self.x - self.milieu.x
y2 = self.y - self.milieu.y
z2 = self.z - self.milieu.z
# x = math.sin(angle)*z + math.cos(angle)*x
# z = math.cos(angle)*z - math.sin(angle)*x
x = z2 * math.sin(-angle) + x2 * math.cos(-angle)
y = y2
z = z2 * math.cos(-angle) - x2 * math.sin(-angle)
x2 = x
y2 = y * math.cos(0) - z * math.sin(0)
z2 = y * math.sin(0) + z * math.cos(0)
x = y2 * math.sin(0) + x2 * math.cos(0)
y = y2 * math.cos(0) - x2 * math.sin(0)
z = z2;
self.x = x+self.milieu.x
self.y = y+self.milieu.y
self.z = z+self.milieu.z
self.yaw += angle
##Axe des Y
##Fonction pour bouger la camera
def bougerX(self, mouvement):
x = 0 * math.sin(-self.yaw) + mouvement * math.cos(-self.yaw)
y = 0
z = 0 * math.cos(-self.yaw) - mouvement * math.sin(-self.yaw)
x2 = x
y2 = y * math.cos(-self.pitch) - z * math.sin(-self.pitch)
z2 = y * math.sin(-self.pitch) + z * math.cos(-self.pitch)
x = y2 * math.sin(-self.roll) + x2 * math.cos(self.roll)
y = y2 * math.cos(-self.roll) - x2 * math.sin(-self.roll)
z = z2;
self.x += x
self.y += y
self.z += z
def bougerY(self, mouvement):
x2 = 0
y2 = mouvement * math.cos(-self.pitch) - 0 * math.sin(-self.pitch)
z2 = mouvement * math.sin(-self.pitch) + 0 * math.cos(-self.pitch)
x = z2 * math.sin(-self.yaw) + x2 * math.cos(-self.yaw)
y = y2
z = z2 * math.cos(-self.yaw) - x2 * math.sin(-self.yaw)
x = y2 * math.sin(-self.roll) + x2 * math.cos(-self.roll)
y = y2 * math.cos(-self.roll) - x2 * math.sin(-self.roll)
z = z2;
self.x += x
self.y += y
self.z += z
def bougerZ(self, mouvement):
x = mouvement * math.sin(-self.yaw) + 0 * math.cos(-self.yaw)
y = 0
z = mouvement * math.cos(-self.yaw) - 0 * math.sin(-self.yaw)
x2 = x
y2 = y * math.cos(-self.pitch) - z * math.sin(-self.pitch)
z2 = y * math.sin(-self.pitch) + z * math.cos(-self.pitch)
x = y2 * math.sin(-self.roll) + x2 * math.cos(-self.roll)
y = y2 * math.cos(-self.roll) - x2 * math.sin(-self.roll)
z = z2;
self.x += x
self.y += y
self.z += z
def zoom(self, zoom):
self.oeil.z += zoom
class Point(object):
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
def toEcran(camera, cercles):
#les cercles sont une liste de points ou d'objets ayant des attributs x,y et z
liste = toCamera(camera, cercles)
for cercle in liste:
cercle.x = (camera.oeil.x + cercle.x*camera.oeil.z/(cercle.z+camera.oeil.z))
cercle.y = (camera.oeil.y - cercle.y*camera.oeil.z/(cercle.z+camera.oeil.z))
return liste
def toCamera(camera, cercles):
liste=[]
for cercle in cercles:
#pour chaque point, on effectue une translation pour avoir la position de la
#camera comme origine
x2 = cercle.x - camera.x
y2 = cercle.y - camera.y
z2 = cercle.z - camera.z
#ensuite pour chaque point, on effectue une rotation pour avoir leur position
#relative a la camera qui a peut-etre effectue une rotation
x = z2 * math.sin(camera.yaw) + x2 * math.cos(camera.yaw)
y = y2
z = z2 * math.cos(camera.yaw) - x2 * math.sin(camera.yaw)
x2 = x
y2 = y * math.cos(camera.pitch) - cercle.z * math.sin(camera.pitch)
z2 = y * math.sin(camera.pitch) + cercle.z * math.cos(camera.pitch)
x = y2 * math.sin(camera.roll) + x2 * math.cos(camera.roll)
y = y2 * math.cos(camera.roll) - x2 * math.sin(camera.roll)
z = z2;
if z > 0:
liste.append(Point(x,y,z))
return liste | Python |
#! /usr/bin/env python
# flickrwatcher - Keep track of your friends' flickr photos.
# Copyright (C) 2008 Joseph G. Echeverria (joey42+flickrwatcher@gmail.com)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import os, sys, shutil, time, traceback
import urllib2
import flickrapi
import sqlite3
apiKey = 'e597cdeedb619f3f47ca999cd6f42149'
apiSecret = '578a2ab88db7e31b'
class NotConnectedException(Exception):
def __init__(self, db):
self.db = db
def __str__(self):
return self.db
class FlickrWatcherDb():
def __init__(self, db='flickrwatcher.db'):
try:
self.db = db
self.dbconn = sqlite3.connect(db)
self.cursor = self.dbconn.cursor()
self.cursor.execute("""CREATE TABLE IF NOT EXISTS subscriptions
(
userName text,
contactName text,
contactId text,
subscribed integer,
maxPhotos integer,
UNIQUE
(
userName,
contactId
) ON CONFLICT REPLACE
)""")
self.cursor.execute("""CREATE TABLE IF NOT EXISTS watch
(
userName text,
contactId text,
photoUrl text,
photoFName text,
uploadDate integer,
downloadDate integer,
UNIQUE
(
userName,
contactId,
photoUrl
) ON CONFLICT REPLACE
)""")
self.dbconn.commit()
except Exception, e:
traceback.print_exc()
print >>sys.stderr, e
self.dbconn = None
self.cursor = None
def isConnected(self):
return self.dbconn and self.cursor
def getUserList(self):
if not self.isConnected():
raise NotConnectedException(self.db)
userList = []
self.cursor.execute('SELECT DISTINCT userName FROM subscriptions')
for row in self.cursor:
userList.append(row[0])
return userList
def getSubscriptions(self, userName):
if not self.isConnected():
raise NotConnectedException(self.db)
subscriptions = []
self.cursor.execute('SELECT contactName, contactId FROM subscriptions WHERE userName=? AND subscribed=1', (userName,))
for row in self.cursor:
subscriptions.append( (row[0], row[1]) )
return subscriptions
def isSubscribed(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
subscribed = False
self.cursor.execute('SELECT subscribed FROM subscriptions WHERE userName=? AND contactId=?', (userName, contactId))
for row in self.cursor:
subscribed = row[0]
return subscribed
def maxPhotos(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
maxPhotos = 0
self.cursor.execute('SELECT maxPhotos FROM subscriptions WHERE userName=? AND contactId=?', (userName, contactId))
for row in self.cursor:
maxPhotos= row[0]
return maxPhotos
def getLastUploadDate(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
lastdate = None
self.cursor.execute('SELECT MAX(uploadDate) FROM watch WHERE userName=? AND contactId=?', (userName, contactId))
for row in self.cursor:
lastdate = row[0]
return lastdate
def photoDownloaded(self, userName, contactId, photoUrl, uploadDate):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('SELECT uploadDate FROM watch WHERE userName=? AND contactId=? AND photoUrl=?', (userName, contactId, photoUrl))
downloaded = False
for row in self.cursor:
if row[0] >= uploadDate:
downloaded = True
break
return downloaded
def markPhotoDownloaded(self, userName, contactId, photoUrl, photoFName, uploadDate):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('REPLACE INTO watch (userName, contactId, photoUrl, photoFName, uploadDate, downloadDate) VALUES (?, ?, ?, ?, ?, ?)',
(userName, contactId, photoUrl, photoFName, uploadDate, time.time()))
self.dbconn.commit()
def subscribe(self, userName, contactId, contactName, maxPhotos):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('REPLACE INTO subscriptions (userName, contactId, contactName, subscribed, maxPhotos) VALUES (?, ?, ?, 1, ?)',
(userName, contactId, contactName, maxPhotos))
self.dbconn.commit()
def unsubscribe(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('REPLACE INTO subscriptions (userName, contactId, subscribed) VALUES (?, ?, 0)',
(userName, contactId))
self.dbconn.commit()
def editSubscription(self, userName, contactId, contactName, maxPhotos):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('UPDATE subscriptions SET maxPhotos=? WHERE userName=? AND contactId=?',
(maxPhotos, userName, contactId))
self.dbconn.commit()
def getPhotoCount(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
photoCount = 0
self.cursor.execute('SELECT COUNT(*) FROM watch WHERE userName=? AND contactId=?', (userName, contactId))
for row in self.cursor:
photoCount = row[0]
return photoCount
def getOldestPhotos(self, userName, contactId, photoCount):
if not self.isConnected():
raise NotConnectedException(self.db)
oldestPhotos = []
self.cursor.execute('SELECT photoFName, photoUrl FROM watch WHERE userName=? AND contactId=? ORDER BY uploadDate LIMIT ?',
(userName, contactId, photoCount))
for row in self.cursor:
oldestPhotos.append( (row[0], row[1]) )
return oldestPhotos
def removePhotos(self, userName, contactId, photoList):
if not self.isConnected():
raise NotConnectedException(self.db)
for (photoFName, photoUrl) in photoList:
self.cursor.execute('DELETE FROM watch WHERE userName=? AND contactId=? AND photoFName=? AND photoUrl=?',
(userName, contactId, photoFName, photoUrl))
self.dbconn.commit()
def download_photos(userName, contactName, contactId, maxPhotos, flickr, db):
if not os.path.exists(userName+'/'+contactName):
os.mkdir(userName+'/'+contactName)
lastdate = db.getLastUploadDate(userName, contactId)
photoCount = db.getPhotoCount(userName, contactId)
retry = 3
while retry:
try:
if lastdate and photoCount >= maxPhotos:
photos = flickr.photos_search(user_id=contactId, min_upload_date=lastdate+1, safe_search='3', extras='date_upload', per_page=maxPhotos)
else:
photos = flickr.photos_search(user_id=contactId, safe_search='3', extras='date_upload', per_page=maxPhotos)
except:
retry = retry - 1
continue
else:
break
if not retry:
return
if photos.photos[0]['pages'] == '0':
return
print 'Evaluating', len(photos.photos[0].photo), 'photos from', contactName
for photo in photos.photos[0].photo:
uploadDate = long(photo['dateupload'])
photo['dateupload'] = uploadDate
photoUrl = 'http://farm%(farm)s.static.flickr.com/%(server)s/%(id)s_%(secret)s.jpg' % photo
fname = '%(dateupload)08d_%(farm)s_%(server)s_%(id)s_%(secret)s.jpg' % photo
if not db.photoDownloaded(userName, contactId, photoUrl, uploadDate):
print >>sys.stderr, "Downloading new photo '%s' from '%s' (%s)" % ( photoUrl, contactName, str(db.photoDownloaded(userName, contactId, photoUrl, uploadDate)))
retry = 3
while retry:
try:
photod = urllib2.urlopen(photoUrl)
fd = open(userName+'/'+contactName+'/'+fname, 'w')
shutil.copyfileobj(photod, fd)
photod.close()
fd.close()
db.markPhotoDownloaded(userName, contactId, photoUrl, fname, uploadDate)
except:
print >>sys.stderr, "Download of", photoUrl, "failed on try", (3 - retry) + 1, "of", 3
retry = retry - 1
continue
else:
break
photoCount = db.getPhotoCount(userName, contactId)
if photoCount > maxPhotos:
oldestPhotos = db.getOldestPhotos(userName, contactId, photoCount - maxPhotos)
for (fname, photoUrl) in oldestPhotos:
try:
os.remove(userName+'/'+contactName+'/'+fname)
except:
pass
db.removePhotos(userName, contactId, oldestPhotos)
def getSubscribedPhotos(userName, flickr, db):
subscriptions = db.getSubscriptions(userName)
for (contactName, contactId) in subscriptions:
# Download photos from subscribed contacts
maxPhotos = db.maxPhotos(userName, contactId)
download_photos(userName, contactName, contactId, maxPhotos, flickr, db)
def subscribe(userName, userId, flickr, db):
unsubscribed = []
contacts = flickr.contacts_getList(user_id=userId)
for contact in contacts.contacts[0].contact:
contactId = contact['nsid']
contactName = contact['username']
if not db.isSubscribed(userName, contactId):
unsubscribed.append( (contactName, contactId) )
if not db.isSubscribed(userName, userId):
unsubscribed.append( (userName, userId) )
contact = None
while not contact:
print ""
idx = 0
for (contactName, contactId) in unsubscribed:
print "%d) %s" % (idx, contactName)
idx = idx + 1
print "%d) Done subscribing" % (idx)
print ""
contact = raw_input('Subscribe to contact: ')
try:
contact = int(contact)
except:
print ""
print "Invalid selection %s, retry 0-%d" % (contact, idx)
contact = None
continue
if contact < 0 or contact > idx:
print ""
print "Invalid selection %d, retry 0-%d" % (contact, idx)
contact = None
elif contact == idx:
break
else:
(contactName, contactId) = unsubscribed[contact]
maxPhotos = None
while not maxPhotos:
print ""
maxPhotos = raw_input('How many photos from %s do you want to keep (1-500)? ' % contactName)
try:
maxPhotos = int(maxPhotos)
except:
print ""
print "Invalid selection %s, retry 0-500" % (maxPhotos)
maxPhotos = None
continue
if maxPhotos < 1 or maxPhotos > 500:
print ""
print "Invalid input %d, retry 1-500" % (maxPhotos)
maxPhotos = None
db.subscribe(userName, contactId, contactName, maxPhotos)
del unsubscribed[contact]
contact = None
def unsubscribe(userName, userId, flickr, db):
subscribed = db.getSubscriptions(userName)
contact = None
while not contact:
print ""
idx = 0
for (contactName, contactId) in subscribed:
print "%d) %s" % (idx, contactName)
idx = idx + 1
print "%d) Done unsubscribing" % (idx)
print ""
contact = raw_input('Unsubscribe to contact: ')
try:
contact = int(contact)
except:
print ""
print "Invalid selection %s, retry 0-%d" % (contact, idx)
contact = None
continue
if contact < 0 or contact > idx:
print ""
print "Invalid selection %d, retry 0-%d" % (contact, idx)
contact = None
elif contact == idx:
break
else:
(contactName, contactId) = subscribed[contact]
confirm = None
while not confirm:
print ""
confirm = raw_input('Are you sure you want to unsubscribe to %s (y or n)? ' % contactName)[0].lower()
if confirm != 'y' and confirm != n:
print ""
print "Invalid input %d, retry y or n" % (maxPhotos)
confirm = None
if confirm == 'y':
db.unsubscribe(userName, contactId)
del subscribed[contact]
contact = None
def editSubscriptions(userName, userId, flickr, db):
subscribed = db.getSubscriptions(userName)
contact = None
while not contact:
print ""
idx = 0
for (contactName, contactId) in subscribed:
print "%d) %s" % (idx, contactName)
idx = idx + 1
print "%d) Done editing subscriptions" % (idx)
print ""
contact = raw_input('Edit settings for contact: ')
try:
contact = int(contact)
except:
print ""
print "Invalid selection %s, retry 0-%d" % (contact, idx)
contact = None
continue
if contact < 0 or contact > idx:
print ""
print "Invalid selection %d, retry 0-%d" % (contact, idx)
contact = None
elif contact == idx:
break
else:
(contactName, contactId) = subscribed[contact]
maxPhotos = None
while not maxPhotos:
print ""
maxPhotos = raw_input('How many photos from %s do you want to keep (1-500)? ' % contactName)
try:
maxPhotos = int(maxPhotos)
except:
print ""
print "Invalid selection %s, retry 0-500" % (maxPhotos)
maxPhotos = None
continue
if maxPhotos < 1 or maxPhotos > 500:
print ""
print "Invalid input %d, retry 1-500" % (maxPhotos)
maxPhotos = None
db.editSubscription(userName, contactId, contactName, maxPhotos)
contact = None
def manageSubscriptions(userName, userId, flickr, db):
choice = {1: subscribe, 2: unsubscribe, 3: editSubscriptions}
selection = 0
while not selection:
print ""
print "1) Add subscriptions"
print "2) Delete subscriptions"
print "3) Edit subscriptions"
print ""
selection = raw_input('Add, delete, or edit: ')
try:
selection = int(selection)
except:
print ""
print "Invalid selection %s, retry 1-3" % (selection)
selection = None
continue
if selection < 1 or selection > 3:
print ""
print "Invalid selection %d, retry 1-3" % (selection)
choice[selection](userName, userId, flickr, db)
print " flickrwatcher version %{VERSION}, Copyright (C) 2008 Joseph G. Echeverria"
print " flickrwatcher comes with ABSOLUTELY NO WARRANTY;"
print " This is free software, and you are welcome to redistribute it"
print " under certain conditions;"
db = FlickrWatcherDb()
userList = db.getUserList()
userName = None
while not userName:
print ""
idx = 0
for user in userList:
print "%d) %s" % (idx, user)
idx = idx + 1
print "%d) Enter new user" % (idx)
print ""
userNumber = raw_input('Enter user number: ')
try:
userNumber = int(userNumber)
except:
print ""
print "Invalid selection %s, retry %d-%d" % (userNumber, 0, idx)
continue
if userNumber == idx:
userName = raw_input('Enter user name: ')
elif userNumber > idx or userNumber < 0:
print ""
print "Invalid selection %d, retry %d-%d" % (userNumber, 0, idx)
else:
userName = userList[userNumber]
if not os.path.exists(userName):
os.mkdir(userName)
flickr = flickrapi.FlickrAPI(apiKey, apiSecret)
(token, frob) = flickr.getTokenPartOne(perms='read')
if not token:
raw_input("Press ENTER after you authorized this program.")
flickr.getTokenPartTwo((token, frob))
user = flickr.people_findByUsername(username=userName)
userId = user.user[0]['nsid']
while True:
selection = None
while not selection:
print ""
print "1) Manage subscriptions"
print "2) Get new photos"
print "3) Exit"
print ""
selection = raw_input('What do you want to do?: ')
try:
selection = int(selection)
except:
print ""
print "Invalid selection %s, retry 1-3" % (selection)
selection = None
continue
if selection < 1 or selection > 3:
print ""
print "Invalid selection %d, retry 1-3" % (selection)
selection = None
continue
if selection == 1:
manageSubscriptions(userName, userId, flickr, db)
elif selection == 2:
getSubscribedPhotos(userName, flickr, db)
elif selection == 3:
break
| Python |
#! /usr/bin/env python
# flickrwatcher - Keep track of your friends' flickr photos.
# Copyright (C) 2008 Joseph G. Echeverria (joey42+flickrwatcher@gmail.com)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import os, sys, shutil, time, traceback
import urllib2
import flickrapi
import sqlite3
apiKey = 'e597cdeedb619f3f47ca999cd6f42149'
apiSecret = '578a2ab88db7e31b'
class NotConnectedException(Exception):
def __init__(self, db):
self.db = db
def __str__(self):
return self.db
class FlickrWatcherDb():
def __init__(self, db='flickrwatcher.db'):
try:
self.db = db
self.dbconn = sqlite3.connect(db)
self.cursor = self.dbconn.cursor()
self.cursor.execute("""CREATE TABLE IF NOT EXISTS subscriptions
(
userName text,
contactName text,
contactId text,
subscribed integer,
maxPhotos integer,
UNIQUE
(
userName,
contactId
) ON CONFLICT REPLACE
)""")
self.cursor.execute("""CREATE TABLE IF NOT EXISTS watch
(
userName text,
contactId text,
photoUrl text,
photoFName text,
uploadDate integer,
downloadDate integer,
UNIQUE
(
userName,
contactId,
photoUrl
) ON CONFLICT REPLACE
)""")
self.dbconn.commit()
except Exception, e:
traceback.print_exc()
print >>sys.stderr, e
self.dbconn = None
self.cursor = None
def isConnected(self):
return self.dbconn and self.cursor
def getUserList(self):
if not self.isConnected():
raise NotConnectedException(self.db)
userList = []
self.cursor.execute('SELECT DISTINCT userName FROM subscriptions')
for row in self.cursor:
userList.append(row[0])
return userList
def getSubscriptions(self, userName):
if not self.isConnected():
raise NotConnectedException(self.db)
subscriptions = []
self.cursor.execute('SELECT contactName, contactId FROM subscriptions WHERE userName=? AND subscribed=1', (userName,))
for row in self.cursor:
subscriptions.append( (row[0], row[1]) )
return subscriptions
def isSubscribed(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
subscribed = False
self.cursor.execute('SELECT subscribed FROM subscriptions WHERE userName=? AND contactId=?', (userName, contactId))
for row in self.cursor:
subscribed = row[0]
return subscribed
def maxPhotos(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
maxPhotos = 0
self.cursor.execute('SELECT maxPhotos FROM subscriptions WHERE userName=? AND contactId=?', (userName, contactId))
for row in self.cursor:
maxPhotos= row[0]
return maxPhotos
def getLastUploadDate(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
lastdate = None
self.cursor.execute('SELECT MAX(uploadDate) FROM watch WHERE userName=? AND contactId=?', (userName, contactId))
for row in self.cursor:
lastdate = row[0]
return lastdate
def photoDownloaded(self, userName, contactId, photoUrl, uploadDate):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('SELECT uploadDate FROM watch WHERE userName=? AND contactId=? AND photoUrl=?', (userName, contactId, photoUrl))
downloaded = False
for row in self.cursor:
if row[0] >= uploadDate:
downloaded = True
break
return downloaded
def markPhotoDownloaded(self, userName, contactId, photoUrl, photoFName, uploadDate):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('REPLACE INTO watch (userName, contactId, photoUrl, photoFName, uploadDate, downloadDate) VALUES (?, ?, ?, ?, ?, ?)',
(userName, contactId, photoUrl, photoFName, uploadDate, time.time()))
self.dbconn.commit()
def subscribe(self, userName, contactId, contactName, maxPhotos):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('REPLACE INTO subscriptions (userName, contactId, contactName, subscribed, maxPhotos) VALUES (?, ?, ?, 1, ?)',
(userName, contactId, contactName, maxPhotos))
self.dbconn.commit()
def unsubscribe(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('REPLACE INTO subscriptions (userName, contactId, subscribed) VALUES (?, ?, 0)',
(userName, contactId))
self.dbconn.commit()
def editSubscription(self, userName, contactId, contactName, maxPhotos):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('UPDATE subscriptions SET maxPhotos=? WHERE userName=? AND contactId=?',
(maxPhotos, userName, contactId))
self.dbconn.commit()
def getPhotoCount(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
photoCount = 0
self.cursor.execute('SELECT COUNT(*) FROM watch WHERE userName=? AND contactId=?', (userName, contactId))
for row in self.cursor:
photoCount = row[0]
return photoCount
def getOldestPhotos(self, userName, contactId, photoCount):
if not self.isConnected():
raise NotConnectedException(self.db)
oldestPhotos = []
self.cursor.execute('SELECT photoFName, photoUrl FROM watch WHERE userName=? AND contactId=? ORDER BY uploadDate LIMIT ?',
(userName, contactId, photoCount))
for row in self.cursor:
oldestPhotos.append( (row[0], row[1]) )
return oldestPhotos
def removePhotos(self, userName, contactId, photoList):
if not self.isConnected():
raise NotConnectedException(self.db)
for (photoFName, photoUrl) in photoList:
self.cursor.execute('DELETE FROM watch WHERE userName=? AND contactId=? AND photoFName=? AND photoUrl=?',
(userName, contactId, photoFName, photoUrl))
self.dbconn.commit()
def download_photos(userName, contactName, contactId, maxPhotos, flickr, db):
if not os.path.exists(userName+'/'+contactName):
os.mkdir(userName+'/'+contactName)
lastdate = db.getLastUploadDate(userName, contactId)
photoCount = db.getPhotoCount(userName, contactId)
retry = 3
while retry:
try:
if lastdate and photoCount >= maxPhotos:
photos = flickr.photos_search(user_id=contactId, min_upload_date=lastdate+1, safe_search='3', extras='date_upload', per_page=maxPhotos)
else:
photos = flickr.photos_search(user_id=contactId, safe_search='3', extras='date_upload', per_page=maxPhotos)
except:
retry = retry - 1
continue
else:
break
if not retry:
return
if photos.photos[0]['pages'] == '0':
return
print 'Evaluating', len(photos.photos[0].photo), 'photos from', contactName
for photo in photos.photos[0].photo:
uploadDate = long(photo['dateupload'])
photo['dateupload'] = uploadDate
photoUrl = 'http://farm%(farm)s.static.flickr.com/%(server)s/%(id)s_%(secret)s.jpg' % photo
fname = '%(dateupload)08d_%(farm)s_%(server)s_%(id)s_%(secret)s.jpg' % photo
if not db.photoDownloaded(userName, contactId, photoUrl, uploadDate):
print >>sys.stderr, "Downloading new photo '%s' from '%s' (%s)" % ( photoUrl, contactName, str(db.photoDownloaded(userName, contactId, photoUrl, uploadDate)))
retry = 3
while retry:
try:
photod = urllib2.urlopen(photoUrl)
fd = open(userName+'/'+contactName+'/'+fname, 'w')
shutil.copyfileobj(photod, fd)
photod.close()
fd.close()
db.markPhotoDownloaded(userName, contactId, photoUrl, fname, uploadDate)
except:
print >>sys.stderr, "Download of", photoUrl, "failed on try", (3 - retry) + 1, "of", 3
retry = retry - 1
continue
else:
break
photoCount = db.getPhotoCount(userName, contactId)
if photoCount > maxPhotos:
oldestPhotos = db.getOldestPhotos(userName, contactId, photoCount - maxPhotos)
for (fname, photoUrl) in oldestPhotos:
try:
os.remove(userName+'/'+contactName+'/'+fname)
except:
pass
db.removePhotos(userName, contactId, oldestPhotos)
def getSubscribedPhotos(userName, flickr, db):
subscriptions = db.getSubscriptions(userName)
for (contactName, contactId) in subscriptions:
# Download photos from subscribed contacts
maxPhotos = db.maxPhotos(userName, contactId)
download_photos(userName, contactName, contactId, maxPhotos, flickr, db)
def subscribe(userName, userId, flickr, db):
unsubscribed = []
contacts = flickr.contacts_getList(user_id=userId)
for contact in contacts.contacts[0].contact:
contactId = contact['nsid']
contactName = contact['username']
if not db.isSubscribed(userName, contactId):
unsubscribed.append( (contactName, contactId) )
if not db.isSubscribed(userName, userId):
unsubscribed.append( (userName, userId) )
contact = None
while not contact:
print ""
idx = 0
for (contactName, contactId) in unsubscribed:
print "%d) %s" % (idx, contactName)
idx = idx + 1
print "%d) Done subscribing" % (idx)
print ""
contact = raw_input('Subscribe to contact: ')
try:
contact = int(contact)
except:
print ""
print "Invalid selection %s, retry 0-%d" % (contact, idx)
contact = None
continue
if contact < 0 or contact > idx:
print ""
print "Invalid selection %d, retry 0-%d" % (contact, idx)
contact = None
elif contact == idx:
break
else:
(contactName, contactId) = unsubscribed[contact]
maxPhotos = None
while not maxPhotos:
print ""
maxPhotos = raw_input('How many photos from %s do you want to keep (1-500)? ' % contactName)
try:
maxPhotos = int(maxPhotos)
except:
print ""
print "Invalid selection %s, retry 0-500" % (maxPhotos)
maxPhotos = None
continue
if maxPhotos < 1 or maxPhotos > 500:
print ""
print "Invalid input %d, retry 1-500" % (maxPhotos)
maxPhotos = None
db.subscribe(userName, contactId, contactName, maxPhotos)
del unsubscribed[contact]
contact = None
def unsubscribe(userName, userId, flickr, db):
subscribed = db.getSubscriptions(userName)
contact = None
while not contact:
print ""
idx = 0
for (contactName, contactId) in subscribed:
print "%d) %s" % (idx, contactName)
idx = idx + 1
print "%d) Done unsubscribing" % (idx)
print ""
contact = raw_input('Unsubscribe to contact: ')
try:
contact = int(contact)
except:
print ""
print "Invalid selection %s, retry 0-%d" % (contact, idx)
contact = None
continue
if contact < 0 or contact > idx:
print ""
print "Invalid selection %d, retry 0-%d" % (contact, idx)
contact = None
elif contact == idx:
break
else:
(contactName, contactId) = subscribed[contact]
confirm = None
while not confirm:
print ""
confirm = raw_input('Are you sure you want to unsubscribe to %s (y or n)? ' % contactName)[0].lower()
if confirm != 'y' and confirm != n:
print ""
print "Invalid input %d, retry y or n" % (maxPhotos)
confirm = None
if confirm == 'y':
db.unsubscribe(userName, contactId)
del subscribed[contact]
contact = None
def editSubscriptions(userName, userId, flickr, db):
subscribed = db.getSubscriptions(userName)
contact = None
while not contact:
print ""
idx = 0
for (contactName, contactId) in subscribed:
print "%d) %s" % (idx, contactName)
idx = idx + 1
print "%d) Done editing subscriptions" % (idx)
print ""
contact = raw_input('Edit settings for contact: ')
try:
contact = int(contact)
except:
print ""
print "Invalid selection %s, retry 0-%d" % (contact, idx)
contact = None
continue
if contact < 0 or contact > idx:
print ""
print "Invalid selection %d, retry 0-%d" % (contact, idx)
contact = None
elif contact == idx:
break
else:
(contactName, contactId) = subscribed[contact]
maxPhotos = None
while not maxPhotos:
print ""
maxPhotos = raw_input('How many photos from %s do you want to keep (1-500)? ' % contactName)
try:
maxPhotos = int(maxPhotos)
except:
print ""
print "Invalid selection %s, retry 0-500" % (maxPhotos)
maxPhotos = None
continue
if maxPhotos < 1 or maxPhotos > 500:
print ""
print "Invalid input %d, retry 1-500" % (maxPhotos)
maxPhotos = None
db.editSubscription(userName, contactId, contactName, maxPhotos)
contact = None
def manageSubscriptions(userName, userId, flickr, db):
choice = {1: subscribe, 2: unsubscribe, 3: editSubscriptions}
selection = 0
while not selection:
print ""
print "1) Add subscriptions"
print "2) Delete subscriptions"
print "3) Edit subscriptions"
print ""
selection = raw_input('Add, delete, or edit: ')
try:
selection = int(selection)
except:
print ""
print "Invalid selection %s, retry 1-3" % (selection)
selection = None
continue
if selection < 1 or selection > 3:
print ""
print "Invalid selection %d, retry 1-3" % (selection)
choice[selection](userName, userId, flickr, db)
print " flickrwatcher version %{VERSION}, Copyright (C) 2008 Joseph G. Echeverria"
print " flickrwatcher comes with ABSOLUTELY NO WARRANTY;"
print " This is free software, and you are welcome to redistribute it"
print " under certain conditions;"
db = FlickrWatcherDb()
userList = db.getUserList()
userName = None
while not userName:
print ""
idx = 0
for user in userList:
print "%d) %s" % (idx, user)
idx = idx + 1
print "%d) Enter new user" % (idx)
print ""
userNumber = raw_input('Enter user number: ')
try:
userNumber = int(userNumber)
except:
print ""
print "Invalid selection %s, retry %d-%d" % (userNumber, 0, idx)
continue
if userNumber == idx:
userName = raw_input('Enter user name: ')
elif userNumber > idx or userNumber < 0:
print ""
print "Invalid selection %d, retry %d-%d" % (userNumber, 0, idx)
else:
userName = userList[userNumber]
if not os.path.exists(userName):
os.mkdir(userName)
flickr = flickrapi.FlickrAPI(apiKey, apiSecret)
(token, frob) = flickr.getTokenPartOne(perms='read')
if not token:
raw_input("Press ENTER after you authorized this program.")
flickr.getTokenPartTwo((token, frob))
user = flickr.people_findByUsername(username=userName)
userId = user.user[0]['nsid']
while True:
selection = None
while not selection:
print ""
print "1) Manage subscriptions"
print "2) Get new photos"
print "3) Exit"
print ""
selection = raw_input('What do you want to do?: ')
try:
selection = int(selection)
except:
print ""
print "Invalid selection %s, retry 1-3" % (selection)
selection = None
continue
if selection < 1 or selection > 3:
print ""
print "Invalid selection %d, retry 1-3" % (selection)
selection = None
continue
if selection == 1:
manageSubscriptions(userName, userId, flickr, db)
elif selection == 2:
getSubscribedPhotos(userName, flickr, db)
elif selection == 3:
break
| Python |
#! /usr/bin/env python
import os, sys, shutil, time, traceback
import urllib2
import flickrapi
import sqlite3
apiKey = 'e597cdeedb619f3f47ca999cd6f42149'
apiSecret = '578a2ab88db7e31b'
class NotConnectedException(Exception):
def __init__(self, db):
self.db = db
def __str__(self):
return self.db
class FlickrWatcherDb():
def __init__(self, db='flickrwatcher.db'):
try:
self.db = db
self.dbconn = sqlite3.connect(db)
self.cursor = self.dbconn.cursor()
self.cursor.execute("""CREATE TABLE IF NOT EXISTS subscriptions
(
userName text,
contactName text,
contactId text,
subscribed integer,
maxPhotos integer,
UNIQUE
(
userName,
contactId
) ON CONFLICT REPLACE
)""")
self.cursor.execute("""CREATE TABLE IF NOT EXISTS watch
(
userName text,
contactId text,
photoUrl text,
photoFName text,
uploadDate integer,
downloadDate integer,
UNIQUE
(
userName,
contactId,
photoUrl
) ON CONFLICT REPLACE
)""")
self.dbconn.commit()
except Exception, e:
traceback.print_exc()
print >>sys.stderr, e
self.dbconn = None
self.cursor = None
def isConnected(self):
return self.dbconn and self.cursor
def getUserList(self):
if not self.isConnected():
raise NotConnectedException(self.db)
userList = []
self.cursor.execute('SELECT DISTINCT userName FROM subscriptions')
for row in self.cursor:
userList.append(row[0])
return userList
def getSubscriptions(self, userName):
if not self.isConnected():
raise NotConnectedException(self.db)
subscriptions = []
self.cursor.execute('SELECT contactName, contactId FROM subscriptions WHERE userName=? AND subscribed=1', (userName,))
for row in self.cursor:
subscriptions.append( (row[0], row[1]) )
return subscriptions
def isSubscribed(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
subscribed = False
self.cursor.execute('SELECT subscribed FROM subscriptions WHERE userName=? AND contactId=?', (userName, contactId))
for row in self.cursor:
subscribed = row[0]
return subscribed
def maxPhotos(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
maxPhotos = 0
self.cursor.execute('SELECT maxPhotos FROM subscriptions WHERE userName=? AND contactId=?', (userName, contactId))
for row in self.cursor:
maxPhotos= row[0]
return maxPhotos
def getLastUploadDate(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
lastdate = None
self.cursor.execute('SELECT MAX(uploadDate) FROM watch WHERE userName=? AND contactId=?', (userName, contactId))
for row in self.cursor:
lastdate = row[0]
return lastdate
def photoDownloaded(self, userName, contactId, photoUrl, uploadDate):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('SELECT uploadDate FROM watch WHERE userName=? AND contactId=? AND photoUrl=?', (userName, contactId, photoUrl))
downloaded = False
for row in self.cursor:
if row[0] >= uploadDate:
downloaded = True
break
return downloaded
def markPhotoDownloaded(self, userName, contactId, photoUrl, photoFName, uploadDate):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('REPLACE INTO watch (userName, contactId, photoUrl, photoFName, uploadDate, downloadDate) VALUES (?, ?, ?, ?, ?, ?)',
(userName, contactId, photoUrl, photoFName, uploadDate, time.time()))
self.dbconn.commit()
def subscribe(self, userName, contactId, contactName, maxPhotos):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('REPLACE INTO subscriptions (userName, contactId, contactName, subscribed, maxPhotos) VALUES (?, ?, ?, 1, ?)',
(userName, contactId, contactName, maxPhotos))
self.dbconn.commit()
def unsubscribe(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('REPLACE INTO subscriptions (userName, contactId, subscribed) VALUES (?, ?, 0)',
(userName, contactId))
self.dbconn.commit()
def getPhotoCount(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
photoCount = 0
self.cursor.execute('SELECT COUNT(*) FROM watch WHERE userName=? AND contactId=?', (userName, contactId))
for row in self.cursor:
photoCount = row[0]
return photoCount
def getOldestPhotos(self, userName, contactId, photoCount):
if not self.isConnected():
raise NotConnectedException(self.db)
oldestPhotos = []
self.cursor.execute('SELECT photoFName, photoUrl FROM watch WHERE userName=? AND contactId=? ORDER BY uploadDate LIMIT ?',
(userName, contactId, photoCount))
for row in self.cursor:
oldestPhotos.append( (row[0], row[1]) )
return oldestPhotos
def removePhotos(self, userName, contactId, photoList):
if not self.isConnected():
raise NotConnectedException(self.db)
for (photoFName, photoUrl) in photoList:
self.cursor.execute('DELETE FROM TABLE watch WHERE userName=? AND contactId=? AND photoFName=? AND photoUrl=?',
(photoFName, photoUrl))
self.dbconn.commit()
def download_photos(userName, contactName, contactId, maxPhotos, flickr, db):
if not os.path.exists(userName+'/'+contactName):
os.mkdir(userName+'/'+contactName)
lastdate = db.getLastUploadDate(userName, contactId)
if lastdate:
photos = flickr.photos_search(user_id=contactId, min_upload_date=lastdate, safe_search='3', extras='date_upload', per_page=maxPhotos)
else:
photos = flickr.photos_search(user_id=contactId, safe_search='3', extras='date_upload', per_page=maxPhotos)
if photos.photos[0]['pages'] == '0':
return
for photo in photos.photos[0].photo:
photoUrl = 'http://farm%(farm)s.static.flickr.com/%(server)s/%(id)s_%(secret)s.jpg' % photo
fname = '%(farm)s_%(server)s_%(id)s_%(secret)s.jpg' % photo
uploadDate = photo['dateupload']
if not db.photoDownloaded(userName, contactId, photoUrl, uploadDate):
try:
photod = urllib2.urlopen(photoUrl)
fd = open(userName+'/'+contactName+'/'+fname, 'w')
shutil.copyfileobj(photod, fd)
photod.close()
fd.close()
db.markPhotoDownloaded(userName, contactId, photoUrl, fname, uploadDate)
except:
traceback.print_exc()
print >>sys.stderr, "Download of", photoUrl, "failed."
photoCount = db.getPhotoCount(userName, contactId)
if photoCount > maxPhotos:
oldestPhotos = db.getOldestPhotos(userName, contactId, photoCount - maxPhotos)
for (fname, photoUrl) in oldestPhotos:
os.remove(userName+'/'+contactName+'/'+fname)
db.removePhotos(userName, contactId, oldestPhotos)
def getSubscribedPhotos(userName, flickr, db):
subscriptions = db.getSubscriptions(userName)
for (contactName, contactId) in subscriptions:
# Download photos from subscribed contacts
maxPhotos = db.maxPhotos(userName, contactId)
download_photos(userName, contactName, contactId, maxPhotos, flickr, db)
def subscribe(userName, userId, flickr, db):
unsubscribed = []
contacts = flickr.contacts_getList(user_id=userId)
for contact in contacts.contacts[0].contact:
contactId = contact['nsid']
contactName = contact['username']
if not db.isSubscribed(userName, contactId):
unsubscribed.append( (contactName, contactId) )
if not db.isSubscribed(userName, userId):
unsubscribed.append( (userName, userId) )
contact = None
while not contact:
print ""
idx = 0
for (contactName, contactId) in unsubscribed:
print "%d) %s" % (idx, contactName)
idx = idx + 1
print "%d) Done subscribing" % (idx)
print ""
contact = raw_input('Subscribe to contact: ')
try:
contact = int(contact)
except:
print ""
print "Invalid selection %s, retry 0-%d" % (contact, idx)
contact = None
continue
if contact < 0 or contact > idx:
print ""
print "Invalid selection %d, retry 0-%d" % (contact, idx)
contact = None
elif contact == idx:
break
else:
(contactName, contactId) = unsubscribed[contact]
maxPhotos = None
while not maxPhotos:
print ""
maxPhotos = raw_input('How many photos from %s do you want to keep (1-500)? ' % contactName)
try:
maxPhotos = int(maxPhotos)
except:
print ""
print "Invalid selection %s, retry 0-500" % (maxPhotos)
maxPhotos = None
continue
if maxPhotos < 1 or maxPhotos > 500:
print ""
print "Invalid input %d, retry 1-500" % (maxPhotos)
maxPhotos = None
db.subscribe(userName, contactId, contactName, maxPhotos)
del unsubscribed[contact]
contact = None
def unsubscribe(userName, userId, flickr, db):
subscribed = db.getSubscriptions(userName)
contact = None
while not contact:
print ""
idx = 0
for (contactName, contactId) in subscribed:
print "%d) %s" % (idx, contactName)
idx = idx + 1
print "%d) Done unsubscribing" % (idx)
print ""
contact = raw_input('Unsubscribe to contact: ')
try:
contact = int(contact)
except:
print ""
print "Invalid selection %s, retry 0-%d" % (contact, idx)
contact = None
continue
if contact < 0 or contact > idx:
print ""
print "Invalid selection %d, retry 0-%d" % (contact, idx)
contact = None
elif contact == idx:
break
else:
(contactName, contactId) = subscribed[contact]
confirm = None
while not confirm:
print ""
confirm = raw_input('Are you sure you want to unsubscribe to %s (y or n)? ' % contactName)[0].lower()
if confirm != 'y' and confirm != n:
print ""
print "Invalid input %d, retry y or n" % (maxPhotos)
confirm = None
if confirm == 'y':
db.unsubscribe(userName, contactId)
contact = None
def manageSubscriptions(userName, userId, flickr, db):
choice = {1: subscribe, 2: unsubscribe}
selection = 0
while not selection:
print ""
print "1) Add subscriptions"
print "2) Delete subscriptions"
print ""
selection = raw_input('Add or delete: ')
try:
selection = int(selection)
except:
print ""
print "Invalid selection %s, retry 1-2" % (selection)
selection = None
continue
if selection < 1 or selection > 2:
print ""
print "Invalid selection %d, retry 1-2" % (selection)
choice[selection](userName, userId, flickr, db)
db = FlickrWatcherDb()
userList = db.getUserList()
userName = None
while not userName:
print ""
idx = 0
for user in userList:
print "%d) %s" % (idx, user)
idx = idx + 1
print "%d) Enter new user" % (idx)
print ""
userNumber = raw_input('Enter user number: ')
try:
userNumber = int(userNumber)
except:
print ""
print "Invalid selection %s, retry %d-%d" % (userNumber, 0, idx)
continue
if userNumber == idx:
userName = raw_input('Enter user name: ')
elif userNumber > idx or userNumber < 0:
print ""
print "Invalid selection %d, retry %d-%d" % (userNumber, 0, idx)
else:
userName = userList[userNumber]
if not os.path.exists(userName):
os.mkdir(userName)
flickr = flickrapi.FlickrAPI(apiKey, apiSecret)
(token, frob) = flickr.getTokenPartOne(perms='read')
if not token:
raw_input("Press ENTER after you authorized this program.")
flickr.getTokenPartTwo((token, frob))
user = flickr.people_findByUsername(username=userName)
userId = user.user[0]['nsid']
while True:
selection = None
while not selection:
print ""
print "1) Manage subscriptions"
print "2) Get new photos"
print "3) Exit"
print ""
selection = raw_input('What do you want to do?: ')
try:
selection = int(selection)
except:
print ""
print "Invalid selection %s, retry 1-3" % (selection)
selection = None
continue
if selection < 1 or selection > 3:
print ""
print "Invalid selection %d, retry 1-3" % (selection)
selection = None
continue
if selection == 1:
manageSubscriptions(userName, userId, flickr, db)
elif selection == 2:
getSubscribedPhotos(userName, flickr, db)
elif selection == 3:
break
| Python |
#! /usr/bin/env python
import os, sys, shutil, time, traceback
import urllib2
import flickrapi
import sqlite3
apiKey = 'e597cdeedb619f3f47ca999cd6f42149'
apiSecret = '578a2ab88db7e31b'
class NotConnectedException(Exception):
def __init__(self, db):
self.db = db
def __str__(self):
return self.db
class FlickrWatcherDb():
def __init__(self, db='flickrwatcher.db'):
try:
self.db = db
self.dbconn = sqlite3.connect(db)
self.cursor = self.dbconn.cursor()
self.cursor.execute("""CREATE TABLE IF NOT EXISTS subscriptions
(
userName text,
contactName text,
contactId text,
subscribed integer,
maxPhotos integer,
UNIQUE
(
userName,
contactId
) ON CONFLICT REPLACE
)""")
self.cursor.execute("""CREATE TABLE IF NOT EXISTS watch
(
userName text,
contactId text,
photoUrl text,
photoFName text,
uploadDate integer,
downloadDate integer,
UNIQUE
(
userName,
contactId,
photoUrl
) ON CONFLICT REPLACE
)""")
self.dbconn.commit()
except Exception, e:
traceback.print_exc()
print >>sys.stderr, e
self.dbconn = None
self.cursor = None
def isConnected(self):
return self.dbconn and self.cursor
def getUserList(self):
if not self.isConnected():
raise NotConnectedException(self.db)
userList = []
self.cursor.execute('SELECT DISTINCT userName FROM subscriptions')
for row in self.cursor:
userList.append(row[0])
return userList
def getSubscriptions(self, userName):
if not self.isConnected():
raise NotConnectedException(self.db)
subscriptions = []
self.cursor.execute('SELECT contactName, contactId FROM subscriptions WHERE userName=? AND subscribed=1', (userName,))
for row in self.cursor:
subscriptions.append( (row[0], row[1]) )
return subscriptions
def isSubscribed(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
subscribed = False
self.cursor.execute('SELECT subscribed FROM subscriptions WHERE userName=? AND contactId=?', (userName, contactId))
for row in self.cursor:
subscribed = row[0]
return subscribed
def maxPhotos(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
maxPhotos = 0
self.cursor.execute('SELECT maxPhotos FROM subscriptions WHERE userName=? AND contactId=?', (userName, contactId))
for row in self.cursor:
maxPhotos= row[0]
return maxPhotos
def getLastUploadDate(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
lastdate = None
self.cursor.execute('SELECT MAX(uploadDate) FROM watch WHERE userName=? AND contactId=?', (userName, contactId))
for row in self.cursor:
lastdate = row[0]
return lastdate
def photoDownloaded(self, userName, contactId, photoUrl, uploadDate):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('SELECT uploadDate FROM watch WHERE userName=? AND contactId=? AND photoUrl=?', (userName, contactId, photoUrl))
downloaded = False
for row in self.cursor:
if row[0] >= uploadDate:
downloaded = True
break
return downloaded
def markPhotoDownloaded(self, userName, contactId, photoUrl, photoFName, uploadDate):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('REPLACE INTO watch (userName, contactId, photoUrl, photoFName, uploadDate, downloadDate) VALUES (?, ?, ?, ?, ?, ?)',
(userName, contactId, photoUrl, photoFName, uploadDate, time.time()))
self.dbconn.commit()
def subscribe(self, userName, contactId, contactName, maxPhotos):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('REPLACE INTO subscriptions (userName, contactId, contactName, subscribed, maxPhotos) VALUES (?, ?, ?, 1, ?)',
(userName, contactId, contactName, maxPhotos))
self.dbconn.commit()
def unsubscribe(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('REPLACE INTO subscriptions (userName, contactId, subscribed) VALUES (?, ?, 0)',
(userName, contactId))
self.dbconn.commit()
def getPhotoCount(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
photoCount = 0
self.cursor.execute('SELECT COUNT(*) FROM watch WHERE userName=? AND contactId=?', (userName, contactId))
for row in self.cursor:
photoCount = row[0]
return photoCount
def getOldestPhotos(self, userName, contactId, photoCount):
if not self.isConnected():
raise NotConnectedException(self.db)
oldestPhotos = []
self.cursor.execute('SELECT photoFName, photoUrl FROM watch WHERE userName=? AND contactId=? ORDER BY uploadDate LIMIT ?',
(userName, contactId, photoCount))
for row in self.cursor:
oldestPhotos.append( (row[0], row[1]) )
return oldestPhotos
def removePhotos(self, userName, contactId, photoList):
if not self.isConnected():
raise NotConnectedException(self.db)
for (photoFName, photoUrl) in photoList:
self.cursor.execute('DELETE FROM TABLE watch WHERE userName=? AND contactId=? AND photoFName=? AND photoUrl=?',
(photoFName, photoUrl))
self.dbconn.commit()
def download_photos(userName, contactName, contactId, maxPhotos, flickr, db):
if not os.path.exists(userName+'/'+contactName):
os.mkdir(userName+'/'+contactName)
lastdate = db.getLastUploadDate(userName, contactId)
if lastdate:
photos = flickr.photos_search(user_id=contactId, min_upload_date=lastdate, safe_search='3', extras='date_upload', per_page=maxPhotos)
else:
photos = flickr.photos_search(user_id=contactId, safe_search='3', extras='date_upload', per_page=maxPhotos)
if photos.photos[0]['pages'] == '0':
return
for photo in photos.photos[0].photo:
photoUrl = 'http://farm%(farm)s.static.flickr.com/%(server)s/%(id)s_%(secret)s.jpg' % photo
fname = '%(farm)s_%(server)s_%(id)s_%(secret)s.jpg' % photo
uploadDate = photo['dateupload']
if not db.photoDownloaded(userName, contactId, photoUrl, uploadDate):
try:
photod = urllib2.urlopen(photoUrl)
fd = open(userName+'/'+contactName+'/'+fname, 'w')
shutil.copyfileobj(photod, fd)
photod.close()
fd.close()
db.markPhotoDownloaded(userName, contactId, photoUrl, fname, uploadDate)
except:
traceback.print_exc()
print >>sys.stderr, "Download of", photoUrl, "failed."
photoCount = db.getPhotoCount(userName, contactId)
if photoCount > maxPhotos:
oldestPhotos = db.getOldestPhotos(userName, contactId, photoCount - maxPhotos)
for (fname, photoUrl) in oldestPhotos:
os.remove(userName+'/'+contactName+'/'+fname)
db.removePhotos(userName, contactId, oldestPhotos)
def getSubscribedPhotos(userName, flickr, db):
subscriptions = db.getSubscriptions(userName)
for (contactName, contactId) in subscriptions:
# Download photos from subscribed contacts
maxPhotos = db.maxPhotos(userName, contactId)
download_photos(userName, contactName, contactId, maxPhotos, flickr, db)
def subscribe(userName, userId, flickr, db):
unsubscribed = []
contacts = flickr.contacts_getList(user_id=userId)
for contact in contacts.contacts[0].contact:
contactId = contact['nsid']
contactName = contact['username']
if not db.isSubscribed(userName, contactId):
unsubscribed.append( (contactName, contactId) )
if not db.isSubscribed(userName, userId):
unsubscribed.append( (userName, userId) )
contact = None
while not contact:
print ""
idx = 0
for (contactName, contactId) in unsubscribed:
print "%d) %s" % (idx, contactName)
idx = idx + 1
print "%d) Done subscribing" % (idx)
print ""
contact = raw_input('Subscribe to contact: ')
try:
contact = int(contact)
except:
print ""
print "Invalid selection %s, retry 0-%d" % (contact, idx)
contact = None
continue
if contact < 0 or contact > idx:
print ""
print "Invalid selection %d, retry 0-%d" % (contact, idx)
contact = None
elif contact == idx:
break
else:
(contactName, contactId) = unsubscribed[contact]
maxPhotos = None
while not maxPhotos:
print ""
maxPhotos = raw_input('How many photos from %s do you want to keep (1-500)? ' % contactName)
try:
maxPhotos = int(maxPhotos)
except:
print ""
print "Invalid selection %s, retry 0-500" % (maxPhotos)
maxPhotos = None
continue
if maxPhotos < 1 or maxPhotos > 500:
print ""
print "Invalid input %d, retry 1-500" % (maxPhotos)
maxPhotos = None
db.subscribe(userName, contactId, contactName, maxPhotos)
del unsubscribed[contact]
contact = None
def unsubscribe(userName, userId, flickr, db):
subscribed = db.getSubscriptions(userName)
contact = None
while not contact:
print ""
idx = 0
for (contactName, contactId) in subscribed:
print "%d) %s" % (idx, contactName)
idx = idx + 1
print "%d) Done unsubscribing" % (idx)
print ""
contact = raw_input('Unsubscribe to contact: ')
try:
contact = int(contact)
except:
print ""
print "Invalid selection %s, retry 0-%d" % (contact, idx)
contact = None
continue
if contact < 0 or contact > idx:
print ""
print "Invalid selection %d, retry 0-%d" % (contact, idx)
contact = None
elif contact == idx:
break
else:
(contactName, contactId) = subscribed[contact]
confirm = None
while not confirm:
print ""
confirm = raw_input('Are you sure you want to unsubscribe to %s (y or n)? ' % contactName)[0].lower()
if confirm != 'y' and confirm != n:
print ""
print "Invalid input %d, retry y or n" % (maxPhotos)
confirm = None
if confirm == 'y':
db.unsubscribe(userName, contactId)
contact = None
def manageSubscriptions(userName, userId, flickr, db):
choice = {1: subscribe, 2: unsubscribe}
selection = 0
while not selection:
print ""
print "1) Add subscriptions"
print "2) Delete subscriptions"
print ""
selection = raw_input('Add or delete: ')
try:
selection = int(selection)
except:
print ""
print "Invalid selection %s, retry 1-2" % (selection)
selection = None
continue
if selection < 1 or selection > 2:
print ""
print "Invalid selection %d, retry 1-2" % (selection)
choice[selection](userName, userId, flickr, db)
db = FlickrWatcherDb()
userList = db.getUserList()
userName = None
while not userName:
print ""
idx = 0
for user in userList:
print "%d) %s" % (idx, user)
idx = idx + 1
print "%d) Enter new user" % (idx)
print ""
userNumber = raw_input('Enter user number: ')
try:
userNumber = int(userNumber)
except:
print ""
print "Invalid selection %s, retry %d-%d" % (userNumber, 0, idx)
continue
if userNumber == idx:
userName = raw_input('Enter user name: ')
elif userNumber > idx or userNumber < 0:
print ""
print "Invalid selection %d, retry %d-%d" % (userNumber, 0, idx)
else:
userName = userList[userNumber]
if not os.path.exists(userName):
os.mkdir(userName)
flickr = flickrapi.FlickrAPI(apiKey, apiSecret)
(token, frob) = flickr.getTokenPartOne(perms='read')
if not token:
raw_input("Press ENTER after you authorized this program.")
flickr.getTokenPartTwo((token, frob))
user = flickr.people_findByUsername(username=userName)
userId = user.user[0]['nsid']
while True:
selection = None
while not selection:
print ""
print "1) Manage subscriptions"
print "2) Get new photos"
print "3) Exit"
print ""
selection = raw_input('What do you want to do?: ')
try:
selection = int(selection)
except:
print ""
print "Invalid selection %s, retry 1-3" % (selection)
selection = None
continue
if selection < 1 or selection > 3:
print ""
print "Invalid selection %d, retry 1-3" % (selection)
selection = None
continue
if selection == 1:
manageSubscriptions(userName, userId, flickr, db)
elif selection == 2:
getSubscribedPhotos(userName, flickr, db)
elif selection == 3:
break
| Python |
#! /usr/bin/env python
import os, sys, shutil
import urllib2
import flickrapi
import sqlite3
api_key = 'e597cdeedb619f3f47ca999cd6f42149'
api_secret = '578a2ab88db7e31b'
dbconn = sqlite3.connect('flickrwatcher.db')
cursor = dbconn.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS watch (username text, user_id text, photo_url text, dateupload integer, UNIQUE (username, user_id, photo_url) ON CONFLICT REPLACE)')
dbconn.commit()
username = raw_input('Enter username: ')
if not os.path.exists(username):
os.mkdir(username)
flickr = flickrapi.FlickrAPI(api_key, api_secret)
(token, frob) = flickr.getTokenPartOne(perms='read')
if not token:
raw_input("Press ENTER after you authorized this program.")
flickr.getTokenPartTwo((token, frob))
user = flickr.people_findByUsername(username=username)
user_id = user.user[0]['nsid']
contacts = flickr.contacts_getList(user_id=user_id)
for contact in contacts.contacts[0].contact:
user_id = contact['nsid']
contactname = contact['username']
if not os.path.exists(username+'/'+contactname):
os.mkdir(username+'/'+contactname)
lastdate = None
cursor.execute('SELECT MAX(dateupload) FROM watch WHERE username=? AND user_id=?', (username, user_id))
for row in cursor:
lastdate = row[0]
if lastdate:
photos = flickr.photos_search(user_id=user_id, min_upload_date=lastdate, safe_search='3', extras='date_upload', per_page=10)
else:
photos = flickr.photos_search(user_id=user_id, safe_search='3', extras='date_upload', per_page=10)
if photos.photos[0]['pages'] == '0':
continue
for photo in photos.photos[0].photo:
photo_url = 'http://farm%(farm)s.static.flickr.com/%(server)s/%(id)s_%(secret)s.jpg' % photo
fname = '%(farm)s_%(server)s_%(id)s_%(secret)s.jpg' % photo
cursor.execute('SELECT * FROM watch WHERE user_id=? AND photo_url=?', (user_id, photo_url))
downloaded = False
for row in cursor:
downloaded = True
break
if not downloaded:
photod = urllib2.urlopen(photo_url)
fd = open(username+'/'+contactname+'/'+fname, 'w')
shutil.copyfileobj(photod, fd)
photod.close()
fd.close()
cursor.execute('INSERT INTO watch (username, user_id, photo_url, dateupload) VALUES (?, ?, ?, ?)', (username, user_id, photo_url, photo['dateupload']))
dbconn.commit()
dbconn.close()
| Python |
#! /usr/bin/env python
import os, sys, shutil
import urllib2
import flickrapi
import sqlite3
api_key = 'e597cdeedb619f3f47ca999cd6f42149'
api_secret = '578a2ab88db7e31b'
dbconn = sqlite3.connect('flickrwatcher.db')
cursor = dbconn.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS watch (username text, user_id text, photo_url text, dateupload integer, UNIQUE (username, user_id, photo_url) ON CONFLICT REPLACE)')
dbconn.commit()
username = raw_input('Enter username: ')
if not os.path.exists(username):
os.mkdir(username)
flickr = flickrapi.FlickrAPI(api_key, api_secret)
(token, frob) = flickr.getTokenPartOne(perms='read')
if not token:
raw_input("Press ENTER after you authorized this program.")
flickr.getTokenPartTwo((token, frob))
user = flickr.people_findByUsername(username=username)
user_id = user.user[0]['nsid']
contacts = flickr.contacts_getList(user_id=user_id)
for contact in contacts.contacts[0].contact:
user_id = contact['nsid']
contactname = contact['username']
if not os.path.exists(username+'/'+contactname):
os.mkdir(username+'/'+contactname)
lastdate = None
cursor.execute('SELECT MAX(dateupload) FROM watch WHERE username=? AND user_id=?', (username, user_id))
for row in cursor:
lastdate = row[0]
if lastdate:
photos = flickr.photos_search(user_id=user_id, min_upload_date=lastdate, safe_search='3', extras='date_upload', per_page=10)
else:
photos = flickr.photos_search(user_id=user_id, safe_search='3', extras='date_upload', per_page=10)
if photos.photos[0]['pages'] == '0':
continue
for photo in photos.photos[0].photo:
photo_url = 'http://farm%(farm)s.static.flickr.com/%(server)s/%(id)s_%(secret)s.jpg' % photo
fname = '%(farm)s_%(server)s_%(id)s_%(secret)s.jpg' % photo
cursor.execute('SELECT * FROM watch WHERE user_id=? AND photo_url=?', (user_id, photo_url))
downloaded = False
for row in cursor:
downloaded = True
break
if not downloaded:
photod = urllib2.urlopen(photo_url)
fd = open(username+'/'+contactname+'/'+fname, 'w')
shutil.copyfileobj(photod, fd)
photod.close()
fd.close()
cursor.execute('INSERT INTO watch (username, user_id, photo_url, dateupload) VALUES (?, ?, ?, ?)', (username, user_id, photo_url, photo['dateupload']))
dbconn.commit()
dbconn.close()
| Python |
#! /usr/bin/env python
# flickrwatcher - Keep track of your friends' flickr photos.
# Copyright (C) 2008 Joseph G. Echeverria (joey42+flickrwatcher@gmail.com)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import os, sys, shutil, time, traceback
import urllib2
import flickrapi
import sqlite3
apiKey = 'e597cdeedb619f3f47ca999cd6f42149'
apiSecret = '578a2ab88db7e31b'
class NotConnectedException(Exception):
def __init__(self, db):
self.db = db
def __str__(self):
return self.db
class FlickrWatcherDb():
def __init__(self, db='flickrwatcher.db'):
try:
self.db = db
self.dbconn = sqlite3.connect(db)
self.cursor = self.dbconn.cursor()
self.cursor.execute("""CREATE TABLE IF NOT EXISTS subscriptions
(
userName text,
contactName text,
contactId text,
subscribed integer,
maxPhotos integer,
UNIQUE
(
userName,
contactId
) ON CONFLICT REPLACE
)""")
self.cursor.execute("""CREATE TABLE IF NOT EXISTS watch
(
userName text,
contactId text,
photoUrl text,
photoFName text,
uploadDate integer,
downloadDate integer,
UNIQUE
(
userName,
contactId,
photoUrl
) ON CONFLICT REPLACE
)""")
self.dbconn.commit()
except Exception, e:
traceback.print_exc()
print >>sys.stderr, e
self.dbconn = None
self.cursor = None
def isConnected(self):
return self.dbconn and self.cursor
def getUserList(self):
if not self.isConnected():
raise NotConnectedException(self.db)
userList = []
self.cursor.execute('SELECT DISTINCT userName FROM subscriptions')
for row in self.cursor:
userList.append(row[0])
return userList
def getSubscriptions(self, userName):
if not self.isConnected():
raise NotConnectedException(self.db)
subscriptions = []
self.cursor.execute('SELECT contactName, contactId FROM subscriptions WHERE userName=? AND subscribed=1', (userName,))
for row in self.cursor:
subscriptions.append( (row[0], row[1]) )
return subscriptions
def isSubscribed(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
subscribed = False
self.cursor.execute('SELECT subscribed FROM subscriptions WHERE userName=? AND contactId=?', (userName, contactId))
for row in self.cursor:
subscribed = row[0]
return subscribed
def maxPhotos(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
maxPhotos = 0
self.cursor.execute('SELECT maxPhotos FROM subscriptions WHERE userName=? AND contactId=?', (userName, contactId))
for row in self.cursor:
maxPhotos= row[0]
return maxPhotos
def getLastUploadDate(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
lastdate = None
self.cursor.execute('SELECT MAX(uploadDate) FROM watch WHERE userName=? AND contactId=?', (userName, contactId))
for row in self.cursor:
lastdate = row[0]
return lastdate
def photoDownloaded(self, userName, contactId, photoUrl, uploadDate):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('SELECT uploadDate FROM watch WHERE userName=? AND contactId=? AND photoUrl=?', (userName, contactId, photoUrl))
downloaded = False
for row in self.cursor:
if row[0] >= uploadDate:
downloaded = True
break
return downloaded
def markPhotoDownloaded(self, userName, contactId, photoUrl, photoFName, uploadDate):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('REPLACE INTO watch (userName, contactId, photoUrl, photoFName, uploadDate, downloadDate) VALUES (?, ?, ?, ?, ?, ?)',
(userName, contactId, photoUrl, photoFName, uploadDate, time.time()))
self.dbconn.commit()
def subscribe(self, userName, contactId, contactName, maxPhotos):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('REPLACE INTO subscriptions (userName, contactId, contactName, subscribed, maxPhotos) VALUES (?, ?, ?, 1, ?)',
(userName, contactId, contactName, maxPhotos))
self.dbconn.commit()
def unsubscribe(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('REPLACE INTO subscriptions (userName, contactId, subscribed) VALUES (?, ?, 0)',
(userName, contactId))
self.dbconn.commit()
def editSubscription(self, userName, contactId, contactName, maxPhotos):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('UPDATE subscriptions SET maxPhotos=? WHERE userName=? AND contactId=?',
(maxPhotos, userName, contactId))
self.dbconn.commit()
def getPhotoCount(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
photoCount = 0
self.cursor.execute('SELECT COUNT(*) FROM watch WHERE userName=? AND contactId=?', (userName, contactId))
for row in self.cursor:
photoCount = row[0]
return photoCount
def getOldestPhotos(self, userName, contactId, photoCount):
if not self.isConnected():
raise NotConnectedException(self.db)
oldestPhotos = []
self.cursor.execute('SELECT photoFName, photoUrl FROM watch WHERE userName=? AND contactId=? ORDER BY uploadDate LIMIT ?',
(userName, contactId, photoCount))
for row in self.cursor:
oldestPhotos.append( (row[0], row[1]) )
return oldestPhotos
def removePhotos(self, userName, contactId, photoList):
if not self.isConnected():
raise NotConnectedException(self.db)
for (photoFName, photoUrl) in photoList:
self.cursor.execute('DELETE FROM watch WHERE userName=? AND contactId=? AND photoFName=? AND photoUrl=?',
(userName, contactId, photoFName, photoUrl))
self.dbconn.commit()
def download_photos(userName, contactName, contactId, maxPhotos, flickr, db):
if not os.path.exists(userName+'/'+contactName):
os.mkdir(userName+'/'+contactName)
lastdate = db.getLastUploadDate(userName, contactId)
photoCount = db.getPhotoCount(userName, contactId)
retry = 3
while retry:
try:
if lastdate and photoCount >= maxPhotos:
photos = flickr.photos_search(user_id=contactId, min_upload_date=lastdate+1, safe_search='3', extras='date_upload', per_page=maxPhotos)
else:
photos = flickr.photos_search(user_id=contactId, safe_search='3', extras='date_upload', per_page=maxPhotos)
except:
retry = retry - 1
continue
else:
break
if not retry:
return
if photos.photos[0]['pages'] == '0':
return
print 'Evaluating', len(photos.photos[0].photo), 'photos from', contactName
for photo in photos.photos[0].photo:
uploadDate = long(photo['dateupload'])
photo['dateupload'] = uploadDate
photoUrl = 'http://farm%(farm)s.static.flickr.com/%(server)s/%(id)s_%(secret)s.jpg' % photo
fname = '%(dateupload)08d_%(farm)s_%(server)s_%(id)s_%(secret)s.jpg' % photo
if not db.photoDownloaded(userName, contactId, photoUrl, uploadDate):
print >>sys.stderr, "Downloading new photo '%s' from '%s' (%s)" % ( photoUrl, contactName, str(db.photoDownloaded(userName, contactId, photoUrl, uploadDate)))
retry = 3
while retry:
try:
photod = urllib2.urlopen(photoUrl)
fd = open(userName+'/'+contactName+'/'+fname, 'w')
shutil.copyfileobj(photod, fd)
photod.close()
fd.close()
db.markPhotoDownloaded(userName, contactId, photoUrl, fname, uploadDate)
except:
print >>sys.stderr, "Download of", photoUrl, "failed on try", (3 - retry) + 1, "of", 3
retry = retry - 1
continue
else:
break
photoCount = db.getPhotoCount(userName, contactId)
if photoCount > maxPhotos:
oldestPhotos = db.getOldestPhotos(userName, contactId, photoCount - maxPhotos)
for (fname, photoUrl) in oldestPhotos:
try:
os.remove(userName+'/'+contactName+'/'+fname)
except:
pass
db.removePhotos(userName, contactId, oldestPhotos)
def getSubscribedPhotos(userName, flickr, db):
subscriptions = db.getSubscriptions(userName)
for (contactName, contactId) in subscriptions:
# Download photos from subscribed contacts
maxPhotos = db.maxPhotos(userName, contactId)
download_photos(userName, contactName, contactId, maxPhotos, flickr, db)
def subscribe(userName, userId, flickr, db):
unsubscribed = []
contacts = flickr.contacts_getList(user_id=userId)
for contact in contacts.contacts[0].contact:
contactId = contact['nsid']
contactName = contact['username']
if not db.isSubscribed(userName, contactId):
unsubscribed.append( (contactName, contactId) )
if not db.isSubscribed(userName, userId):
unsubscribed.append( (userName, userId) )
contact = None
while not contact:
print ""
idx = 0
for (contactName, contactId) in unsubscribed:
print "%d) %s" % (idx, contactName)
idx = idx + 1
print "%d) Done subscribing" % (idx)
print ""
contact = raw_input('Subscribe to contact: ')
try:
contact = int(contact)
except:
print ""
print "Invalid selection %s, retry 0-%d" % (contact, idx)
contact = None
continue
if contact < 0 or contact > idx:
print ""
print "Invalid selection %d, retry 0-%d" % (contact, idx)
contact = None
elif contact == idx:
break
else:
(contactName, contactId) = unsubscribed[contact]
maxPhotos = None
while not maxPhotos:
print ""
maxPhotos = raw_input('How many photos from %s do you want to keep (1-500)? ' % contactName)
try:
maxPhotos = int(maxPhotos)
except:
print ""
print "Invalid selection %s, retry 0-500" % (maxPhotos)
maxPhotos = None
continue
if maxPhotos < 1 or maxPhotos > 500:
print ""
print "Invalid input %d, retry 1-500" % (maxPhotos)
maxPhotos = None
db.subscribe(userName, contactId, contactName, maxPhotos)
del unsubscribed[contact]
contact = None
def unsubscribe(userName, userId, flickr, db):
subscribed = db.getSubscriptions(userName)
contact = None
while not contact:
print ""
idx = 0
for (contactName, contactId) in subscribed:
print "%d) %s" % (idx, contactName)
idx = idx + 1
print "%d) Done unsubscribing" % (idx)
print ""
contact = raw_input('Unsubscribe to contact: ')
try:
contact = int(contact)
except:
print ""
print "Invalid selection %s, retry 0-%d" % (contact, idx)
contact = None
continue
if contact < 0 or contact > idx:
print ""
print "Invalid selection %d, retry 0-%d" % (contact, idx)
contact = None
elif contact == idx:
break
else:
(contactName, contactId) = subscribed[contact]
confirm = None
while not confirm:
print ""
confirm = raw_input('Are you sure you want to unsubscribe to %s (y or n)? ' % contactName)[0].lower()
if confirm != 'y' and confirm != n:
print ""
print "Invalid input %d, retry y or n" % (maxPhotos)
confirm = None
if confirm == 'y':
db.unsubscribe(userName, contactId)
del subscribed[contact]
contact = None
def editSubscriptions(userName, userId, flickr, db):
subscribed = db.getSubscriptions(userName)
contact = None
while not contact:
print ""
idx = 0
for (contactName, contactId) in subscribed:
print "%d) %s" % (idx, contactName)
idx = idx + 1
print "%d) Done editing subscriptions" % (idx)
print ""
contact = raw_input('Edit settings for contact: ')
try:
contact = int(contact)
except:
print ""
print "Invalid selection %s, retry 0-%d" % (contact, idx)
contact = None
continue
if contact < 0 or contact > idx:
print ""
print "Invalid selection %d, retry 0-%d" % (contact, idx)
contact = None
elif contact == idx:
break
else:
(contactName, contactId) = subscribed[contact]
maxPhotos = None
while not maxPhotos:
print ""
maxPhotos = raw_input('How many photos from %s do you want to keep (1-500)? ' % contactName)
try:
maxPhotos = int(maxPhotos)
except:
print ""
print "Invalid selection %s, retry 0-500" % (maxPhotos)
maxPhotos = None
continue
if maxPhotos < 1 or maxPhotos > 500:
print ""
print "Invalid input %d, retry 1-500" % (maxPhotos)
maxPhotos = None
db.editSubscription(userName, contactId, contactName, maxPhotos)
contact = None
def manageSubscriptions(userName, userId, flickr, db):
choice = {1: subscribe, 2: unsubscribe, 3: editSubscriptions}
selection = 0
while not selection:
print ""
print "1) Add subscriptions"
print "2) Delete subscriptions"
print "3) Edit subscriptions"
print ""
selection = raw_input('Add, delete, or edit: ')
try:
selection = int(selection)
except:
print ""
print "Invalid selection %s, retry 1-3" % (selection)
selection = None
continue
if selection < 1 or selection > 3:
print ""
print "Invalid selection %d, retry 1-3" % (selection)
choice[selection](userName, userId, flickr, db)
print " flickrwatcher version %{VERSION}, Copyright (C) 2008 Joseph G. Echeverria"
print " flickrwatcher comes with ABSOLUTELY NO WARRANTY;"
print " This is free software, and you are welcome to redistribute it"
print " under certain conditions;"
db = FlickrWatcherDb()
userList = db.getUserList()
userName = None
while not userName:
print ""
idx = 0
for user in userList:
print "%d) %s" % (idx, user)
idx = idx + 1
print "%d) Enter new user" % (idx)
print ""
userNumber = raw_input('Enter user number: ')
try:
userNumber = int(userNumber)
except:
print ""
print "Invalid selection %s, retry %d-%d" % (userNumber, 0, idx)
continue
if userNumber == idx:
userName = raw_input('Enter user name: ')
elif userNumber > idx or userNumber < 0:
print ""
print "Invalid selection %d, retry %d-%d" % (userNumber, 0, idx)
else:
userName = userList[userNumber]
if not os.path.exists(userName):
os.mkdir(userName)
flickr = flickrapi.FlickrAPI(apiKey, apiSecret)
(token, frob) = flickr.getTokenPartOne(perms='read')
if not token:
raw_input("Press ENTER after you authorized this program.")
flickr.getTokenPartTwo((token, frob))
user = flickr.people_findByUsername(username=userName)
userId = user.user[0]['nsid']
while True:
selection = None
while not selection:
print ""
print "1) Manage subscriptions"
print "2) Get new photos"
print "3) Exit"
print ""
selection = raw_input('What do you want to do?: ')
try:
selection = int(selection)
except:
print ""
print "Invalid selection %s, retry 1-3" % (selection)
selection = None
continue
if selection < 1 or selection > 3:
print ""
print "Invalid selection %d, retry 1-3" % (selection)
selection = None
continue
if selection == 1:
manageSubscriptions(userName, userId, flickr, db)
elif selection == 2:
getSubscribedPhotos(userName, flickr, db)
elif selection == 3:
break
| Python |
#! /usr/bin/env python
# flickrwatcher - Keep track of your friends' flickr photos.
# Copyright (C) 2008 Joseph G. Echeverria (joey42+flickrwatcher@gmail.com)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import os, sys, shutil, time, traceback
import urllib2
import flickrapi
import sqlite3
apiKey = 'e597cdeedb619f3f47ca999cd6f42149'
apiSecret = '578a2ab88db7e31b'
class NotConnectedException(Exception):
def __init__(self, db):
self.db = db
def __str__(self):
return self.db
class FlickrWatcherDb():
def __init__(self, db='flickrwatcher.db'):
try:
self.db = db
self.dbconn = sqlite3.connect(db)
self.cursor = self.dbconn.cursor()
self.cursor.execute("""CREATE TABLE IF NOT EXISTS subscriptions
(
userName text,
contactName text,
contactId text,
subscribed integer,
maxPhotos integer,
UNIQUE
(
userName,
contactId
) ON CONFLICT REPLACE
)""")
self.cursor.execute("""CREATE TABLE IF NOT EXISTS watch
(
userName text,
contactId text,
photoUrl text,
photoFName text,
uploadDate integer,
downloadDate integer,
UNIQUE
(
userName,
contactId,
photoUrl
) ON CONFLICT REPLACE
)""")
self.dbconn.commit()
except Exception, e:
traceback.print_exc()
print >>sys.stderr, e
self.dbconn = None
self.cursor = None
def isConnected(self):
return self.dbconn and self.cursor
def getUserList(self):
if not self.isConnected():
raise NotConnectedException(self.db)
userList = []
self.cursor.execute('SELECT DISTINCT userName FROM subscriptions')
for row in self.cursor:
userList.append(row[0])
return userList
def getSubscriptions(self, userName):
if not self.isConnected():
raise NotConnectedException(self.db)
subscriptions = []
self.cursor.execute('SELECT contactName, contactId FROM subscriptions WHERE userName=? AND subscribed=1', (userName,))
for row in self.cursor:
subscriptions.append( (row[0], row[1]) )
return subscriptions
def isSubscribed(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
subscribed = False
self.cursor.execute('SELECT subscribed FROM subscriptions WHERE userName=? AND contactId=?', (userName, contactId))
for row in self.cursor:
subscribed = row[0]
return subscribed
def maxPhotos(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
maxPhotos = 0
self.cursor.execute('SELECT maxPhotos FROM subscriptions WHERE userName=? AND contactId=?', (userName, contactId))
for row in self.cursor:
maxPhotos= row[0]
return maxPhotos
def getLastUploadDate(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
lastdate = None
self.cursor.execute('SELECT MAX(uploadDate) FROM watch WHERE userName=? AND contactId=?', (userName, contactId))
for row in self.cursor:
lastdate = row[0]
return lastdate
def photoDownloaded(self, userName, contactId, photoUrl, uploadDate):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('SELECT uploadDate FROM watch WHERE userName=? AND contactId=? AND photoUrl=?', (userName, contactId, photoUrl))
downloaded = False
for row in self.cursor:
if row[0] >= uploadDate:
downloaded = True
break
return downloaded
def markPhotoDownloaded(self, userName, contactId, photoUrl, photoFName, uploadDate):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('REPLACE INTO watch (userName, contactId, photoUrl, photoFName, uploadDate, downloadDate) VALUES (?, ?, ?, ?, ?, ?)',
(userName, contactId, photoUrl, photoFName, uploadDate, time.time()))
self.dbconn.commit()
def subscribe(self, userName, contactId, contactName, maxPhotos):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('REPLACE INTO subscriptions (userName, contactId, contactName, subscribed, maxPhotos) VALUES (?, ?, ?, 1, ?)',
(userName, contactId, contactName, maxPhotos))
self.dbconn.commit()
def unsubscribe(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('REPLACE INTO subscriptions (userName, contactId, subscribed) VALUES (?, ?, 0)',
(userName, contactId))
self.dbconn.commit()
def editSubscription(self, userName, contactId, contactName, maxPhotos):
if not self.isConnected():
raise NotConnectedException(self.db)
self.cursor.execute('UPDATE subscriptions SET maxPhotos=? WHERE userName=? AND contactId=?',
(maxPhotos, userName, contactId))
self.dbconn.commit()
def getPhotoCount(self, userName, contactId):
if not self.isConnected():
raise NotConnectedException(self.db)
photoCount = 0
self.cursor.execute('SELECT COUNT(*) FROM watch WHERE userName=? AND contactId=?', (userName, contactId))
for row in self.cursor:
photoCount = row[0]
return photoCount
def getOldestPhotos(self, userName, contactId, photoCount):
if not self.isConnected():
raise NotConnectedException(self.db)
oldestPhotos = []
self.cursor.execute('SELECT photoFName, photoUrl FROM watch WHERE userName=? AND contactId=? ORDER BY uploadDate LIMIT ?',
(userName, contactId, photoCount))
for row in self.cursor:
oldestPhotos.append( (row[0], row[1]) )
return oldestPhotos
def removePhotos(self, userName, contactId, photoList):
if not self.isConnected():
raise NotConnectedException(self.db)
for (photoFName, photoUrl) in photoList:
self.cursor.execute('DELETE FROM watch WHERE userName=? AND contactId=? AND photoFName=? AND photoUrl=?',
(userName, contactId, photoFName, photoUrl))
self.dbconn.commit()
def download_photos(userName, contactName, contactId, maxPhotos, flickr, db):
if not os.path.exists(userName+'/'+contactName):
os.mkdir(userName+'/'+contactName)
lastdate = db.getLastUploadDate(userName, contactId)
photoCount = db.getPhotoCount(userName, contactId)
retry = 3
while retry:
try:
if lastdate and photoCount >= maxPhotos:
photos = flickr.photos_search(user_id=contactId, min_upload_date=lastdate+1, safe_search='3', extras='date_upload', per_page=maxPhotos)
else:
photos = flickr.photos_search(user_id=contactId, safe_search='3', extras='date_upload', per_page=maxPhotos)
except:
retry = retry - 1
continue
else:
break
if not retry:
return
if photos.photos[0]['pages'] == '0':
return
print 'Evaluating', len(photos.photos[0].photo), 'photos from', contactName
for photo in photos.photos[0].photo:
uploadDate = long(photo['dateupload'])
photo['dateupload'] = uploadDate
photoUrl = 'http://farm%(farm)s.static.flickr.com/%(server)s/%(id)s_%(secret)s.jpg' % photo
fname = '%(dateupload)08d_%(farm)s_%(server)s_%(id)s_%(secret)s.jpg' % photo
if not db.photoDownloaded(userName, contactId, photoUrl, uploadDate):
print >>sys.stderr, "Downloading new photo '%s' from '%s' (%s)" % ( photoUrl, contactName, str(db.photoDownloaded(userName, contactId, photoUrl, uploadDate)))
retry = 3
while retry:
try:
photod = urllib2.urlopen(photoUrl)
fd = open(userName+'/'+contactName+'/'+fname, 'w')
shutil.copyfileobj(photod, fd)
photod.close()
fd.close()
db.markPhotoDownloaded(userName, contactId, photoUrl, fname, uploadDate)
except:
print >>sys.stderr, "Download of", photoUrl, "failed on try", (3 - retry) + 1, "of", 3
retry = retry - 1
continue
else:
break
photoCount = db.getPhotoCount(userName, contactId)
if photoCount > maxPhotos:
oldestPhotos = db.getOldestPhotos(userName, contactId, photoCount - maxPhotos)
for (fname, photoUrl) in oldestPhotos:
try:
os.remove(userName+'/'+contactName+'/'+fname)
except:
pass
db.removePhotos(userName, contactId, oldestPhotos)
def getSubscribedPhotos(userName, flickr, db):
subscriptions = db.getSubscriptions(userName)
for (contactName, contactId) in subscriptions:
# Download photos from subscribed contacts
maxPhotos = db.maxPhotos(userName, contactId)
download_photos(userName, contactName, contactId, maxPhotos, flickr, db)
def subscribe(userName, userId, flickr, db):
unsubscribed = []
contacts = flickr.contacts_getList(user_id=userId)
for contact in contacts.contacts[0].contact:
contactId = contact['nsid']
contactName = contact['username']
if not db.isSubscribed(userName, contactId):
unsubscribed.append( (contactName, contactId) )
if not db.isSubscribed(userName, userId):
unsubscribed.append( (userName, userId) )
contact = None
while not contact:
print ""
idx = 0
for (contactName, contactId) in unsubscribed:
print "%d) %s" % (idx, contactName)
idx = idx + 1
print "%d) Done subscribing" % (idx)
print ""
contact = raw_input('Subscribe to contact: ')
try:
contact = int(contact)
except:
print ""
print "Invalid selection %s, retry 0-%d" % (contact, idx)
contact = None
continue
if contact < 0 or contact > idx:
print ""
print "Invalid selection %d, retry 0-%d" % (contact, idx)
contact = None
elif contact == idx:
break
else:
(contactName, contactId) = unsubscribed[contact]
maxPhotos = None
while not maxPhotos:
print ""
maxPhotos = raw_input('How many photos from %s do you want to keep (1-500)? ' % contactName)
try:
maxPhotos = int(maxPhotos)
except:
print ""
print "Invalid selection %s, retry 0-500" % (maxPhotos)
maxPhotos = None
continue
if maxPhotos < 1 or maxPhotos > 500:
print ""
print "Invalid input %d, retry 1-500" % (maxPhotos)
maxPhotos = None
db.subscribe(userName, contactId, contactName, maxPhotos)
del unsubscribed[contact]
contact = None
def unsubscribe(userName, userId, flickr, db):
subscribed = db.getSubscriptions(userName)
contact = None
while not contact:
print ""
idx = 0
for (contactName, contactId) in subscribed:
print "%d) %s" % (idx, contactName)
idx = idx + 1
print "%d) Done unsubscribing" % (idx)
print ""
contact = raw_input('Unsubscribe to contact: ')
try:
contact = int(contact)
except:
print ""
print "Invalid selection %s, retry 0-%d" % (contact, idx)
contact = None
continue
if contact < 0 or contact > idx:
print ""
print "Invalid selection %d, retry 0-%d" % (contact, idx)
contact = None
elif contact == idx:
break
else:
(contactName, contactId) = subscribed[contact]
confirm = None
while not confirm:
print ""
confirm = raw_input('Are you sure you want to unsubscribe to %s (y or n)? ' % contactName)[0].lower()
if confirm != 'y' and confirm != n:
print ""
print "Invalid input %d, retry y or n" % (maxPhotos)
confirm = None
if confirm == 'y':
db.unsubscribe(userName, contactId)
del subscribed[contact]
contact = None
def editSubscriptions(userName, userId, flickr, db):
subscribed = db.getSubscriptions(userName)
contact = None
while not contact:
print ""
idx = 0
for (contactName, contactId) in subscribed:
print "%d) %s" % (idx, contactName)
idx = idx + 1
print "%d) Done editing subscriptions" % (idx)
print ""
contact = raw_input('Edit settings for contact: ')
try:
contact = int(contact)
except:
print ""
print "Invalid selection %s, retry 0-%d" % (contact, idx)
contact = None
continue
if contact < 0 or contact > idx:
print ""
print "Invalid selection %d, retry 0-%d" % (contact, idx)
contact = None
elif contact == idx:
break
else:
(contactName, contactId) = subscribed[contact]
maxPhotos = None
while not maxPhotos:
print ""
maxPhotos = raw_input('How many photos from %s do you want to keep (1-500)? ' % contactName)
try:
maxPhotos = int(maxPhotos)
except:
print ""
print "Invalid selection %s, retry 0-500" % (maxPhotos)
maxPhotos = None
continue
if maxPhotos < 1 or maxPhotos > 500:
print ""
print "Invalid input %d, retry 1-500" % (maxPhotos)
maxPhotos = None
db.editSubscription(userName, contactId, contactName, maxPhotos)
contact = None
def manageSubscriptions(userName, userId, flickr, db):
choice = {1: subscribe, 2: unsubscribe, 3: editSubscriptions}
selection = 0
while not selection:
print ""
print "1) Add subscriptions"
print "2) Delete subscriptions"
print "3) Edit subscriptions"
print ""
selection = raw_input('Add, delete, or edit: ')
try:
selection = int(selection)
except:
print ""
print "Invalid selection %s, retry 1-3" % (selection)
selection = None
continue
if selection < 1 or selection > 3:
print ""
print "Invalid selection %d, retry 1-3" % (selection)
choice[selection](userName, userId, flickr, db)
print " flickrwatcher version %{VERSION}, Copyright (C) 2008 Joseph G. Echeverria"
print " flickrwatcher comes with ABSOLUTELY NO WARRANTY;"
print " This is free software, and you are welcome to redistribute it"
print " under certain conditions;"
db = FlickrWatcherDb()
userList = db.getUserList()
userName = None
while not userName:
print ""
idx = 0
for user in userList:
print "%d) %s" % (idx, user)
idx = idx + 1
print "%d) Enter new user" % (idx)
print ""
userNumber = raw_input('Enter user number: ')
try:
userNumber = int(userNumber)
except:
print ""
print "Invalid selection %s, retry %d-%d" % (userNumber, 0, idx)
continue
if userNumber == idx:
userName = raw_input('Enter user name: ')
elif userNumber > idx or userNumber < 0:
print ""
print "Invalid selection %d, retry %d-%d" % (userNumber, 0, idx)
else:
userName = userList[userNumber]
if not os.path.exists(userName):
os.mkdir(userName)
flickr = flickrapi.FlickrAPI(apiKey, apiSecret)
(token, frob) = flickr.getTokenPartOne(perms='read')
if not token:
raw_input("Press ENTER after you authorized this program.")
flickr.getTokenPartTwo((token, frob))
user = flickr.people_findByUsername(username=userName)
userId = user.user[0]['nsid']
while True:
selection = None
while not selection:
print ""
print "1) Manage subscriptions"
print "2) Get new photos"
print "3) Exit"
print ""
selection = raw_input('What do you want to do?: ')
try:
selection = int(selection)
except:
print ""
print "Invalid selection %s, retry 1-3" % (selection)
selection = None
continue
if selection < 1 or selection > 3:
print ""
print "Invalid selection %d, retry 1-3" % (selection)
selection = None
continue
if selection == 1:
manageSubscriptions(userName, userId, flickr, db)
elif selection == 2:
getSubscribedPhotos(userName, flickr, db)
elif selection == 3:
break
| Python |
# Django settings for moviering project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
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.
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
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'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'a%3d037pj3f8@87qjn9^cy-wb*y-j=oyxzb3c1@28%gqnt)7v@'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
)
ROOT_URLCONF = 'moviering.urls'
import os
ROOT_PATH = os.path.dirname(__file__)
TEMPLATE_DIRS = (
ROOT_PATH + '/templates',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'moviering.moviering',
)
| Python |
from google.appengine.api import users
from google.appengine.ext import db
from common import *
import datetime
string_encoding = 'latin1'
class Dude(db.Model):
email = db.StringProperty()
nickname = db.StringProperty()
homepage = db.StringProperty()
created_on = db.DateTimeProperty(auto_now_add = 1)
created_by = db.UserProperty()
comments = db.StringProperty(multiline=True)
standard_email_sign = db.StringProperty(multiline=True)
# new
recieve_newsletter = db.BooleanProperty(default = True)
location = db.StringProperty()
enable_fancy_stuff = db.BooleanProperty(default = True)
def homepage_(self):
return self.homepage.encode(string_encoding)
def nickname_(self):
return self.nickname.encode(string_encoding)
def comments_(self):
return self.comments.encode(string_encoding)
def location_(self):
return self.location.encode(string_encoding)
def standard_email_sign_(self):
return self.standard_email_sign.encode(string_encoding)
def get_absolute_url(self):
return '/dude/%s/' % self.key()
def has_access(self):
return str(users.get_current_user().email()) in [str(acl.owner.email) for acl in self.guests]
class Movie(db.Model):
title = db.StringProperty()
buy_url = db.StringProperty()
imdb_url = db.StringProperty()
comments = db.StringProperty()
created_on = db.DateTimeProperty(auto_now_add = 1)
created_by = db.UserProperty()
media_type = db.IntegerProperty(default = 0)
status = db.IntegerProperty(default = 0)
genre = db.IntegerProperty(default = 0)
kudos_count = db.IntegerProperty(default = 0)
can_be_sold = db.BooleanProperty(default = True)
suggested_price = db.StringProperty()
can_be_borrowed = db.BooleanProperty(default = True)
can_be_swapped = db.BooleanProperty(default = True)
is_public = db.BooleanProperty(default = False)
def comments_count(self):
return len(list(self.user_comments))
def for_sale_only(self):
if self.can_be_borrowed or self.can_be_swapped:
return False
return self.can_be_sold == True
def title_(self):
return self.title.encode(string_encoding)
def comments_(self):
return self.comments.encode(string_encoding)
def imdb_url_(self):
return self.imdb_url.encode(string_encoding)
def buy_url_(self):
return self.buy_url.encode(string_encoding)
def get_absolute_url(self):
return '/movie/%s/' % self.key()
def status_text(self):
return status_dict.get(self.status, '')
def media_text(self):
return media_dict.get(self.media_type, '?')
def imdb_qs(self):
if self.imdb_url:
return self.imdb_url_()
return 'http://www.imdb.com/find?s=all&q=%s' % '+'.join(self.title_.lower().split(' '))
def contact_mail(self):
return self.created_by.email()
def genre_text(self):
return genre_dict.get(self.genre, '')
def review_mode(self):
return self.status == MovieStatus.Review
def calculated_rating(self):
if not self.ratings:
return None
value = 0.0
counter = 0.0
for r in self.ratings:
value += r.rating
counter += 1
if counter != 0:
return '%.1f' % (value / counter)
return None
def is_owner(self):
return self.created_by == users.get_current_user()
def is_available(self):
return self.status == MovieStatus.Available
def owner_nickname(self):
query = db.GqlQuery("SELECT * FROM Dude WHERE email = :1", self.created_by.email())
qs = query.fetch(1)
dude = None
if len(qs) == 1:
dude = qs[0]
return dude.nickname.encode(string_encoding)
def can_give_kudos(self):
current_user = users.get_current_user()
return current_user not in [i.user for i in self.kudos] and self.created_by != current_user
class Access(db.Model):
owner = db.ReferenceProperty(Dude, collection_name="owners")
guest = db.ReferenceProperty(Dude, collection_name="guests")
class Kudos(db.Model):
user = db.UserProperty()
movie = db.ReferenceProperty(Movie, collection_name="kudos")
class Action(db.Model):
user = db.UserProperty()
movie = db.ReferenceProperty(Movie, collection_name="actions")
action = db.StringProperty()
completed = db.BooleanProperty(default = None)
class Rating(db.Model):
user = db.UserProperty()
movie = db.ReferenceProperty(Movie, collection_name="ratings")
rating = db.IntegerProperty(default = 0)
class Loan(db.Model):
guest = db.ReferenceProperty(Dude, collection_name="loaners")
movie = db.ReferenceProperty(Movie, collection_name="loans")
created_on = db.DateTimeProperty(auto_now_add = 1)
due_date = db.DateTimeProperty()
returned = db.BooleanProperty(default = None)
def over_due(self):
return datetime.datetime.today() < self.due_date
class MovieComment(db.Model):
movie = db.ReferenceProperty(Movie, collection_name="user_comments")
created_on = db.DateTimeProperty(auto_now_add = 1)
author = db.ReferenceProperty(Dude, collection_name="comment_authors")
comment = db.StringProperty()
def comment_(self):
return self.comment.encode(string_encoding)
class SystemInfo(db.Model):
date_of_last_newsletter = db.DateTimeProperty(auto_now_add = 1)
class MiniBlog(db.Model):
title_ = db.StringProperty()
body_ = db.StringProperty()
created_on = db.DateTimeProperty(auto_now_add = 1)
created_by = db.UserProperty()
sort_order = db.IntegerProperty(default = 999)
public = db.BooleanProperty(default = True)
def get_title(self):
return self.title_.encode('latin1')
def set_title(self, value):
self.title_ = unicode(value, 'utf-8')
title = property(get_title, set_title) | Python |
import types
string_encoding = 'latin1'
def st(s):
return unicode(s, string_encoding)
status_dict = {
1 : 'Ordered',
2 : 'Available',
3 : 'Unavailable',
4 : 'Wanted',
5 : 'Review'
}
media_dict = {
1: 'Blu-ray',
2: 'DVD',
3: 'Other'
}
genre_dict = {
1: 'Action',
2: 'Comedy',
3: 'Thriller',
4: 'Horror',
5: 'Music',
6: 'Documentary',
7: 'Animation',
8: 'Romance',
9: 'Drama',
10: 'Sci-fi',
11: 'Adult',
12: 'Mystery',
13: 'Adventure'
}
reverse_genre_dict = {}
for k,v in genre_dict.items():
reverse_genre_dict[v] = k
class MovieStatus:
Ordered = 1
Available = 2
Unavailable = 3
Wanted = 4
Review = 5
class MediaType:
Bluray = 1
DVD = 2
Other = 3
def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Returns a bytestring version of 's', encoded as specified in 'encoding'.
If strings_only is True, don't convert (some) non-string-like objects.
"""
if strings_only and isinstance(s, (types.NoneType, int)):
return s
if isinstance(s, str):
return unicode(s).encode(encoding, errors)
elif not isinstance(s, basestring):
try:
return str(s)
except UnicodeEncodeError:
if isinstance(s, Exception):
# An Exception subclass containing non-ASCII data that doesn't
# know how to print itself properly. We shouldn't raise a
# further exception.
return ' '.join([smart_str(arg, encoding, strings_only,
errors) for arg in s])
return unicode(s).encode(encoding, errors)
elif isinstance(s, unicode):
return s.encode(encoding, errors)
elif s and encoding != 'utf-8':
return s.decode('utf-8', errors).encode(encoding, errors)
else:
return s
#try:
# unicode(s, 'ISO-8859-1'))
#except (UnicodeEncodeError, UnicodeDecodeError), e:
# pass
#s.encode('utf-8')
| Python |
#!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
| Python |
from django.conf.urls.defaults import *
from feeds import LatestEntries
latest_feeds = {
'latest': LatestEntries,
'categories': LatestEntries,
}
urlpatterns = patterns('',
(r'^$', 'moviering.moviering.views.index'),
(r'profile/$', 'moviering.moviering.views.profile'),
#(r'newsletter/$', 'moviering.moviering.views.newsletter'),
(r'send_updates/$', 'moviering.moviering.views.send_updates'),
(r'actions/$', 'moviering.moviering.views.actions'),
(r'add/$', 'moviering.moviering.views.add'),
(r'add_many/$', 'moviering.moviering.views.add_many'),
(r'add_review/$', 'moviering.moviering.views.add_review'),
(r'^movie/(?P<movie_key>[^\.^/]+)/$', 'moviering.moviering.views.view'),
(r'^delete/(?P<movie_key>[^\.^/]+)/$', 'moviering.moviering.views.delete'),
(r'^update/(?P<movie_key>[^\.^/]+)/$', 'moviering.moviering.views.update'),
#(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': latest_feeds}),
(r'^by_status/(?P<status>[^\.^/]+)/$', 'moviering.moviering.views.by_status'),
(r'^by_media/(?P<media_type>[^\.^/]+)/$', 'moviering.moviering.views.by_media'),
(r'for_sale/$', 'moviering.moviering.views.for_sale'),
(r'^by_dude/(?P<dude_key>[^\.^/]+)/$', 'moviering.moviering.views.by_dude'),
(r'^by_group/(?P<group>[^\.^/]+)/$', 'moviering.moviering.views.by_group'),
(r'^buy/(?P<movie_key>[^\.^/]+)/$', 'moviering.moviering.views.buy'),
(r'^swap/(?P<movie_key>[^\.^/]+)/$', 'moviering.moviering.views.swap'),
(r'^borrow/(?P<movie_key>[^\.^/]+)/$', 'moviering.moviering.views.borrow'),
(r'^kudos/(?P<movie_key>[^\.^/]+)/$', 'moviering.moviering.views.kudos'),
(r'^by_genre/(?P<genre>[^\.^/]+)/$', 'moviering.moviering.views.by_genre'),
(r'users/$', 'moviering.moviering.views.list_users'),
(r'^grant_access/(?P<dude_key>[^\.^/]+)/$', 'moviering.moviering.views.grant_access'),
(r'^revoke_access/(?P<dude_key>[^\.^/]+)/$', 'moviering.moviering.views.revoke_access'),
(r'^set_unavailable/(?P<movie_key>[^\.^/]+)/$', 'moviering.moviering.views.set_unavailable'),
(r'wanted_movies/$', 'moviering.moviering.views.wanted_movies'),
(r'most_kodus/$', 'moviering.moviering.views.most_kodus'),
(r'blurays/$', 'moviering.moviering.views.blurays'),
(r'dvds/$', 'moviering.moviering.views.dvds'),
(r'by_rating/$', 'moviering.moviering.views.by_rating'),
(r'process_multiple/$', 'moviering.moviering.views.process_multiple'),
(r'give_rating/(?P<movie_key>\w+)/(?P<rating>\w+)/$', 'moviering.moviering.views.give_rating'),
(r'^delete_comment/(?P<comment_key>[^\.^/]+)/$', 'moviering.moviering.views.delete_comment'),
(r'^borrow_to/$', 'moviering.moviering.views.borrow_to'),
(r'^list_loans/$', 'moviering.moviering.views.list_loans'),
(r'^reviews/$', 'moviering.moviering.views.reviews'),
(r'^to_xml/$', 'moviering.moviering.views.to_xml'),
#(r'test/$', 'moviering.moviering.views.test'),
)
| Python |
from django.contrib.syndication.feeds import Feed
from moviering.views import get_movies
class LatestEntries(Feed):
title = "Movie Ring"
link = "/"
description = "Some movies."
def items(self):
return get_flicks()
| Python |
#!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
| Python |
import os,sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'moviering.settings'
# Google App Engine imports.
from google.appengine.ext.webapp import util
# Force Django to reload its settings.
from django.conf import settings
settings._target = None
import django.core.handlers.wsgi
import django.core.signals
import django.db
import django.dispatch.dispatcher
# Log errors.
#django.dispatch.dispatcher.connect(
# log_exception, django.core.signals.got_request_exception)
# Unregister the rollback event handler.
django.dispatch.dispatcher.disconnect(
django.db._rollback_on_exception,
django.core.signals.got_request_exception)
def main():
# Create a Django application for WSGI.
application = django.core.handlers.wsgi.WSGIHandler()
# Run the WSGI CGI handler with that application.
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
| Python |
import multiprocessing
| Python |
# -*- coding: utf-8 -*-
from ragendja.settings_pre import *
# Increase this when you update your media on the production site, so users
# don't have to refresh their cache. By setting this your MEDIA_URL
# automatically becomes /media/MEDIA_VERSION/
MEDIA_VERSION = 1
# By hosting media on a different domain we can get a speedup (more parallel
# browser connections).
#if on_production_server or not have_appserver:
# MEDIA_URL = 'http://media.mydomain.com/media/%d/'
# Add base media (jquery can be easily added via INSTALLED_APPS)
COMBINE_MEDIA = {
'combined-%(LANGUAGE_CODE)s.js': (
# See documentation why site_data can be useful:
# http://code.google.com/p/app-engine-patch/wiki/MediaGenerator
'.site_data.js',
),
'combined-%(LANGUAGE_DIR)s.css': (
'global/look.css',
),
}
# Change your email settings
if on_production_server:
DEFAULT_FROM_EMAIL = 'bla@bla.com'
SERVER_EMAIL = DEFAULT_FROM_EMAIL
# Make this unique, and don't share it with anybody.
SECRET_KEY = '1234567890'
#ENABLE_PROFILER = True
#ONLY_FORCED_PROFILE = True
#PROFILE_PERCENTAGE = 25
#SORT_PROFILE_RESULTS_BY = 'cumulative' # default is 'time'
# Profile only datastore calls
#PROFILE_PATTERN = 'ext.db..+\((?:get|get_by_key_name|fetch|count|put)\)'
# Enable I18N and set default language to 'en'
USE_I18N = True
LANGUAGE_CODE = 'en'
# Restrict supported languages (and JS media generation)
LANGUAGES = (
('de', 'German'),
('en', 'English'),
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.auth',
'django.core.context_processors.media',
'django.core.context_processors.request',
'django.core.context_processors.i18n',
)
MIDDLEWARE_CLASSES = (
'ragendja.middleware.ErrorMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
# Django authentication
'django.contrib.auth.middleware.AuthenticationMiddleware',
# Google authentication
#'ragendja.auth.middleware.GoogleAuthenticationMiddleware',
# Hybrid Django/Google authentication
#'ragendja.auth.middleware.HybridAuthenticationMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.locale.LocaleMiddleware',
'ragendja.sites.dynamicsite.DynamicSiteIDMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
)
# Google authentication
#AUTH_USER_MODULE = 'ragendja.auth.google_models'
#AUTH_ADMIN_MODULE = 'ragendja.auth.google_admin'
# Hybrid Django/Google authentication
#AUTH_USER_MODULE = 'ragendja.auth.hybrid_models'
LOGIN_URL = '/account/login/'
LOGOUT_URL = '/account/logout/'
LOGIN_REDIRECT_URL = '/'
INSTALLED_APPS = (
# Add jquery support (app is in "common" folder). This automatically
# adds jquery to your COMBINE_MEDIA['combined-%(LANGUAGE_CODE)s.js']
# Note: the order of your INSTALLED_APPS specifies the order in which
# your app-specific media files get combined, so jquery should normally
# come first.
'jquery',
# Add blueprint CSS (http://blueprintcss.org/)
'blueprintcss',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.webdesign',
'django.contrib.flatpages',
'django.contrib.redirects',
'django.contrib.sites',
'appenginepatcher',
'ragendja',
'myapp',
'registration',
'mediautils',
)
# List apps which should be left out from app settings and urlsauto loading
IGNORE_APP_SETTINGS = IGNORE_APP_URLSAUTO = (
# Example:
# 'django.contrib.admin',
# 'django.contrib.auth',
# 'yetanotherapp',
)
# Remote access to production server (e.g., via manage.py shell --remote)
DATABASE_OPTIONS = {
# Override remoteapi handler's path (default: '/remote_api').
# This is a good idea, so you make it not too easy for hackers. ;)
# Don't forget to also update your app.yaml!
#'remote_url': '/remote-secret-url',
# !!!Normally, the following settings should not be used!!!
# Always use remoteapi (no need to add manage.py --remote option)
#'use_remote': True,
# Change appid for remote connection (by default it's the same as in
# your app.yaml)
#'remote_id': 'otherappid',
# Change domain (default: <remoteid>.appspot.com)
#'remote_host': 'bla.com',
}
from ragendja.settings_post import *
| Python |
# Django settings for moviering project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
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.
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
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'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'a%3d037pj3f8@87qjn9^cy-wb*y-j=oyxzb3c1@28%gqnt)7v@'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
)
ROOT_URLCONF = 'moviering.urls'
import os
ROOT_PATH = os.path.dirname(__file__)
TEMPLATE_DIRS = (
ROOT_PATH + '/templates',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'moviering.moviering',
)
| Python |
from google.appengine.api import users
from google.appengine.ext import db
from common import *
import datetime
string_encoding = 'latin1'
class Dude(db.Model):
email = db.StringProperty()
nickname = db.StringProperty()
homepage = db.StringProperty()
created_on = db.DateTimeProperty(auto_now_add = 1)
created_by = db.UserProperty()
comments = db.StringProperty(multiline=True)
standard_email_sign = db.StringProperty(multiline=True)
# new
recieve_newsletter = db.BooleanProperty(default = True)
location = db.StringProperty()
enable_fancy_stuff = db.BooleanProperty(default = True)
def homepage_(self):
return self.homepage.encode(string_encoding)
def nickname_(self):
return self.nickname.encode(string_encoding)
def comments_(self):
return self.comments.encode(string_encoding)
def location_(self):
return self.location.encode(string_encoding)
def standard_email_sign_(self):
return self.standard_email_sign.encode(string_encoding)
def get_absolute_url(self):
return '/dude/%s/' % self.key()
def has_access(self):
return str(users.get_current_user().email()) in [str(acl.owner.email) for acl in self.guests]
class Movie(db.Model):
title = db.StringProperty()
buy_url = db.StringProperty()
imdb_url = db.StringProperty()
comments = db.StringProperty()
created_on = db.DateTimeProperty(auto_now_add = 1)
created_by = db.UserProperty()
media_type = db.IntegerProperty(default = 0)
status = db.IntegerProperty(default = 0)
genre = db.IntegerProperty(default = 0)
kudos_count = db.IntegerProperty(default = 0)
can_be_sold = db.BooleanProperty(default = True)
suggested_price = db.StringProperty()
can_be_borrowed = db.BooleanProperty(default = True)
can_be_swapped = db.BooleanProperty(default = True)
is_public = db.BooleanProperty(default = False)
def comments_count(self):
return len(list(self.user_comments))
def for_sale_only(self):
if self.can_be_borrowed or self.can_be_swapped:
return False
return self.can_be_sold == True
def title_(self):
return self.title.encode(string_encoding)
def comments_(self):
return self.comments.encode(string_encoding)
def imdb_url_(self):
return self.imdb_url.encode(string_encoding)
def buy_url_(self):
return self.buy_url.encode(string_encoding)
def get_absolute_url(self):
return '/movie/%s/' % self.key()
def status_text(self):
return status_dict.get(self.status, '')
def media_text(self):
return media_dict.get(self.media_type, '?')
def imdb_qs(self):
if self.imdb_url:
return self.imdb_url_()
return 'http://www.imdb.com/find?s=all&q=%s' % '+'.join(self.title_.lower().split(' '))
def contact_mail(self):
return self.created_by.email()
def genre_text(self):
return genre_dict.get(self.genre, '')
def review_mode(self):
return self.status == MovieStatus.Review
def calculated_rating(self):
if not self.ratings:
return None
value = 0.0
counter = 0.0
for r in self.ratings:
value += r.rating
counter += 1
if counter != 0:
return '%.1f' % (value / counter)
return None
def is_owner(self):
return self.created_by == users.get_current_user()
def is_available(self):
return self.status == MovieStatus.Available
def owner_nickname(self):
query = db.GqlQuery("SELECT * FROM Dude WHERE email = :1", self.created_by.email())
qs = query.fetch(1)
dude = None
if len(qs) == 1:
dude = qs[0]
return dude.nickname.encode(string_encoding)
def can_give_kudos(self):
current_user = users.get_current_user()
return current_user not in [i.user for i in self.kudos] and self.created_by != current_user
class Access(db.Model):
owner = db.ReferenceProperty(Dude, collection_name="owners")
guest = db.ReferenceProperty(Dude, collection_name="guests")
class Kudos(db.Model):
user = db.UserProperty()
movie = db.ReferenceProperty(Movie, collection_name="kudos")
class Action(db.Model):
user = db.UserProperty()
movie = db.ReferenceProperty(Movie, collection_name="actions")
action = db.StringProperty()
completed = db.BooleanProperty(default = None)
class Rating(db.Model):
user = db.UserProperty()
movie = db.ReferenceProperty(Movie, collection_name="ratings")
rating = db.IntegerProperty(default = 0)
class Loan(db.Model):
guest = db.ReferenceProperty(Dude, collection_name="loaners")
movie = db.ReferenceProperty(Movie, collection_name="loans")
created_on = db.DateTimeProperty(auto_now_add = 1)
due_date = db.DateTimeProperty()
returned = db.BooleanProperty(default = None)
def over_due(self):
return datetime.datetime.today() < self.due_date
class MovieComment(db.Model):
movie = db.ReferenceProperty(Movie, collection_name="user_comments")
created_on = db.DateTimeProperty(auto_now_add = 1)
author = db.ReferenceProperty(Dude, collection_name="comment_authors")
comment = db.StringProperty()
def comment_(self):
return self.comment.encode(string_encoding)
class SystemInfo(db.Model):
date_of_last_newsletter = db.DateTimeProperty(auto_now_add = 1)
class MiniBlog(db.Model):
title_ = db.StringProperty()
body_ = db.StringProperty()
created_on = db.DateTimeProperty(auto_now_add = 1)
created_by = db.UserProperty()
sort_order = db.IntegerProperty(default = 999)
public = db.BooleanProperty(default = True)
def get_title(self):
return self.title_.encode('latin1')
def set_title(self, value):
self.title_ = unicode(value, 'utf-8')
title = property(get_title, set_title) | Python |
import types
string_encoding = 'latin1'
def st(s):
return unicode(s, string_encoding)
status_dict = {
1 : 'Ordered',
2 : 'Available',
3 : 'Unavailable',
4 : 'Wanted',
5 : 'Review'
}
media_dict = {
1: 'Blu-ray',
2: 'DVD',
3: 'Other'
}
genre_dict = {
1: 'Action',
2: 'Comedy',
3: 'Thriller',
4: 'Horror',
5: 'Music',
6: 'Documentary',
7: 'Animation',
8: 'Romance',
9: 'Drama',
10: 'Sci-fi',
11: 'Adult',
12: 'Mystery',
13: 'Adventure'
}
reverse_genre_dict = {}
for k,v in genre_dict.items():
reverse_genre_dict[v] = k
class MovieStatus:
Ordered = 1
Available = 2
Unavailable = 3
Wanted = 4
Review = 5
class MediaType:
Bluray = 1
DVD = 2
Other = 3
def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Returns a bytestring version of 's', encoded as specified in 'encoding'.
If strings_only is True, don't convert (some) non-string-like objects.
"""
if strings_only and isinstance(s, (types.NoneType, int)):
return s
if isinstance(s, str):
return unicode(s).encode(encoding, errors)
elif not isinstance(s, basestring):
try:
return str(s)
except UnicodeEncodeError:
if isinstance(s, Exception):
# An Exception subclass containing non-ASCII data that doesn't
# know how to print itself properly. We shouldn't raise a
# further exception.
return ' '.join([smart_str(arg, encoding, strings_only,
errors) for arg in s])
return unicode(s).encode(encoding, errors)
elif isinstance(s, unicode):
return s.encode(encoding, errors)
elif s and encoding != 'utf-8':
return s.decode('utf-8', errors).encode(encoding, errors)
else:
return s
#try:
# unicode(s, 'ISO-8859-1'))
#except (UnicodeEncodeError, UnicodeDecodeError), e:
# pass
#s.encode('utf-8')
| Python |
#!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
| Python |
from django.conf.urls.defaults import *
from feeds import LatestEntries
latest_feeds = {
'latest': LatestEntries,
'categories': LatestEntries,
}
urlpatterns = patterns('',
(r'^$', 'moviering.moviering.views.index'),
(r'profile/$', 'moviering.moviering.views.profile'),
#(r'newsletter/$', 'moviering.moviering.views.newsletter'),
(r'send_updates/$', 'moviering.moviering.views.send_updates'),
(r'actions/$', 'moviering.moviering.views.actions'),
(r'add/$', 'moviering.moviering.views.add'),
(r'add_many/$', 'moviering.moviering.views.add_many'),
(r'add_review/$', 'moviering.moviering.views.add_review'),
(r'^movie/(?P<movie_key>[^\.^/]+)/$', 'moviering.moviering.views.view'),
(r'^delete/(?P<movie_key>[^\.^/]+)/$', 'moviering.moviering.views.delete'),
(r'^update/(?P<movie_key>[^\.^/]+)/$', 'moviering.moviering.views.update'),
#(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': latest_feeds}),
(r'^by_status/(?P<status>[^\.^/]+)/$', 'moviering.moviering.views.by_status'),
(r'^by_media/(?P<media_type>[^\.^/]+)/$', 'moviering.moviering.views.by_media'),
(r'for_sale/$', 'moviering.moviering.views.for_sale'),
(r'^by_dude/(?P<dude_key>[^\.^/]+)/$', 'moviering.moviering.views.by_dude'),
(r'^by_group/(?P<group>[^\.^/]+)/$', 'moviering.moviering.views.by_group'),
(r'^buy/(?P<movie_key>[^\.^/]+)/$', 'moviering.moviering.views.buy'),
(r'^swap/(?P<movie_key>[^\.^/]+)/$', 'moviering.moviering.views.swap'),
(r'^borrow/(?P<movie_key>[^\.^/]+)/$', 'moviering.moviering.views.borrow'),
(r'^kudos/(?P<movie_key>[^\.^/]+)/$', 'moviering.moviering.views.kudos'),
(r'^by_genre/(?P<genre>[^\.^/]+)/$', 'moviering.moviering.views.by_genre'),
(r'users/$', 'moviering.moviering.views.list_users'),
(r'^grant_access/(?P<dude_key>[^\.^/]+)/$', 'moviering.moviering.views.grant_access'),
(r'^revoke_access/(?P<dude_key>[^\.^/]+)/$', 'moviering.moviering.views.revoke_access'),
(r'^set_unavailable/(?P<movie_key>[^\.^/]+)/$', 'moviering.moviering.views.set_unavailable'),
(r'wanted_movies/$', 'moviering.moviering.views.wanted_movies'),
(r'most_kodus/$', 'moviering.moviering.views.most_kodus'),
(r'blurays/$', 'moviering.moviering.views.blurays'),
(r'dvds/$', 'moviering.moviering.views.dvds'),
(r'by_rating/$', 'moviering.moviering.views.by_rating'),
(r'process_multiple/$', 'moviering.moviering.views.process_multiple'),
(r'give_rating/(?P<movie_key>\w+)/(?P<rating>\w+)/$', 'moviering.moviering.views.give_rating'),
(r'^delete_comment/(?P<comment_key>[^\.^/]+)/$', 'moviering.moviering.views.delete_comment'),
(r'^borrow_to/$', 'moviering.moviering.views.borrow_to'),
(r'^list_loans/$', 'moviering.moviering.views.list_loans'),
(r'^reviews/$', 'moviering.moviering.views.reviews'),
(r'^to_xml/$', 'moviering.moviering.views.to_xml'),
#(r'test/$', 'moviering.moviering.views.test'),
)
| Python |
from django.contrib.syndication.feeds import Feed
from moviering.views import get_movies
class LatestEntries(Feed):
title = "Movie Ring"
link = "/"
description = "Some movies."
def items(self):
return get_flicks()
| Python |
#!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
| Python |
from ragendja.settings_post import settings
settings.add_app_media('combined-%(LANGUAGE_CODE)s.js',
'myapp/code.js',
)
| Python |
# -*- coding: utf-8 -*-
from django.conf.urls.defaults import *
rootpatterns = patterns('',
(r'^person/', include('myapp.urls')),
)
| Python |
# -*- coding: utf-8 -*-
from django.db.models import permalink, signals
from google.appengine.ext import db
from ragendja.dbutils import cleanup_relations
class Person(db.Model):
"""Basic user profile with personal details."""
first_name = db.StringProperty(required=True)
last_name = db.StringProperty(required=True)
def __unicode__(self):
return '%s %s' % (self.first_name, self.last_name)
@permalink
def get_absolute_url(self):
return ('myapp.views.show_person', (), {'key': self.key()})
signals.pre_delete.connect(cleanup_relations, sender=Person)
class File(db.Model):
owner = db.ReferenceProperty(Person, required=True, collection_name='file_set')
name = db.StringProperty(required=True)
file = db.BlobProperty(required=True)
@permalink
def get_absolute_url(self):
return ('myapp.views.download_file', (), {'key': self.key(),
'name': self.name})
def __unicode__(self):
return u'File: %s' % self.name
class Contract(db.Model):
employer = db.ReferenceProperty(Person, required=True, collection_name='employee_contract_set')
employee = db.ReferenceProperty(Person, required=True, collection_name='employer_contract_set')
start_date = db.DateTimeProperty()
end_date = db.DateTimeProperty()
| Python |
# -*- coding: utf-8 -*-
from django import forms
from django.contrib.auth.models import User
from django.core.files.uploadedfile import UploadedFile
from django.utils.translation import ugettext_lazy as _, ugettext as __
from myapp.models import Person, File, Contract
from ragendja.auth.models import UserTraits
from ragendja.forms import FormWithSets, FormSetField
from registration.forms import RegistrationForm, RegistrationFormUniqueEmail
from registration.models import RegistrationProfile
class UserRegistrationForm(forms.ModelForm):
username = forms.RegexField(regex=r'^\w+$', max_length=30,
label=_(u'Username'))
email = forms.EmailField(widget=forms.TextInput(attrs=dict(maxlength=75)),
label=_(u'Email address'))
password1 = forms.CharField(widget=forms.PasswordInput(render_value=False),
label=_(u'Password'))
password2 = forms.CharField(widget=forms.PasswordInput(render_value=False),
label=_(u'Password (again)'))
def clean_username(self):
"""
Validate that the username is alphanumeric and is not already
in use.
"""
user = User.get_by_key_name("key_"+self.cleaned_data['username'].lower())
if user and user.is_active:
raise forms.ValidationError(__(u'This username is already taken. Please choose another.'))
return self.cleaned_data['username']
def clean(self):
"""
Verifiy that the values entered into the two password fields
match. Note that an error here will end up in
``non_field_errors()`` because it doesn't apply to a single
field.
"""
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError(__(u'You must type the same password each time'))
return self.cleaned_data
def save(self, domain_override=""):
"""
Create the new ``User`` and ``RegistrationProfile``, and
returns the ``User``.
This is essentially a light wrapper around
``RegistrationProfile.objects.create_inactive_user()``,
feeding it the form data and a profile callback (see the
documentation on ``create_inactive_user()`` for details) if
supplied.
"""
new_user = RegistrationProfile.objects.create_inactive_user(
username=self.cleaned_data['username'],
password=self.cleaned_data['password1'],
email=self.cleaned_data['email'],
domain_override=domain_override)
self.instance = new_user
return super(UserRegistrationForm, self).save()
def clean_email(self):
"""
Validate that the supplied email address is unique for the
site.
"""
email = self.cleaned_data['email'].lower()
if User.all().filter('email =', email).filter(
'is_active =', True).count(1):
raise forms.ValidationError(__(u'This email address is already in use. Please supply a different email address.'))
return email
class Meta:
model = User
exclude = UserTraits.properties().keys()
class FileForm(forms.ModelForm):
name = forms.CharField(required=False, label='Name (set automatically)')
def clean(self):
file = self.cleaned_data.get('file')
if not self.cleaned_data.get('name'):
if isinstance(file, UploadedFile):
self.cleaned_data['name'] = file.name
else:
del self.cleaned_data['name']
return self.cleaned_data
class Meta:
model = File
class PersonForm(forms.ModelForm):
files = FormSetField(File, form=FileForm, exclude='content_type')
employers = FormSetField(Contract, fk_name='employee')
employees = FormSetField(Contract, fk_name='employer')
class Meta:
model = Person
PersonForm = FormWithSets(PersonForm)
| Python |
# -*- coding: utf-8 -*-
from django.conf.urls.defaults import *
urlpatterns = patterns('myapp.views',
(r'^create_admin_user$', 'create_admin_user'),
(r'^$', 'list_people'),
(r'^create/$', 'add_person'),
(r'^show/(?P<key>.+)$', 'show_person'),
(r'^edit/(?P<key>.+)$', 'edit_person'),
(r'^delete/(?P<key>.+)$', 'delete_person'),
(r'^download/(?P<key>.+)/(?P<name>.+)$', 'download_file'),
)
| Python |
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.http import HttpResponse, Http404
from django.views.generic.list_detail import object_list, object_detail
from django.views.generic.create_update import create_object, delete_object, \
update_object
from google.appengine.ext import db
from mimetypes import guess_type
from myapp.forms import PersonForm
from myapp.models import Contract, File, Person
from ragendja.dbutils import get_object_or_404
from ragendja.template import render_to_response
def list_people(request):
return object_list(request, Person.all(), paginate_by=10)
def show_person(request, key):
return object_detail(request, Person.all(), key)
def add_person(request):
return create_object(request, form_class=PersonForm,
post_save_redirect=reverse('myapp.views.show_person',
kwargs=dict(key='%(key)s')))
def edit_person(request, key):
return update_object(request, object_id=key, form_class=PersonForm,
post_save_redirect=reverse('myapp.views.show_person',
kwargs=dict(key='%(key)s')))
def delete_person(request, key):
return delete_object(request, Person, object_id=key,
post_delete_redirect=reverse('myapp.views.list_people'))
def download_file(request, key, name):
file = get_object_or_404(File, key)
if file.name != name:
raise Http404('Could not find file with this name!')
return HttpResponse(file.file,
content_type=guess_type(file.name)[0] or 'application/octet-stream')
def create_admin_user(request):
user = User.get_by_key_name('admin')
if not user or user.username != 'admin' or not (user.is_active and
user.is_staff and user.is_superuser and
user.check_password('admin')):
user = User(key_name='admin', username='admin',
email='admin@localhost', first_name='Boss', last_name='Admin',
is_active=True, is_staff=True, is_superuser=True)
user.set_password('admin')
user.put()
return render_to_response(request, 'myapp/admin_created.html')
| Python |
from django.contrib import admin
from myapp.models import Person, File
class FileInline(admin.TabularInline):
model = File
class PersonAdmin(admin.ModelAdmin):
inlines = (FileInline,)
list_display = ('first_name', 'last_name')
admin.site.register(Person, PersonAdmin)
| Python |
#!/usr/bin/env python
if __name__ == '__main__':
from common.appenginepatch.aecmd import setup_env
setup_env(manage_py_env=True)
# Recompile translation files
from mediautils.compilemessages import updatemessages
updatemessages()
# Generate compressed media files for manage.py update
import sys
from mediautils.generatemedia import updatemedia
if len(sys.argv) >= 2 and sys.argv[1] == 'update':
updatemedia(True)
import settings
from django.core.management import execute_manager
execute_manager(settings)
| Python |
import os,sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'moviering.settings'
# Google App Engine imports.
from google.appengine.ext.webapp import util
# Force Django to reload its settings.
from django.conf import settings
settings._target = None
import django.core.handlers.wsgi
import django.core.signals
import django.db
import django.dispatch.dispatcher
# Log errors.
#django.dispatch.dispatcher.connect(
# log_exception, django.core.signals.got_request_exception)
# Unregister the rollback event handler.
django.dispatch.dispatcher.disconnect(
django.db._rollback_on_exception,
django.core.signals.got_request_exception)
def main():
# Create a Django application for WSGI.
application = django.core.handlers.wsgi.WSGIHandler()
# Run the WSGI CGI handler with that application.
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
| Python |
from ragendja.settings_post import settings
settings.add_app_media('combined-%(LANGUAGE_DIR)s.css',
'blueprintcss/reset.css',
'blueprintcss/typography.css',
'blueprintcss/forms.css',
'blueprintcss/grid.css',
'blueprintcss/lang-%(LANGUAGE_DIR)s.css',
)
settings.add_app_media('combined-print-%(LANGUAGE_DIR)s.css',
'blueprintcss/print.css',
)
settings.add_app_media('ie.css',
'blueprintcss/ie.css',
)
| Python |
# -*- coding: utf-8 -*-
from django.conf.urls.defaults import *
from ragendja.urlsauto import urlpatterns
from ragendja.auth.urls import urlpatterns as auth_patterns
from myapp.forms import UserRegistrationForm
from django.contrib import admin
admin.autodiscover()
handler500 = 'ragendja.views.server_error'
urlpatterns = auth_patterns + patterns('',
('^admin/(.*)', admin.site.root),
(r'^$', 'django.views.generic.simple.direct_to_template',
{'template': 'main.html'}),
# Override the default registration form
url(r'^account/register/$', 'registration.views.register',
kwargs={'form_class': UserRegistrationForm},
name='registration_register'),
) + urlpatterns
| Python |
from ragendja.settings_post import settings
if not hasattr(settings, 'ACCOUNT_ACTIVATION_DAYS'):
settings.ACCOUNT_ACTIVATION_DAYS = 30
| Python |
from django.conf.urls.defaults import *
rootpatterns = patterns('',
(r'^account/', include('registration.urls')),
)
| Python |
import datetime
import random
import re
import sha
from google.appengine.ext import db
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.db import models
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
SHA1_RE = re.compile('^[a-f0-9]{40}$')
class RegistrationManager(models.Manager):
"""
Custom manager for the ``RegistrationProfile`` model.
The methods defined here provide shortcuts for account creation
and activation (including generation and emailing of activation
keys), and for cleaning out expired inactive accounts.
"""
def activate_user(self, activation_key):
"""
Validate an activation key and activate the corresponding
``User`` if valid.
If the key is valid and has not expired, return the ``User``
after activating.
If the key is not valid or has expired, return ``False``.
If the key is valid but the ``User`` is already active,
return ``False``.
To prevent reactivation of an account which has been
deactivated by site administrators, the activation key is
reset to the string constant ``RegistrationProfile.ACTIVATED``
after successful activation.
To execute customized logic when a ``User`` is activated,
connect a function to the signal
``registration.signals.user_activated``; this signal will be
sent (with the ``User`` as the value of the keyword argument
``user``) after a successful activation.
"""
from registration.signals import user_activated
# Make sure the key we're trying conforms to the pattern of a
# SHA1 hash; if it doesn't, no point trying to look it up in
# the database.
if SHA1_RE.search(activation_key):
profile = RegistrationProfile.get_by_key_name("key_"+activation_key)
if not profile:
return False
if not profile.activation_key_expired():
user = profile.user
user.is_active = True
user.put()
profile.activation_key = RegistrationProfile.ACTIVATED
profile.put()
user_activated.send(sender=self.model, user=user)
return user
return False
def create_inactive_user(self, username, password, email, domain_override="",
send_email=True):
"""
Create a new, inactive ``User``, generate a
``RegistrationProfile`` and email its activation key to the
``User``, returning the new ``User``.
To disable the email, call with ``send_email=False``.
The activation email will make use of two templates:
``registration/activation_email_subject.txt``
This template will be used for the subject line of the
email. It receives one context variable, ``site``, which
is the currently-active
``django.contrib.sites.models.Site`` instance. Because it
is used as the subject line of an email, this template's
output **must** be only a single line of text; output
longer than one line will be forcibly joined into only a
single line.
``registration/activation_email.txt``
This template will be used for the body of the email. It
will receive three context variables: ``activation_key``
will be the user's activation key (for use in constructing
a URL to activate the account), ``expiration_days`` will
be the number of days for which the key will be valid and
``site`` will be the currently-active
``django.contrib.sites.models.Site`` instance.
To execute customized logic once the new ``User`` has been
created, connect a function to the signal
``registration.signals.user_registered``; this signal will be
sent (with the new ``User`` as the value of the keyword
argument ``user``) after the ``User`` and
``RegistrationProfile`` have been created, and the email (if
any) has been sent..
"""
from registration.signals import user_registered
# prepend "key_" to the key_name, because key_names can't start with numbers
new_user = User(username=username, key_name="key_"+username.lower(),
email=email, is_active=False)
new_user.set_password(password)
new_user.put()
registration_profile = self.create_profile(new_user)
if send_email:
from django.core.mail import send_mail
current_site = domain_override
# current_site = Site.objects.get_current()
subject = render_to_string('registration/activation_email_subject.txt',
{ 'site': current_site })
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
message = render_to_string('registration/activation_email.txt',
{ 'activation_key': registration_profile.activation_key,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
'site': current_site })
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user.email])
user_registered.send(sender=self.model, user=new_user)
return new_user
def create_profile(self, user):
"""
Create a ``RegistrationProfile`` for a given
``User``, and return the ``RegistrationProfile``.
The activation key for the ``RegistrationProfile`` will be a
SHA1 hash, generated from a combination of the ``User``'s
username and a random salt.
"""
salt = sha.new(str(random.random())).hexdigest()[:5]
activation_key = sha.new(salt+user.username).hexdigest()
# prepend "key_" to the key_name, because key_names can't start with numbers
registrationprofile = RegistrationProfile(user=user, activation_key=activation_key, key_name="key_"+activation_key)
registrationprofile.put()
return registrationprofile
def delete_expired_users(self):
"""
Remove expired instances of ``RegistrationProfile`` and their
associated ``User``s.
Accounts to be deleted are identified by searching for
instances of ``RegistrationProfile`` with expired activation
keys, and then checking to see if their associated ``User``
instances have the field ``is_active`` set to ``False``; any
``User`` who is both inactive and has an expired activation
key will be deleted.
It is recommended that this method be executed regularly as
part of your routine site maintenance; this application
provides a custom management command which will call this
method, accessible as ``manage.py cleanupregistration``.
Regularly clearing out accounts which have never been
activated serves two useful purposes:
1. It alleviates the ocasional need to reset a
``RegistrationProfile`` and/or re-send an activation email
when a user does not receive or does not act upon the
initial activation email; since the account will be
deleted, the user will be able to simply re-register and
receive a new activation key.
2. It prevents the possibility of a malicious user registering
one or more accounts and never activating them (thus
denying the use of those usernames to anyone else); since
those accounts will be deleted, the usernames will become
available for use again.
If you have a troublesome ``User`` and wish to disable their
account while keeping it in the database, simply delete the
associated ``RegistrationProfile``; an inactive ``User`` which
does not have an associated ``RegistrationProfile`` will not
be deleted.
"""
for profile in RegistrationProfile.all():
if profile.activation_key_expired():
user = profile.user
if not user.is_active:
user.delete()
profile.delete()
class RegistrationProfile(db.Model):
"""
A simple profile which stores an activation key for use during
user account registration.
Generally, you will not want to interact directly with instances
of this model; the provided manager includes methods
for creating and activating new accounts, as well as for cleaning
out accounts which have never been activated.
While it is possible to use this model as the value of the
``AUTH_PROFILE_MODULE`` setting, it's not recommended that you do
so. This model's sole purpose is to store data temporarily during
account registration and activation.
"""
ACTIVATED = u"ALREADY_ACTIVATED"
user = db.ReferenceProperty(User, verbose_name=_('user'))
activation_key = db.StringProperty(_('activation key'))
objects = RegistrationManager()
class Meta:
verbose_name = _('registration profile')
verbose_name_plural = _('registration profiles')
def __unicode__(self):
return u"Registration information for %s" % self.user
def activation_key_expired(self):
"""
Determine whether this ``RegistrationProfile``'s activation
key has expired, returning a boolean -- ``True`` if the key
has expired.
Key expiration is determined by a two-step process:
1. If the user has already activated, the key will have been
reset to the string constant ``ACTIVATED``. Re-activating
is not permitted, and so this method returns ``True`` in
this case.
2. Otherwise, the date the user signed up is incremented by
the number of days specified in the setting
``ACCOUNT_ACTIVATION_DAYS`` (which should be the number of
days after signup during which a user is allowed to
activate their account); if the result is less than or
equal to the current date, the key has expired and this
method returns ``True``.
"""
expiration_date = datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)
return self.activation_key == RegistrationProfile.ACTIVATED or \
(self.user.date_joined + expiration_date <= datetime.datetime.now())
activation_key_expired.boolean = True
| Python |
"""
Forms and validation code for user registration.
"""
from django.contrib.auth.models import User
from django import forms
from django.utils.translation import ugettext_lazy as _
from registration.models import RegistrationProfile
# I put this on all required fields, because it's easier to pick up
# on them with CSS or JavaScript if they have a class of "required"
# in the HTML. Your mileage may vary. If/when Django ticket #3515
# lands in trunk, this will no longer be necessary.
attrs_dict = { 'class': 'required' }
class RegistrationForm(forms.Form):
"""
Form for registering a new user account.
Validates that the requested username is not already in use, and
requires the password to be entered twice to catch typos.
Subclasses should feel free to add any additional validation they
need, but should either preserve the base ``save()`` or implement
a ``save()`` method which returns a ``User``.
"""
username = forms.RegexField(regex=r'^\w+$',
max_length=30,
widget=forms.TextInput(attrs=attrs_dict),
label=_(u'username'))
email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,
maxlength=75)),
label=_(u'email address'))
password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
label=_(u'password'))
password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
label=_(u'password (again)'))
def clean_username(self):
"""
Validate that the username is alphanumeric and is not already
in use.
"""
user = User.get_by_key_name("key_"+self.cleaned_data['username'].lower())
if user:
raise forms.ValidationError(_(u'This username is already taken. Please choose another.'))
return self.cleaned_data['username']
def clean(self):
"""
Verifiy that the values entered into the two password fields
match. Note that an error here will end up in
``non_field_errors()`` because it doesn't apply to a single
field.
"""
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError(_(u'You must type the same password each time'))
return self.cleaned_data
def save(self, domain_override=""):
"""
Create the new ``User`` and ``RegistrationProfile``, and
returns the ``User`` (by calling
``RegistrationProfile.objects.create_inactive_user()``).
"""
new_user = RegistrationProfile.objects.create_inactive_user(username=self.cleaned_data['username'],
password=self.cleaned_data['password1'],
email=self.cleaned_data['email'],
domain_override=domain_override,
)
return new_user
class RegistrationFormTermsOfService(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which adds a required checkbox
for agreeing to a site's Terms of Service.
"""
tos = forms.BooleanField(widget=forms.CheckboxInput(attrs=attrs_dict),
label=_(u'I have read and agree to the Terms of Service'),
error_messages={ 'required': u"You must agree to the terms to register" })
class RegistrationFormUniqueEmail(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which enforces uniqueness of
email addresses.
"""
def clean_email(self):
"""
Validate that the supplied email address is unique for the
site.
"""
email = self.cleaned_data['email'].lower()
if User.all().filter('email =', email).count(1):
raise forms.ValidationError(_(u'This email address is already in use. Please supply a different email address.'))
return email
class RegistrationFormNoFreeEmail(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which disallows registration with
email addresses from popular free webmail services; moderately
useful for preventing automated spam registrations.
To change the list of banned domains, subclass this form and
override the attribute ``bad_domains``.
"""
bad_domains = ['aim.com', 'aol.com', 'email.com', 'gmail.com',
'googlemail.com', 'hotmail.com', 'hushmail.com',
'msn.com', 'mail.ru', 'mailinator.com', 'live.com']
def clean_email(self):
"""
Check the supplied email address against a list of known free
webmail domains.
"""
email_domain = self.cleaned_data['email'].split('@')[1]
if email_domain in self.bad_domains:
raise forms.ValidationError(_(u'Registration using free email addresses is prohibited. Please supply a different email address.'))
return self.cleaned_data['email']
| Python |
"""
Unit tests for django-registration.
These tests assume that you've completed all the prerequisites for
getting django-registration running in the default setup, to wit:
1. You have ``registration`` in your ``INSTALLED_APPS`` setting.
2. You have created all of the templates mentioned in this
application's documentation.
3. You have added the setting ``ACCOUNT_ACTIVATION_DAYS`` to your
settings file.
4. You have URL patterns pointing to the registration and activation
views, with the names ``registration_register`` and
``registration_activate``, respectively, and a URL pattern named
'registration_complete'.
"""
import datetime
import sha
from django.conf import settings
from django.contrib.auth.models import User
from django.core import mail
from django.core import management
from django.core.urlresolvers import reverse
from django.test import TestCase
from google.appengine.ext import db
from registration import forms
from registration.models import RegistrationProfile
from registration import signals
class RegistrationTestCase(TestCase):
"""
Base class for the test cases; this sets up two users -- one
expired, one not -- which are used to exercise various parts of
the application.
"""
def setUp(self):
self.sample_user = RegistrationProfile.objects.create_inactive_user(username='alice',
password='secret',
email='alice@example.com')
self.expired_user = RegistrationProfile.objects.create_inactive_user(username='bob',
password='swordfish',
email='bob@example.com')
self.expired_user.date_joined -= datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS + 1)
self.expired_user.save()
class RegistrationModelTests(RegistrationTestCase):
"""
Tests for the model-oriented functionality of django-registration,
including ``RegistrationProfile`` and its custom manager.
"""
def test_new_user_is_inactive(self):
"""
Test that a newly-created user is inactive.
"""
self.failIf(self.sample_user.is_active)
def test_registration_profile_created(self):
"""
Test that a ``RegistrationProfile`` is created for a new user.
"""
self.assertEqual(RegistrationProfile.all().count(), 2)
def test_activation_email(self):
"""
Test that user signup sends an activation email.
"""
self.assertEqual(len(mail.outbox), 2)
def test_activation_email_disable(self):
"""
Test that activation email can be disabled.
"""
RegistrationProfile.objects.create_inactive_user(username='noemail',
password='foo',
email='nobody@example.com',
send_email=False)
self.assertEqual(len(mail.outbox), 2)
def test_activation(self):
"""
Test that user activation actually activates the user and
properly resets the activation key, and fails for an
already-active or expired user, or an invalid key.
"""
# Activating a valid user returns the user.
self.failUnlessEqual(RegistrationProfile.objects.activate_user(RegistrationProfile.all().filter('user =', self.sample_user).get().activation_key).key(),
self.sample_user.key())
# The activated user must now be active.
self.failUnless(User.get(self.sample_user.key()).is_active)
# The activation key must now be reset to the "already activated" constant.
self.failUnlessEqual(RegistrationProfile.all().filter('user =', self.sample_user).get().activation_key,
RegistrationProfile.ACTIVATED)
# Activating an expired user returns False.
self.failIf(RegistrationProfile.objects.activate_user(RegistrationProfile.all().filter('user =', self.expired_user).get().activation_key))
# Activating from a key that isn't a SHA1 hash returns False.
self.failIf(RegistrationProfile.objects.activate_user('foo'))
# Activating from a key that doesn't exist returns False.
self.failIf(RegistrationProfile.objects.activate_user(sha.new('foo').hexdigest()))
def test_account_expiration_condition(self):
"""
Test that ``RegistrationProfile.activation_key_expired()``
returns ``True`` for expired users and for active users, and
``False`` otherwise.
"""
# Unexpired user returns False.
self.failIf(RegistrationProfile.all().filter('user =', self.sample_user).get().activation_key_expired())
# Expired user returns True.
self.failUnless(RegistrationProfile.all().filter('user =', self.expired_user).get().activation_key_expired())
# Activated user returns True.
RegistrationProfile.objects.activate_user(RegistrationProfile.all().filter('user =', self.sample_user).get().activation_key)
self.failUnless(RegistrationProfile.all().filter('user =', self.sample_user).get().activation_key_expired())
def test_expired_user_deletion(self):
"""
Test that
``RegistrationProfile.objects.delete_expired_users()`` deletes
only inactive users whose activation window has expired.
"""
RegistrationProfile.objects.delete_expired_users()
self.assertEqual(RegistrationProfile.all().count(), 1)
def test_management_command(self):
"""
Test that ``manage.py cleanupregistration`` functions
correctly.
"""
management.call_command('cleanupregistration')
self.assertEqual(RegistrationProfile.all().count(), 1)
def test_signals(self):
"""
Test that the ``user_registered`` and ``user_activated``
signals are sent, and that they send the ``User`` as an
argument.
"""
def receiver(sender, **kwargs):
self.assert_('user' in kwargs)
self.assertEqual(kwargs['user'].username, u'signal_test')
received_signals.append(kwargs.get('signal'))
received_signals = []
expected_signals = [signals.user_registered, signals.user_activated]
for signal in expected_signals:
signal.connect(receiver)
RegistrationProfile.objects.create_inactive_user(username='signal_test',
password='foo',
email='nobody@example.com',
send_email=False)
RegistrationProfile.objects.activate_user(RegistrationProfile.all().filter('user =', db.Key.from_path(User.kind(), 'key_signal_test')).get().activation_key)
self.assertEqual(received_signals, expected_signals)
class RegistrationFormTests(RegistrationTestCase):
"""
Tests for the forms and custom validation logic included in
django-registration.
"""
def test_registration_form(self):
"""
Test that ``RegistrationForm`` enforces username constraints
and matching passwords.
"""
invalid_data_dicts = [
# Non-alphanumeric username.
{
'data':
{ 'username': 'foo/bar',
'email': 'foo@example.com',
'password1': 'foo',
'password2': 'foo' },
'error':
('username', [u"Enter a valid value."])
},
# Already-existing username.
{
'data':
{ 'username': 'alice',
'email': 'alice@example.com',
'password1': 'secret',
'password2': 'secret' },
'error':
('username', [u"This username is already taken. Please choose another."])
},
# Mismatched passwords.
{
'data':
{ 'username': 'foo',
'email': 'foo@example.com',
'password1': 'foo',
'password2': 'bar' },
'error':
('__all__', [u"You must type the same password each time"])
},
]
for invalid_dict in invalid_data_dicts:
form = forms.RegistrationForm(data=invalid_dict['data'])
self.failIf(form.is_valid())
self.assertEqual(form.errors[invalid_dict['error'][0]], invalid_dict['error'][1])
form = forms.RegistrationForm(data={ 'username': 'foo',
'email': 'foo@example.com',
'password1': 'foo',
'password2': 'foo' })
self.failUnless(form.is_valid())
def test_registration_form_tos(self):
"""
Test that ``RegistrationFormTermsOfService`` requires
agreement to the terms of service.
"""
form = forms.RegistrationFormTermsOfService(data={ 'username': 'foo',
'email': 'foo@example.com',
'password1': 'foo',
'password2': 'foo' })
self.failIf(form.is_valid())
self.assertEqual(form.errors['tos'], [u"You must agree to the terms to register"])
form = forms.RegistrationFormTermsOfService(data={ 'username': 'foo',
'email': 'foo@example.com',
'password1': 'foo',
'password2': 'foo',
'tos': 'on' })
self.failUnless(form.is_valid())
def test_registration_form_unique_email(self):
"""
Test that ``RegistrationFormUniqueEmail`` validates uniqueness
of email addresses.
"""
form = forms.RegistrationFormUniqueEmail(data={ 'username': 'foo',
'email': 'alice@example.com',
'password1': 'foo',
'password2': 'foo' })
self.failIf(form.is_valid())
self.assertEqual(form.errors['email'], [u"This email address is already in use. Please supply a different email address."])
form = forms.RegistrationFormUniqueEmail(data={ 'username': 'foo',
'email': 'foo@example.com',
'password1': 'foo',
'password2': 'foo' })
self.failUnless(form.is_valid())
def test_registration_form_no_free_email(self):
"""
Test that ``RegistrationFormNoFreeEmail`` disallows
registration with free email addresses.
"""
base_data = { 'username': 'foo',
'password1': 'foo',
'password2': 'foo' }
for domain in ('aim.com', 'aol.com', 'email.com', 'gmail.com',
'googlemail.com', 'hotmail.com', 'hushmail.com',
'msn.com', 'mail.ru', 'mailinator.com', 'live.com'):
invalid_data = base_data.copy()
invalid_data['email'] = u"foo@%s" % domain
form = forms.RegistrationFormNoFreeEmail(data=invalid_data)
self.failIf(form.is_valid())
self.assertEqual(form.errors['email'], [u"Registration using free email addresses is prohibited. Please supply a different email address."])
base_data['email'] = 'foo@example.com'
form = forms.RegistrationFormNoFreeEmail(data=base_data)
self.failUnless(form.is_valid())
class RegistrationViewTests(RegistrationTestCase):
"""
Tests for the views included in django-registration.
"""
def test_registration_view(self):
"""
Test that the registration view rejects invalid submissions,
and creates a new user and redirects after a valid submission.
"""
# Invalid data fails.
alice = User.all().filter('username =', 'alice').get()
alice.is_active = True
alice.put()
response = self.client.post(reverse('registration_register'),
data={ 'username': 'alice', # Will fail on username uniqueness.
'email': 'foo@example.com',
'password1': 'foo',
'password2': 'foo' })
self.assertEqual(response.status_code, 200)
self.failUnless(response.context[0]['form'])
self.failUnless(response.context[0]['form'].errors)
response = self.client.post(reverse('registration_register'),
data={ 'username': 'foo',
'email': 'foo@example.com',
'password1': 'foo',
'password2': 'foo' })
self.assertEqual(response.status_code, 302)
self.assertEqual(response['Location'], 'http://testserver%s' % reverse('registration_complete'))
self.assertEqual(RegistrationProfile.all().count(), 3)
def test_activation_view(self):
"""
Test that the activation view activates the user from a valid
key and fails if the key is invalid or has expired.
"""
# Valid user puts the user account into the context.
response = self.client.get(reverse('registration_activate',
kwargs={ 'activation_key': RegistrationProfile.all().filter('user =', self.sample_user).get().activation_key }))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context[0]['account'].key(), self.sample_user.key())
# Expired user sets the account to False.
response = self.client.get(reverse('registration_activate',
kwargs={ 'activation_key': RegistrationProfile.all().filter('user =', self.expired_user).get().activation_key }))
self.failIf(response.context[0]['account'])
# Invalid key gets to the view, but sets account to False.
response = self.client.get(reverse('registration_activate',
kwargs={ 'activation_key': 'foo' }))
self.failIf(response.context[0]['account'])
# Nonexistent key sets the account to False.
response = self.client.get(reverse('registration_activate',
kwargs={ 'activation_key': sha.new('foo').hexdigest() }))
self.failIf(response.context[0]['account'])
| Python |
"""
URLConf for Django user registration and authentication.
If the default behavior of the registration views is acceptable to
you, simply use a line like this in your root URLConf to set up the
default URLs for registration::
(r'^accounts/', include('registration.urls')),
This will also automatically set up the views in
``django.contrib.auth`` at sensible default locations.
But if you'd like to customize the behavior (e.g., by passing extra
arguments to the various views) or split up the URLs, feel free to set
up your own URL patterns for these views instead. If you do, it's a
good idea to use the names ``registration_activate``,
``registration_complete`` and ``registration_register`` for the
various steps of the user-signup process.
"""
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from django.contrib.auth import views as auth_views
from registration.views import activate
from registration.views import register
urlpatterns = patterns('',
# Activation keys get matched by \w+ instead of the more specific
# [a-fA-F0-9]{40} because a bad activation key should still get to the view;
# that way it can return a sensible "invalid key" message instead of a
# confusing 404.
url(r'^activate/(?P<activation_key>\w+)/$',
activate,
name='registration_activate'),
url(r'^login/$',
auth_views.login,
{'template_name': 'registration/login.html'},
name='auth_login'),
url(r'^logout/$',
auth_views.logout,
name='auth_logout'),
url(r'^password/change/$',
auth_views.password_change,
name='auth_password_change'),
url(r'^password/change/done/$',
auth_views.password_change_done,
name='auth_password_change_done'),
url(r'^password/reset/$',
auth_views.password_reset,
name='auth_password_reset'),
url(r'^password/reset/confirm/(?P<uidb36>.+)/(?P<token>.+)/$',
auth_views.password_reset_confirm,
name='auth_password_reset_confirm'),
url(r'^password/reset/complete/$',
auth_views.password_reset_complete,
name='auth_password_reset_complete'),
url(r'^password/reset/done/$',
auth_views.password_reset_done,
name='auth_password_reset_done'),
url(r'^register/$',
register,
name='registration_register'),
url(r'^register/complete/$',
direct_to_template,
{'template': 'registration/registration_complete.html'},
name='registration_complete'),
)
| Python |
"""
A management command which deletes expired accounts (e.g.,
accounts which signed up but never activated) from the database.
Calls ``RegistrationProfile.objects.delete_expired_users()``, which
contains the actual logic for determining which accounts are deleted.
"""
from django.core.management.base import NoArgsCommand
from registration.models import RegistrationProfile
class Command(NoArgsCommand):
help = "Delete expired user registrations from the database"
def handle_noargs(self, **options):
RegistrationProfile.objects.delete_expired_users()
| Python |
"""
Views which allow users to create and activate accounts.
"""
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from registration.forms import RegistrationForm
from registration.models import RegistrationProfile
def activate(request, activation_key,
template_name='registration/activate.html',
extra_context=None):
"""
Activate a ``User``'s account from an activation key, if their key
is valid and hasn't expired.
By default, use the template ``registration/activate.html``; to
change this, pass the name of a template as the keyword argument
``template_name``.
**Required arguments**
``activation_key``
The activation key to validate and use for activating the
``User``.
**Optional arguments**
``extra_context``
A dictionary of variables to add to the template context. Any
callable object in this dictionary will be called to produce
the end result which appears in the context.
``template_name``
A custom template to use.
**Context:**
``account``
The ``User`` object corresponding to the account, if the
activation was successful. ``False`` if the activation was not
successful.
``expiration_days``
The number of days for which activation keys stay valid after
registration.
Any extra variables supplied in the ``extra_context`` argument
(see above).
**Template:**
registration/activate.html or ``template_name`` keyword argument.
"""
activation_key = activation_key.lower() # Normalize before trying anything with it.
account = RegistrationProfile.objects.activate_user(activation_key)
if extra_context is None:
extra_context = {}
context = RequestContext(request)
for key, value in extra_context.items():
context[key] = callable(value) and value() or value
return render_to_response(template_name,
{ 'account': account,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS },
context_instance=context)
def register(request, success_url=None,
form_class=RegistrationForm,
template_name='registration/registration_form.html',
extra_context=None):
"""
Allow a new user to register an account.
Following successful registration, issue a redirect; by default,
this will be whatever URL corresponds to the named URL pattern
``registration_complete``, which will be
``/accounts/register/complete/`` if using the included URLConf. To
change this, point that named pattern at another URL, or pass your
preferred URL as the keyword argument ``success_url``.
By default, ``registration.forms.RegistrationForm`` will be used
as the registration form; to change this, pass a different form
class as the ``form_class`` keyword argument. The form class you
specify must have a method ``save`` which will create and return
the new ``User``.
By default, use the template
``registration/registration_form.html``; to change this, pass the
name of a template as the keyword argument ``template_name``.
**Required arguments**
None.
**Optional arguments**
``form_class``
The form class to use for registration.
``extra_context``
A dictionary of variables to add to the template context. Any
callable object in this dictionary will be called to produce
the end result which appears in the context.
``success_url``
The URL to redirect to on successful registration.
``template_name``
A custom template to use.
**Context:**
``form``
The registration form.
Any extra variables supplied in the ``extra_context`` argument
(see above).
**Template:**
registration/registration_form.html or ``template_name`` keyword
argument.
"""
if request.method == 'POST':
form = form_class(data=request.POST, files=request.FILES)
domain_override = request.get_host()
if form.is_valid():
new_user = form.save(domain_override)
# success_url needs to be dynamically generated here; setting a
# a default value using reverse() will cause circular-import
# problems with the default URLConf for this application, which
# imports this file.
return HttpResponseRedirect(success_url or reverse('registration_complete'))
else:
form = form_class()
if extra_context is None:
extra_context = {}
context = RequestContext(request)
for key, value in extra_context.items():
context[key] = callable(value) and value() or value
return render_to_response(template_name,
{ 'form': form },
context_instance=context)
| Python |
from django.contrib import admin
from registration.models import RegistrationProfile
class RegistrationAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'activation_key_expired')
search_fields = ('user__username', 'user__first_name')
admin.site.register(RegistrationProfile, RegistrationAdmin)
| Python |
from django.dispatch import Signal
# A new user has registered.
user_registered = Signal(providing_args=["user"])
# A user has activated his or her account.
user_activated = Signal(providing_args=["user"])
| Python |
import multiprocessing
| Python |
# -*- coding: utf-8 -*-
import os, sys
COMMON_DIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
PROJECT_DIR = os.path.dirname(COMMON_DIR)
ZIP_PACKAGES_DIRS = (os.path.join(PROJECT_DIR, 'zip-packages'),
os.path.join(COMMON_DIR, 'zip-packages'))
# Overrides for os.environ
env_ext = {'DJANGO_SETTINGS_MODULE': 'settings'}
def setup_env(manage_py_env=False):
"""Configures app engine environment for command-line apps."""
# Try to import the appengine code from the system path.
try:
from google.appengine.api import apiproxy_stub_map
except ImportError, e:
for k in [k for k in sys.modules if k.startswith('google')]:
del sys.modules[k]
# Not on the system path. Build a list of alternative paths where it
# may be. First look within the project for a local copy, then look for
# where the Mac OS SDK installs it.
paths = [os.path.join(COMMON_DIR, '.google_appengine'),
'/usr/local/google_appengine',
'/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine']
for path in os.environ.get('PATH', '').replace(';', ':').split(':'):
path = path.rstrip(os.sep)
if path.endswith('google_appengine'):
paths.append(path)
if os.name in ('nt', 'dos'):
prefix = '%(PROGRAMFILES)s' % os.environ
paths.append(prefix + r'\Google\google_appengine')
# Loop through all possible paths and look for the SDK dir.
SDK_PATH = None
for sdk_path in paths:
sdk_path = os.path.realpath(sdk_path)
if os.path.exists(sdk_path):
SDK_PATH = sdk_path
break
if SDK_PATH is None:
# The SDK could not be found in any known location.
sys.stderr.write('The Google App Engine SDK could not be found!\n'
'Visit http://code.google.com/p/app-engine-patch/'
' for installation instructions.\n')
sys.exit(1)
# Add the SDK and the libraries within it to the system path.
EXTRA_PATHS = [SDK_PATH]
lib = os.path.join(SDK_PATH, 'lib')
# Automatically add all packages in the SDK's lib folder:
for dir in os.listdir(lib):
path = os.path.join(lib, dir)
# Package can be under 'lib/<pkg>/<pkg>/' or 'lib/<pkg>/lib/<pkg>/'
detect = (os.path.join(path, dir), os.path.join(path, 'lib', dir))
for path in detect:
if os.path.isdir(path):
EXTRA_PATHS.append(os.path.dirname(path))
break
sys.path = EXTRA_PATHS + sys.path
from google.appengine.api import apiproxy_stub_map
# Add this folder to sys.path
sys.path = [os.path.abspath(os.path.dirname(__file__))] + sys.path
setup_project()
from appenginepatcher.patch import patch_all
patch_all()
if not manage_py_env:
return
print >> sys.stderr, 'Running on app-engine-patch 1.1'
def setup_project():
from appenginepatcher import on_production_server
if on_production_server:
# This fixes a pwd import bug for os.path.expanduser()
global env_ext
env_ext['HOME'] = PROJECT_DIR
os.environ.update(env_ext)
# Add the two parent folders and appenginepatcher's lib folder to sys.path.
# The current folder has to be added in main.py or setup_env(). This
# suggests a folder structure where you separate reusable code from project
# code:
# project -> common -> appenginepatch
# You can put a custom Django version into the "common" folder, for example.
EXTRA_PATHS = [
PROJECT_DIR,
COMMON_DIR,
]
this_folder = os.path.abspath(os.path.dirname(__file__))
EXTRA_PATHS.append(os.path.join(this_folder, 'appenginepatcher', 'lib'))
# We support zipped packages in the common and project folders.
# The files must be in the packages folder.
for packages_dir in ZIP_PACKAGES_DIRS:
if os.path.isdir(packages_dir):
for zip_package in os.listdir(packages_dir):
EXTRA_PATHS.append(os.path.join(packages_dir, zip_package))
# App Engine causes main.py to be reloaded if an exception gets raised
# on the first request of a main.py instance, so don't call setup_project()
# multiple times. We ensure this indirectly by checking if we've already
# modified sys.path.
if len(sys.path) < len(EXTRA_PATHS) or \
sys.path[:len(EXTRA_PATHS)] != EXTRA_PATHS:
# Remove the standard version of Django
for k in [k for k in sys.modules if k.startswith('django')]:
del sys.modules[k]
sys.path = EXTRA_PATHS + sys.path
| Python |
#!/usr/bin/env python
if __name__ == '__main__':
from common.appenginepatch.aecmd import setup_env
setup_env(manage_py_env=True)
# Recompile translation files
from mediautils.compilemessages import updatemessages
updatemessages()
# Generate compressed media files for manage.py update
import sys
from mediautils.generatemedia import updatemedia
if len(sys.argv) >= 2 and sys.argv[1] == 'update':
updatemedia(True)
import settings
from django.core.management import execute_manager
execute_manager(settings)
| Python |
# -*- coding: utf-8 -*-
import os, sys
# Add current folder to sys.path, so we can import aecmd.
# App Engine causes main.py to be reloaded if an exception gets raised
# on the first request of a main.py instance, so don't add current_dir multiple
# times.
current_dir = os.path.abspath(os.path.dirname(__file__))
if current_dir not in sys.path:
sys.path = [current_dir] + sys.path
import aecmd
aecmd.setup_project()
from appenginepatcher.patch import patch_all, setup_logging
patch_all()
import django.core.handlers.wsgi
from google.appengine.ext.webapp import util
from django.conf import settings
def real_main():
# Reset path and environment variables
global path_backup
try:
sys.path = path_backup[:]
except:
path_backup = sys.path[:]
os.environ.update(aecmd.env_ext)
setup_logging()
# Create a Django application for WSGI.
application = django.core.handlers.wsgi.WSGIHandler()
# Run the WSGI CGI handler with that application.
util.run_wsgi_app(application)
def profile_main():
import logging, cProfile, pstats, random, StringIO
only_forced_profile = getattr(settings, 'ONLY_FORCED_PROFILE', False)
profile_percentage = getattr(settings, 'PROFILE_PERCENTAGE', None)
if (only_forced_profile and
'profile=forced' not in os.environ.get('QUERY_STRING')) or \
(not only_forced_profile and profile_percentage and
float(profile_percentage) / 100.0 <= random.random()):
return real_main()
prof = cProfile.Profile()
prof = prof.runctx('real_main()', globals(), locals())
stream = StringIO.StringIO()
stats = pstats.Stats(prof, stream=stream)
sort_by = getattr(settings, 'SORT_PROFILE_RESULTS_BY', 'time')
if not isinstance(sort_by, (list, tuple)):
sort_by = (sort_by,)
stats.sort_stats(*sort_by)
restrictions = []
profile_pattern = getattr(settings, 'PROFILE_PATTERN', None)
if profile_pattern:
restrictions.append(profile_pattern)
max_results = getattr(settings, 'MAX_PROFILE_RESULTS', 80)
if max_results and max_results != 'all':
restrictions.append(max_results)
stats.print_stats(*restrictions)
extra_output = getattr(settings, 'EXTRA_PROFILE_OUTPUT', None) or ()
if not isinstance(sort_by, (list, tuple)):
extra_output = (extra_output,)
if 'callees' in extra_output:
stats.print_callees()
if 'callers' in extra_output:
stats.print_callers()
logging.info('Profile data:\n%s', stream.getvalue())
main = getattr(settings, 'ENABLE_PROFILER', False) and profile_main or real_main
if __name__ == '__main__':
main()
| Python |
# Empty file neeed to make this a Django app.
| Python |
#!/usr/bin/python2.4
#
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This file acts as a very minimal replacement for the 'imp' module.
It contains only what Django expects to use and does not actually implement the
same functionality as the real 'imp' module.
"""
def find_module(name, path=None):
"""Django needs imp.find_module, but it works fine if nothing is found."""
raise ImportError
| Python |
# -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from google.appengine.ext import db
| Python |
# -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext as _
from ragendja.template import render_to_response
| Python |
#!/usr/bin/python2.4
#
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This file acts as a very minimal replacement for the 'imp' module.
It contains only what Django expects to use and does not actually implement the
same functionality as the real 'imp' module.
"""
def find_module(name, path=None):
"""Django needs imp.find_module, but it works fine if nothing is found."""
raise ImportError
| Python |
# -*- coding: utf-8 -*-
from django.db.models import signals
from django.test import TestCase
from ragendja.dbutils import cleanup_relations
from ragendja.testutils import ModelTestCase
from google.appengine.ext import db
from google.appengine.ext.db.polymodel import PolyModel
from datetime import datetime
# Test class Meta
class TestA(db.Model):
class Meta:
abstract = True
verbose_name = 'aaa'
class TestB(TestA):
class Meta:
verbose_name = 'bbb'
class TestC(TestA):
pass
class TestModelRel(db.Model):
modelrel = db.ReferenceProperty(db.Model)
class PolyA(PolyModel):
class Meta:
verbose_name = 'polyb'
class PolyB(PolyA):
pass
class ModelMetaTest(TestCase):
def test_class_meta(self):
self.assertEqual(TestA._meta.verbose_name_plural, 'aaas')
self.assertTrue(TestA._meta.abstract)
self.assertEqual(TestB._meta.verbose_name_plural, 'bbbs')
self.assertFalse(TestB._meta.abstract)
self.assertEqual(TestC._meta.verbose_name_plural, 'test cs')
self.assertFalse(TestC._meta.abstract)
self.assertFalse(PolyA._meta.abstract)
self.assertFalse(PolyB._meta.abstract)
# Test signals
class SignalTest(TestCase):
def test_signals(self):
global received_pre_delete
global received_post_save
received_pre_delete = False
received_post_save = False
def handle_pre_delete(**kwargs):
global received_pre_delete
received_pre_delete = True
signals.pre_delete.connect(handle_pre_delete, sender=TestC)
def handle_post_save(**kwargs):
global received_post_save
received_post_save = True
signals.post_save.connect(handle_post_save, sender=TestC)
a = TestC()
a.put()
a.delete()
self.assertTrue(received_pre_delete)
self.assertTrue(received_post_save)
def test_batch_signals(self):
global received_pre_delete
global received_post_save
received_pre_delete = False
received_post_save = False
def handle_pre_delete(**kwargs):
global received_pre_delete
received_pre_delete = True
signals.pre_delete.connect(handle_pre_delete, sender=TestC)
def handle_post_save(**kwargs):
global received_post_save
received_post_save = True
signals.post_save.connect(handle_post_save, sender=TestC)
a = TestC()
db.put([a])
db.delete([a])
self.assertTrue(received_pre_delete)
self.assertTrue(received_post_save)
# Test serialization
class SerializeModel(db.Model):
name = db.StringProperty()
count = db.IntegerProperty()
created = db.DateTimeProperty()
class SerializerTest(ModelTestCase):
model = SerializeModel
def test_serializer(self, format='json'):
from django.core import serializers
created = datetime.now()
x = SerializeModel(key_name='blue_key', name='blue', count=4)
x.put()
SerializeModel(name='green', count=1, created=created).put()
data = serializers.serialize(format, SerializeModel.all())
db.delete(SerializeModel.all().fetch(100))
for obj in serializers.deserialize(format, data):
obj.save()
self.validate_state(
('key.name', 'name', 'count', 'created'),
(None, 'green', 1, created),
('blue_key', 'blue', 4, None),
)
def test_xml_serializer(self):
self.test_serializer(format='xml')
def test_python_serializer(self):
self.test_serializer(format='python')
def test_yaml_serializer(self):
self.test_serializer(format='yaml')
# Test ragendja cleanup handler
class SigChild(db.Model):
CLEANUP_REFERENCES = 'rel'
owner = db.ReferenceProperty(TestC)
rel = db.ReferenceProperty(TestC, collection_name='sigchildrel_set')
class RelationsCleanupTest(TestCase):
def test_cleanup(self):
signals.pre_delete.connect(cleanup_relations, sender=TestC)
c1 = TestC()
c2 = TestC()
db.put((c1, c2))
TestModelRel(modelrel=c1).put()
child = SigChild(owner=c1, rel=c2)
child.put()
self.assertEqual(TestC.all().count(), 2)
self.assertEqual(SigChild.all().count(), 1)
self.assertEqual(TestModelRel.all().count(), 1)
c1.delete()
signals.pre_delete.disconnect(cleanup_relations, sender=TestC)
self.assertEqual(SigChild.all().count(), 0)
self.assertEqual(TestC.all().count(), 0)
self.assertEqual(TestModelRel.all().count(), 0)
from ragendja.dbutils import FakeModel, FakeModelProperty, \
FakeModelListProperty
class FM(db.Model):
data = FakeModelProperty(FakeModel, indexed=False)
class FML(db.Model):
data = FakeModelListProperty(FakeModel, indexed=False)
# Test FakeModel, FakeModelProperty, FakeModelListProperty
class RelationsCleanupTest(TestCase):
def test_fake_model_property(self):
value = {'bla': [1, 2, {'blub': 'bla'*1000}]}
FM(data=FakeModel(value=value)).put()
self.assertEqual(FM.all()[0].data.value, value)
def test_fake_model_list_property(self):
value = {'bla': [1, 2, {'blub': 'bla'*1000}]}
FML(data=[FakeModel(value=value)]).put()
self.assertEqual(FML.all()[0].data[0].value, value)
| Python |
# -*- coding: utf-8 -*-
# Unfortunately, we have to fix a few App Engine bugs here because otherwise
# not all of our features will work. Still, we should keep the number of bug
# fixes to a minimum and report everything to Google, please:
# http://code.google.com/p/googleappengine/issues/list
from google.appengine.ext import db
from google.appengine.ext.db import polymodel
import logging, os, re, sys
base_path = os.path.abspath(os.path.dirname(__file__))
get_verbose_name = lambda class_name: re.sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', ' \\1', class_name).lower().strip()
DEFAULT_NAMES = ('verbose_name', 'ordering', 'permissions', 'app_label',
'abstract', 'db_table', 'db_tablespace')
# Add checkpoints to patching procedure, so we don't apply certain patches
# multiple times. This can happen if an exeception gets raised on the first
# request of an instance. In that case, main.py gets reloaded and patch_all()
# gets executed yet another time.
done_patch_all = False
def patch_all():
global done_patch_all
if done_patch_all:
return
patch_python()
patch_app_engine()
# Add signals: post_save_committed, post_delete_committed
from appenginepatcher import transactions
setup_logging()
done_patch_all = True
def patch_python():
# Remove modules that we want to override. Don't remove modules that we've
# already overridden.
for module in ('memcache',):
if module in sys.modules and \
not sys.modules[module].__file__.startswith(base_path):
del sys.modules[module]
# For some reason the imp module can't be replaced via sys.path
from appenginepatcher import have_appserver
if have_appserver:
from appenginepatcher import imp
sys.modules['imp'] = imp
if have_appserver:
def unlink(_):
raise NotImplementedError('App Engine does not support FS writes!')
os.unlink = unlink
def patch_app_engine():
# This allows for using Paginator on a Query object. We limit the number
# of results to 301, so there won't be any timeouts (301, so you can say
# "more than 300 results").
def __len__(self):
return self.count()
db.Query.__len__ = __len__
old_count = db.Query.count
def count(self, limit=301):
return old_count(self, limit)
db.Query.count = count
# Add "model" property to Query (needed by generic views)
class ModelProperty(object):
def __get__(self, query, unused):
try:
return query._Query__model_class
except:
return query._model_class
db.Query.model = ModelProperty()
db.GqlQuery.model = ModelProperty()
# Add a few Model methods that are needed for serialization and ModelForm
def _get_pk_val(self):
if self.has_key():
return unicode(self.key())
else:
return None
db.Model._get_pk_val = _get_pk_val
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self._get_pk_val() == other._get_pk_val()
db.Model.__eq__ = __eq__
def __ne__(self, other):
return not self.__eq__(other)
db.Model.__ne__ = __ne__
def pk(self):
return self._get_pk_val()
db.Model.id = db.Model.pk = property(pk)
def serializable_value(self, field_name):
"""
Returns the value of the field name for this instance. If the field is
a foreign key, returns the id value, instead of the object. If there's
no Field object with this name on the model, the model attribute's
value is returned directly.
Used to serialize a field's value (in the serializer, or form output,
for example). Normally, you would just access the attribute directly
and not use this method.
"""
from django.db.models.fields import FieldDoesNotExist
try:
field = self._meta.get_field(field_name)
except FieldDoesNotExist:
return getattr(self, field_name)
return getattr(self, field.attname)
db.Model.serializable_value = serializable_value
# Make Property more Django-like (needed for serialization and ModelForm)
db.Property.serialize = True
db.Property.editable = True
db.Property.help_text = ''
def blank(self):
return not self.required
db.Property.blank = property(blank)
def _get_verbose_name(self):
if not getattr(self, '_verbose_name', None):
self._verbose_name = self.name.replace('_', ' ')
return self._verbose_name
def _set_verbose_name(self, verbose_name):
self._verbose_name = verbose_name
db.Property.verbose_name = property(_get_verbose_name, _set_verbose_name)
def attname(self):
return self.name
db.Property.attname = property(attname)
class EmptyObject(object):
pass
class Rel(object):
def __init__(self, property):
self.field_name = 'key'
self.field = EmptyObject()
self.field.name = self.field_name
self.property = property
self.to = property.reference_class
self.multiple = True
self.parent_link = False
self.related_name = getattr(property, 'collection_name', None)
self.through = None
def get_related_field(self):
"""
Returns the Field in the 'to' object to which this relationship is
tied.
"""
data = self.to._meta.get_field_by_name(self.field_name)
if not data[2]:
raise FieldDoesNotExist("No related field named '%s'" %
self.field_name)
return data[0]
class RelProperty(object):
def __get__(self, property, cls):
if property is None:
return self
if not hasattr(property, 'reference_class'):
return None
if not hasattr(property, '_rel_cache'):
property._rel_cache = Rel(property)
return property._rel_cache
db.Property.rel = RelProperty()
def formfield(self, **kwargs):
return self.get_form_field(**kwargs)
db.Property.formfield = formfield
def _get_flatchoices(self):
"""Flattened version of choices tuple."""
if not self.choices:
return []
if not isinstance(choices[0], (list, tuple)):
return [(choice, choice) for choice in self.choices]
flat = []
for choice, value in self.choices:
if type(value) in (list, tuple):
flat.extend(value)
else:
flat.append((choice,value))
return flat
db.Property.flatchoices = property(_get_flatchoices)
# Add repr to make debugging a little bit easier
def __repr__(self):
data = []
if self.has_key():
if self.key().name():
data.append('key_name='+repr(self.key().name()))
else:
data.append('key_id='+repr(self.key().id()))
for field in self._meta.fields:
if isinstance(field, db.ReferenceProperty):
data.append(field.name+'='+repr(field.get_value_for_datastore(self)))
continue
try:
data.append(field.name+'='+repr(getattr(self, field.name)))
except:
data.append(field.name+'='+repr(field.get_value_for_datastore(self)))
return u'%s(%s)' % (self.__class__.__name__, ', '.join(data))
db.Model.__repr__ = __repr__
# Add default __str__ and __unicode__ methods
def __str__(self):
return unicode(self).encode('utf-8')
db.Model.__str__ = __str__
def __unicode__(self):
return unicode(repr(self))
db.Model.__unicode__ = __unicode__
# Replace save() method with one that calls put(), so a monkey-patched
# put() will also work if someone uses save()
def save(self):
self.put()
db.Model.save = save
# Add _meta to Model, so porting code becomes easier (generic views,
# xheaders, and serialization depend on it).
from django.conf import settings
from django.utils.encoding import force_unicode, smart_str
from django.utils.translation import string_concat, get_language, \
activate, deactivate_all
class _meta(object):
many_to_many = ()
class pk:
name = 'key'
attname = 'pk'
@classmethod
def get_db_prep_lookup(cls, lookup_type, pk_value):
if isinstance(pk_value, db.Key):
return pk_value
return db.Key(pk_value)
def __init__(self, model, bases):
try:
self.app_label = model.__module__.split('.')[-2]
except IndexError:
raise ValueError('Django expects models (here: %s.%s) to be defined in their own apps!' % (model.__module__, model.__name__))
self.parents = [b for b in bases if issubclass(b, db.Model)]
self.object_name = model.__name__
self.module_name = self.object_name.lower()
self.verbose_name = get_verbose_name(self.object_name)
self.ordering = ()
self.abstract = model is db.Model
self.model = model
self.unique_together = ()
self.proxy = False
self.has_auto_field = True
self.installed = model.__module__.rsplit('.', 1)[0] in \
settings.INSTALLED_APPS
self.permissions = []
meta = model.__dict__.get('Meta')
if meta:
meta_attrs = meta.__dict__.copy()
for name in meta.__dict__:
# Ignore any private attributes that Django doesn't care about.
# NOTE: We can't modify a dictionary's contents while looping
# over it, so we loop over the *original* dictionary instead.
if name.startswith('_'):
del meta_attrs[name]
for attr_name in DEFAULT_NAMES:
if attr_name in meta_attrs:
setattr(self, attr_name, meta_attrs.pop(attr_name))
elif hasattr(meta, attr_name):
setattr(self, attr_name, getattr(meta, attr_name))
# verbose_name_plural is a special case because it uses a 's'
# by default.
setattr(self, 'verbose_name_plural', meta_attrs.pop('verbose_name_plural', string_concat(self.verbose_name, 's')))
# Any leftover attributes must be invalid.
if meta_attrs != {}:
raise TypeError, "'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs.keys())
else:
self.verbose_name_plural = self.verbose_name + 's'
if not isinstance(self.permissions, list):
self.permissions = list(self.permissions)
if not self.abstract:
self.permissions.extend([
('add_%s' % self.object_name.lower(),
string_concat('Can add ', self.verbose_name)),
('change_%s' % self.object_name.lower(),
string_concat('Can change ', self.verbose_name)),
('delete_%s' % self.object_name.lower(),
string_concat('Can delete ', self.verbose_name)),
])
def __repr__(self):
return '<Options for %s>' % self.object_name
def __str__(self):
return "%s.%s" % (smart_str(self.app_label), smart_str(self.module_name))
def _set_db_table(self, db_table):
self._db_table = db_table
def _get_db_table(self):
if getattr(settings, 'DJANGO_STYLE_MODEL_KIND', True):
if hasattr(self, '_db_table'):
return self._db_table
return '%s_%s' % (self.app_label, self.module_name)
return self.object_name
db_table = property(_get_db_table, _set_db_table)
def _set_db_tablespace(self, db_tablespace):
self._db_tablespace = db_tablespace
def _get_db_tablespace(self):
if hasattr(self, '_db_tablespace'):
return self._db_tablespace
return settings.DEFAULT_TABLESPACE
db_tablespace = property(_get_db_tablespace, _set_db_tablespace)
@property
def verbose_name_raw(self):
"""
There are a few places where the untranslated verbose name is needed
(so that we get the same value regardless of currently active
locale).
"""
lang = get_language()
deactivate_all()
raw = force_unicode(self.verbose_name)
activate(lang)
return raw
@property
def local_fields(self):
return tuple(sorted([p for p in self.model.properties().values()
if not isinstance(p, db.ListProperty)],
key=lambda prop: prop.creation_counter))
@property
def local_many_to_many(self):
return tuple(sorted([p for p in self.model.properties().values()
if isinstance(p, db.ListProperty) and
not (issubclass(self.model,
polymodel.PolyModel)
and p.name == 'class')],
key=lambda prop: prop.creation_counter))
@property
def fields(self):
return self.local_fields + self.local_many_to_many
def init_name_map(self):
"""
Initialises the field name -> field object mapping.
"""
from django.db.models.loading import app_cache_ready
cache = {}
# We intentionally handle related m2m objects first so that symmetrical
# m2m accessor names can be overridden, if necessary.
for f, model in self.get_all_related_m2m_objects_with_model():
try:
cache[f.field.collection_name] = (f, model, False, True)
except:
pass
for f, model in self.get_all_related_objects_with_model():
try:
cache[f.field.collection_name] = (f, model, False, False)
except:
pass
if app_cache_ready():
self._name_map = cache
return cache
def get_field(self, name, many_to_many=True):
"""
Returns the requested field by name. Raises FieldDoesNotExist on error.
"""
for f in self.fields:
if f.name == name:
return f
from django.db.models.fields import FieldDoesNotExist
raise FieldDoesNotExist, '%s has no field named %r' % (self.object_name, name)
def get_field_by_name(self, name):
"""
Returns the (field_object, model, direct, m2m), where field_object is
the Field instance for the given name, model is the model containing
this field (None for local fields), direct is True if the field exists
on this model, and m2m is True for many-to-many relations. When
'direct' is False, 'field_object' is the corresponding RelatedObject
for this field (since the field doesn't have an instance associated
with it).
Uses a cache internally, so after the first access, this is very fast.
"""
try:
try:
return self._name_map[name]
except AttributeError:
cache = self.init_name_map()
return cache[name]
except KeyError:
from django.db.models.fields import FieldDoesNotExist
raise FieldDoesNotExist('%s has no field named %r'
% (self.object_name, name))
def get_all_related_objects(self, local_only=False):
try:
self._related_objects_cache
except AttributeError:
self._fill_related_objects_cache()
if local_only:
return [k for k, v in self._related_objects_cache.items() if not v]
return self._related_objects_cache.keys()
def get_all_related_objects_with_model(self):
"""
Returns a list of (related-object, model) pairs. Similar to
get_fields_with_model().
"""
try:
self._related_objects_cache
except AttributeError:
self._fill_related_objects_cache()
return self._related_objects_cache.items()
def _fill_related_objects_cache(self):
from django.db.models.loading import get_models
from django.db.models.related import RelatedObject
from django.utils.datastructures import SortedDict
cache = SortedDict()
parent_list = self.get_parent_list()
for parent in self.parents:
for obj, model in parent._meta.get_all_related_objects_with_model():
if (obj.field.creation_counter < 0 or obj.field.rel.parent_link) and obj.model not in parent_list:
continue
if not model:
cache[obj] = parent
else:
cache[obj] = model
for klass in get_models():
for f in klass._meta.local_fields:
if f.rel and not isinstance(f.rel.to, str) and self == f.rel.to._meta:
cache[RelatedObject(f.rel.to, klass, f)] = None
self._related_objects_cache = cache
def get_all_related_many_to_many_objects(self, local_only=False):
try:
cache = self._related_many_to_many_cache
except AttributeError:
cache = self._fill_related_many_to_many_cache()
if local_only:
return [k for k, v in cache.items() if not v]
return cache.keys()
def get_all_related_m2m_objects_with_model(self):
"""
Returns a list of (related-m2m-object, model) pairs. Similar to
get_fields_with_model().
"""
try:
cache = self._related_many_to_many_cache
except AttributeError:
cache = self._fill_related_many_to_many_cache()
return cache.items()
def _fill_related_many_to_many_cache(self):
from django.db.models.loading import get_models, app_cache_ready
from django.db.models.related import RelatedObject
from django.utils.datastructures import SortedDict
cache = SortedDict()
parent_list = self.get_parent_list()
for parent in self.parents:
for obj, model in parent._meta.get_all_related_m2m_objects_with_model():
if obj.field.creation_counter < 0 and obj.model not in parent_list:
continue
if not model:
cache[obj] = parent
else:
cache[obj] = model
for klass in get_models():
for f in klass._meta.local_many_to_many:
if f.rel and not isinstance(f.rel.to, str) and self == f.rel.to._meta:
cache[RelatedObject(f.rel.to, klass, f)] = None
if app_cache_ready():
self._related_many_to_many_cache = cache
return cache
def get_add_permission(self):
return 'add_%s' % self.object_name.lower()
def get_change_permission(self):
return 'change_%s' % self.object_name.lower()
def get_delete_permission(self):
return 'delete_%s' % self.object_name.lower()
def get_ordered_objects(self):
return []
def get_parent_list(self):
"""
Returns a list of all the ancestor of this model as a list. Useful for
determining if something is an ancestor, regardless of lineage.
"""
result = set()
for parent in self.parents:
result.add(parent)
result.update(parent._meta.get_parent_list())
return result
# Required to support reference properties to db.Model
db.Model._meta = _meta(db.Model, ())
def _initialize_model(cls, bases):
cls._meta = _meta(cls, bases)
cls._default_manager = cls
if not cls._meta.abstract:
from django.db.models.loading import register_models
register_models(cls._meta.app_label, cls)
# Register models with Django
from django.db.models import signals
if not hasattr(db.PropertiedClass.__init__, 'patched'):
old_propertied_class_init = db.PropertiedClass.__init__
def __init__(cls, name, bases, attrs, map_kind=True):
"""Creates a combined appengine and Django model.
The resulting model will be known to both the appengine libraries
and Django.
"""
_initialize_model(cls, bases)
old_propertied_class_init(cls, name, bases, attrs,
not cls._meta.abstract)
signals.class_prepared.send(sender=cls)
__init__.patched = True
db.PropertiedClass.__init__ = __init__
if not hasattr(polymodel.PolymorphicClass.__init__, 'patched'):
old_poly_init = polymodel.PolymorphicClass.__init__
def __init__(cls, name, bases, attrs):
if polymodel.PolyModel not in bases:
_initialize_model(cls, bases)
old_poly_init(cls, name, bases, attrs)
if polymodel.PolyModel not in bases:
signals.class_prepared.send(sender=cls)
__init__.patched = True
polymodel.PolymorphicClass.__init__ = __init__
@classmethod
def kind(cls):
return cls._meta.db_table
db.Model.kind = kind
# Add model signals
if not hasattr(db.Model.__init__, 'patched'):
old_model_init = db.Model.__init__
def __init__(self, *args, **kwargs):
signals.pre_init.send(sender=self.__class__, args=args,
kwargs=kwargs)
old_model_init(self, *args, **kwargs)
signals.post_init.send(sender=self.__class__, instance=self)
__init__.patched = True
db.Model.__init__ = __init__
if not hasattr(db.Model.put, 'patched'):
old_put = db.Model.put
def put(self, *args, **kwargs):
signals.pre_save.send(sender=self.__class__, instance=self,
raw=False)
created = not self.is_saved()
result = old_put(self, *args, **kwargs)
signals.post_save.send(sender=self.__class__, instance=self,
created=created, raw=False)
return result
put.patched = True
db.Model.put = put
if not hasattr(db.put, 'patched'):
old_db_put = db.put
def put(models, *args, **kwargs):
if not isinstance(models, (list, tuple)):
items = (models,)
else:
items = models
items_created = []
for item in items:
if not isinstance(item, db.Model):
continue
signals.pre_save.send(sender=item.__class__, instance=item,
raw=False)
items_created.append(not item.is_saved())
result = old_db_put(models, *args, **kwargs)
for item, created in zip(items, items_created):
if not isinstance(item, db.Model):
continue
signals.post_save.send(sender=item.__class__, instance=item,
created=created, raw=False)
return result
put.patched = True
db.put = put
if not hasattr(db.Model.delete, 'patched'):
old_delete = db.Model.delete
def delete(self, *args, **kwargs):
signals.pre_delete.send(sender=self.__class__, instance=self)
result = old_delete(self, *args, **kwargs)
signals.post_delete.send(sender=self.__class__, instance=self)
return result
delete.patched = True
db.Model.delete = delete
if not hasattr(db.delete, 'patched'):
old_db_delete = db.delete
def delete(models, *args, **kwargs):
if not isinstance(models, (list, tuple)):
items = (models,)
else:
items = models
for item in items:
if not isinstance(item, db.Model):
continue
signals.pre_delete.send(sender=item.__class__, instance=item)
result = old_db_delete(models, *args, **kwargs)
for item in items:
if not isinstance(item, db.Model):
continue
signals.post_delete.send(sender=item.__class__, instance=item)
return result
delete.patched = True
db.delete = delete
# This has to come last because we load Django here
from django.db.models.fields import BLANK_CHOICE_DASH
def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH):
first_choice = include_blank and blank_choice or []
if self.choices:
return first_choice + list(self.choices)
if self.rel:
return first_choice + [(obj.pk, unicode(obj))
for obj in self.rel.to.all().fetch(301)]
return first_choice
db.Property.get_choices = get_choices
fix_app_engine_bugs()
def fix_app_engine_bugs():
# Fix handling of verbose_name. Google resolves lazy translation objects
# immedately which of course breaks translation support.
# http://code.google.com/p/googleappengine/issues/detail?id=583
from django import forms
from django.utils.text import capfirst
# This import is needed, so the djangoforms patch can do its work, first
from google.appengine.ext.db import djangoforms
def get_form_field(self, form_class=forms.CharField, **kwargs):
defaults = {'required': self.required}
defaults['label'] = capfirst(self.verbose_name)
if self.choices:
choices = []
if not self.required or (self.default is None and
'initial' not in kwargs):
choices.append(('', '---------'))
for choice in self.choices:
choices.append((unicode(choice), unicode(choice)))
defaults['widget'] = forms.Select(choices=choices)
if self.default is not None:
defaults['initial'] = self.default
defaults.update(kwargs)
return form_class(**defaults)
db.Property.get_form_field = get_form_field
# Extend ModelForm with support for EmailProperty
# http://code.google.com/p/googleappengine/issues/detail?id=880
def get_form_field(self, **kwargs):
"""Return a Django form field appropriate for an email property."""
defaults = {'form_class': forms.EmailField}
defaults.update(kwargs)
return super(db.EmailProperty, self).get_form_field(**defaults)
db.EmailProperty.get_form_field = get_form_field
# Fix DateTimeProperty, so it returns a property even for auto_now and
# auto_now_add.
# http://code.google.com/p/googleappengine/issues/detail?id=994
def get_form_field(self, **kwargs):
defaults = {'form_class': forms.DateTimeField}
defaults.update(kwargs)
return super(db.DateTimeProperty, self).get_form_field(**defaults)
db.DateTimeProperty.get_form_field = get_form_field
def get_form_field(self, **kwargs):
defaults = {'form_class': forms.DateField}
defaults.update(kwargs)
return super(db.DateProperty, self).get_form_field(**defaults)
db.DateProperty.get_form_field = get_form_field
def get_form_field(self, **kwargs):
defaults = {'form_class': forms.TimeField}
defaults.update(kwargs)
return super(db.TimeProperty, self).get_form_field(**defaults)
db.TimeProperty.get_form_field = get_form_field
# Improve handing of StringListProperty
def get_form_field(self, **kwargs):
defaults = {'widget': forms.Textarea,
'initial': ''}
defaults.update(kwargs)
defaults['required'] = False
return super(db.StringListProperty, self).get_form_field(**defaults)
db.StringListProperty.get_form_field = get_form_field
# Fix file uploads via BlobProperty
def get_form_field(self, **kwargs):
defaults = {'form_class': forms.FileField}
defaults.update(kwargs)
return super(db.BlobProperty, self).get_form_field(**defaults)
db.BlobProperty.get_form_field = get_form_field
def get_value_for_form(self, instance):
return getattr(instance, self.name)
db.BlobProperty.get_value_for_form = get_value_for_form
from django.core.files.uploadedfile import UploadedFile
def make_value_from_form(self, value):
if isinstance(value, UploadedFile):
return db.Blob(value.read())
return super(db.BlobProperty, self).make_value_from_form(value)
db.BlobProperty.make_value_from_form = make_value_from_form
# Optimize ReferenceProperty, so it returns the key directly
# http://code.google.com/p/googleappengine/issues/detail?id=993
def get_value_for_form(self, instance):
return self.get_value_for_datastore(instance)
db.ReferenceProperty.get_value_for_form = get_value_for_form
# Use our ModelChoiceField instead of Google's
def get_form_field(self, **kwargs):
defaults = {'form_class': forms.ModelChoiceField,
'queryset': self.reference_class.all()}
defaults.update(kwargs)
return super(db.ReferenceProperty, self).get_form_field(**defaults)
db.ReferenceProperty.get_form_field = get_form_field
def setup_logging():
from django.conf import settings
if settings.DEBUG:
logging.getLogger().setLevel(logging.DEBUG)
else:
logging.getLogger().setLevel(logging.INFO)
| Python |
from google.appengine.api import apiproxy_stub_map
from google.appengine.ext import db
from django.dispatch import Signal
from django.db.models import signals
from django.utils._threading_local import local
from functools import wraps
# Add signals which can be run after a transaction has been committed
signals.post_save_committed = Signal()
signals.post_delete_committed = Signal()
local = local()
# Patch transaction handlers, so we can support post_xxx_committed signals
run_in_transaction = db.run_in_transaction
if not hasattr(run_in_transaction, 'patched'):
@wraps(run_in_transaction)
def handle_signals(*args, **kwargs):
try:
if not getattr(local, 'in_transaction', False):
local.in_transaction = True
local.notify = []
result = run_in_transaction(*args, **kwargs)
except:
local.in_transaction = False
local.notify = []
raise
else:
commit()
return result
handle_signals.patched = True
db.run_in_transaction = handle_signals
run_in_transaction_custom_retries = db.run_in_transaction_custom_retries
if not hasattr(run_in_transaction_custom_retries, 'patched'):
@wraps(run_in_transaction_custom_retries)
def handle_signals(*args, **kwargs):
try:
result = run_in_transaction_custom_retries(*args, **kwargs)
except:
local.in_transaction = False
local.notify = []
raise
else:
commit()
return result
handle_signals.patched = True
db.run_in_transaction_custom_retries = handle_signals
def hook(service, call, request, response):
if call == 'Rollback':
# This stores a list of tuples (action, sender, kwargs)
# Possible actions: 'delete', 'save'
local.in_transaction = True
local.notify = []
apiproxy_stub_map.apiproxy.GetPostCallHooks().Append('tx_signals', hook)
def commit():
local.in_transaction = False
for action, sender, kwds in local.notify:
signal = getattr(signals, 'post_%s_committed' % action)
signal.send(sender=sender, **kwds)
def entity_saved(sender, **kwargs):
if 'signal' in kwargs:
del kwargs['signal']
if getattr(local, 'in_transaction', False):
local.notify.append(('save', sender, kwargs))
else:
signals.post_save_committed.send(sender=sender, **kwargs)
signals.post_save.connect(entity_saved)
def entity_deleted(sender, **kwargs):
if 'signal' in kwargs:
del kwargs['signal']
if getattr(local, 'in_transaction', False):
local.notify.append(('delete', sender, kwargs))
else:
signals.post_delete_committed.send(sender=sender, **kwargs)
signals.post_delete.connect(entity_deleted)
| Python |
from google.appengine.api import apiproxy_stub_map
import os, sys
have_appserver = bool(apiproxy_stub_map.apiproxy.GetStub('datastore_v3'))
if have_appserver:
appid = os.environ.get('APPLICATION_ID')
else:
try:
from google.appengine.tools import dev_appserver
from aecmd import PROJECT_DIR
appconfig, unused = dev_appserver.LoadAppConfig(PROJECT_DIR, {})
appid = appconfig.application
except ImportError:
appid = None
on_production_server = have_appserver and \
not os.environ.get('SERVER_SOFTWARE', '').lower().startswith('devel')
| Python |
from google.appengine.api.memcache import *
| Python |
from ragendja.settings_post import settings
from appenginepatcher import have_appserver, on_production_server
if have_appserver and not on_production_server and \
settings.MEDIA_URL.startswith('/'):
if settings.ADMIN_MEDIA_PREFIX.startswith(settings.MEDIA_URL):
settings.ADMIN_MEDIA_PREFIX = '/generated_media' + \
settings.ADMIN_MEDIA_PREFIX
settings.MEDIA_URL = '/generated_media' + settings.MEDIA_URL
settings.MIDDLEWARE_CLASSES = (
'mediautils.middleware.MediaMiddleware',
) + settings.MIDDLEWARE_CLASSES
| Python |
# -*- coding: utf-8 -*-
from django.conf import settings
from django.utils.simplejson import dumps
from os.path import getmtime
import os, codecs, shutil, logging, re
class MediaGeneratorError(Exception):
pass
path_re = re.compile(r'/[^/]+/\.\./')
MEDIA_VERSION = unicode(settings.MEDIA_VERSION)
COMPRESSOR = os.path.join(os.path.dirname(__file__), '.yuicompressor.jar')
PROJECT_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(
os.path.dirname(__file__)))))
GENERATED_MEDIA = os.path.join(PROJECT_ROOT, '_generated_media')
MEDIA_ROOT = os.path.join(GENERATED_MEDIA, MEDIA_VERSION)
DYNAMIC_MEDIA = os.path.join(PROJECT_ROOT, '.dynamic_media')
# A list of file types that have to be combined
MUST_COMBINE = ['.js', '.css']
# Detect language codes
if not settings.USE_I18N:
LANGUAGES = (settings.LANGUAGE_CODE,)
else:
LANGUAGES = [code for code, _ in settings.LANGUAGES]
# Dynamic source handlers
def site_data(**kwargs):
"""Provide site_data variable with settings (currently only MEDIA_URL)."""
content = 'window.site_data = {};'
content += 'window.site_data.settings = %s;' % dumps({
'MEDIA_URL': settings.MEDIA_URL
})
return content
def lang_data(LANGUAGE_CODE, **kwargs):
# These are needed for i18n
from django.http import HttpRequest
from django.views.i18n import javascript_catalog
LANGUAGE_BIDI = LANGUAGE_CODE.split('-')[0] in \
settings.LANGUAGES_BIDI
request = HttpRequest()
request.GET['language'] = LANGUAGE_CODE
# Add some JavaScript data
content = 'var LANGUAGE_CODE = "%s";\n' % LANGUAGE_CODE
content += 'var LANGUAGE_BIDI = ' + \
(LANGUAGE_BIDI and 'true' or 'false') + ';\n'
content += javascript_catalog(request,
packages=settings.INSTALLED_APPS).content
# The hgettext() function just calls gettext() internally, but
# it won't get indexed by makemessages.
content += '\nwindow.hgettext = function(text) { return gettext(text); };\n'
# Add a similar hngettext() function
content += 'window.hngettext = function(singular, plural, count) { return ngettext(singular, plural, count); };\n'
return content
lang_data.name = 'lang-%(LANGUAGE_CODE)s.js'
def generatemedia(compressed):
if os.path.exists(MEDIA_ROOT):
shutil.rmtree(MEDIA_ROOT)
updatemedia(compressed)
def copy_file(path, generated):
dirpath = os.path.dirname(generated)
if not os.path.exists(dirpath):
os.makedirs(dirpath)
shutil.copyfile(path, generated)
def compress_file(path):
if not path.endswith(('.css', '.js')):
return
from subprocess import Popen
print ' Running yuicompressor...',
try:
cmd = Popen(['java', '-jar', COMPRESSOR, '--charset', 'UTF-8',
path, '-o', path])
if cmd.wait() == 0:
print '%d bytes' % os.path.getsize(path)
else:
print 'Failed!'
except:
raise MediaGeneratorError("Failed to execute Java VM. "
"Please make sure that you have installed Java "
"and that it's in your PATH.")
def get_file_path(handler, target, media_dirs, **kwargs):
if isinstance(handler, basestring):
path = handler % dict(kwargs, target=target)
app, filepath = path.replace('/', os.sep).split(os.sep, 1)
return os.path.abspath(os.path.join(media_dirs[app], filepath))
ext = os.path.splitext(target)[1]
owner = ''
for app in settings.INSTALLED_APPS:
if handler.__module__.startswith(app + '.') and len(app) > len(owner):
owner = app
owner = owner or handler.__module__
name = getattr(handler, 'name', handler.__name__ + ext) % dict(kwargs,
target=target)
return os.path.join(DYNAMIC_MEDIA, '%s/%s' % (owner, name))
def get_css_content(handler, content, **kwargs):
# Add $MEDIA_URL variable to CSS files
content = content.replace('$MEDIA_URL/', settings.MEDIA_URL)
# Remove @charset rules
content = re.sub(r'@charset(.*?);', '', content)
if not isinstance(handler, basestring):
return content
def fixurls(path):
# Resolve ../ paths
path = '%s%s/%s' % (settings.MEDIA_URL,
os.path.dirname(handler % dict(kwargs)),
path.group(1))
while path_re.search(path):
path = path_re.sub('/', path, 1)
return 'url("%s")' % path
# Make relative paths work with MEDIA_URL
content = re.sub(r'url\s*\(["\']?([\w\.][^:]*?)["\']?\)',
fixurls, content)
return content
def get_file_content(handler, cache, **kwargs):
path = get_file_path(handler, **kwargs)
if path not in cache:
if isinstance(handler, basestring):
try:
file = codecs.open(path, 'r', 'utf-8')
cache[path] = file.read().lstrip(codecs.BOM_UTF8.decode('utf-8')
).replace('\r\n', '\n').replace('\r', '\n')
except:
import traceback
raise MediaGeneratorError('Error in %s:\n%s\n' %
(path, traceback.format_exc()))
file.close()
elif callable(handler):
cache[path] = handler(**kwargs)
else:
raise ValueError('Media generator source "%r" not valid!' % handler)
# Rewrite url() paths in CSS files
ext = os.path.splitext(path)[1]
if ext == '.css':
cache[path] = get_css_content(handler, cache[path], **kwargs)
return cache[path]
def update_dynamic_file(handler, cache, **kwargs):
assert callable(handler)
path = get_file_path(handler, **kwargs)
content = get_file_content(handler, cache, **kwargs)
needs_update = not os.path.exists(path)
if not needs_update:
file = codecs.open(path, 'r', 'utf-8')
if content != file.read():
needs_update = True
file.close()
if needs_update:
dir = os.path.dirname(path)
if not os.path.isdir(dir):
os.makedirs(dir)
file = codecs.open(path, 'w', 'utf-8')
file.write(content)
file.close()
return needs_update
def get_target_content(group, cache, **kwargs):
content = ''
for handler in group:
content += get_file_content(handler, cache, **kwargs)
content += '\n'
return content
def get_targets(combine_media=settings.COMBINE_MEDIA, **kwargs):
"""Returns all files that must be combined."""
targets = []
for target in sorted(combine_media.keys()):
group = combine_media[target]
if '.site_data.js' in group:
# site_data must always come first because other modules might
# depend on it
group.remove('.site_data.js')
group.insert(0, site_data)
if '%(LANGUAGE_CODE)s' in target:
# This file uses i18n, so generate a separate file per language.
# The language data is always added before all other files.
for LANGUAGE_CODE in LANGUAGES:
data = kwargs.copy()
data['LANGUAGE_CODE'] = LANGUAGE_CODE
filename = target % data
data['target'] = filename
if lang_data not in group:
group.insert(0, lang_data)
targets.append((filename, data, group))
elif '%(LANGUAGE_DIR)s' in target:
# Generate CSS files for both text directions
for LANGUAGE_DIR in ('ltr', 'rtl'):
data = kwargs.copy()
data['LANGUAGE_DIR'] = LANGUAGE_DIR
filename = target % data
data['target'] = filename
targets.append((filename, data, group))
else:
data = kwargs.copy()
filename = target % data
data['target'] = filename
targets.append((filename, data, group))
return targets
def get_copy_targets(media_dirs, **kwargs):
"""Returns paths of files that must be copied directly."""
# Some files types (MUST_COMBINE) never get copied.
# They must always be combined.
targets = {}
for app, media_dir in media_dirs.items():
for root, dirs, files in os.walk(media_dir):
for name in dirs[:]:
if name.startswith('.'):
dirs.remove(name)
for file in files:
if file.startswith('.') or file.endswith(tuple(MUST_COMBINE)):
continue
path = os.path.abspath(os.path.join(root, file))
base = app + path[len(media_dir):]
targets[base.replace(os.sep, '/')] = path
return targets
def cleanup_dir(dir, paths):
# Remove old generated files
keep = []
dir = os.path.abspath(dir)
for path in paths:
if not os.path.isabs(path):
path = os.path.join(dir, path)
path = os.path.abspath(path)
while path not in keep and path != dir:
keep.append(path)
path = os.path.dirname(path)
for root, dirs, files in os.walk(dir):
for name in dirs[:]:
path = os.path.abspath(os.path.join(root, name))
if path not in keep:
shutil.rmtree(path)
dirs.remove(name)
for file in files:
path = os.path.abspath(os.path.join(root, file))
if path not in keep:
os.remove(path)
def get_media_dirs():
from ragendja.apputils import get_app_dirs
media_dirs = get_app_dirs('media')
media_dirs['global'] = os.path.join(PROJECT_ROOT, 'media')
return media_dirs
def updatemedia(compressed=None):
if 'mediautils' not in settings.INSTALLED_APPS:
return
# Remove unused media versions
if os.path.exists(GENERATED_MEDIA):
entries = os.listdir(GENERATED_MEDIA)
if len(entries) != 1 or MEDIA_VERSION not in entries:
shutil.rmtree(GENERATED_MEDIA)
from ragendja.apputils import get_app_dirs
# Remove old media if settings got modified (too much work to check
# if COMBINE_MEDIA was changed)
mtime = getmtime(os.path.join(PROJECT_ROOT, 'settings.py'))
for app_path in get_app_dirs().values():
path = os.path.join(app_path, 'settings.py')
if os.path.exists(path) and os.path.getmtime(path) > mtime:
mtime = os.path.getmtime(path)
if os.path.exists(MEDIA_ROOT) and getmtime(MEDIA_ROOT) <= mtime:
shutil.rmtree(MEDIA_ROOT)
if not os.path.exists(MEDIA_ROOT):
os.makedirs(MEDIA_ROOT)
if not os.path.exists(DYNAMIC_MEDIA):
os.makedirs(DYNAMIC_MEDIA)
if compressed is None:
compressed = not getattr(settings, 'FORCE_UNCOMPRESSED_MEDIA', False)
media_dirs = get_media_dirs()
data = {'media_dirs': media_dirs}
targets = get_targets(**data)
copy_targets = get_copy_targets(**data)
target_names = [target[0] for target in targets]
# Remove unneeded files
cleanup_dir(MEDIA_ROOT, target_names + copy_targets.keys())
dynamic_files = []
for target, kwargs, group in targets:
for handler in group:
if callable(handler):
dynamic_files.append(get_file_path(handler, **kwargs))
cleanup_dir(DYNAMIC_MEDIA, dynamic_files)
# Copy files
for target in sorted(copy_targets.keys()):
# Only overwrite files if they've been modified. Also, only
# copy files that won't get combined.
path = copy_targets[target]
generated = os.path.join(MEDIA_ROOT, target.replace('/', os.sep))
if os.path.exists(generated) and \
getmtime(generated) >= getmtime(path):
continue
print 'Copying %s...' % target
copy_file(path, generated)
# Update dynamic files
cache = {}
for target, kwargs, group in targets:
for handler in group:
if callable(handler):
update_dynamic_file(handler, cache, **kwargs)
# Combine media files
for target, kwargs, group in targets:
files = [get_file_path(handler, **kwargs) for handler in group]
path = os.path.join(MEDIA_ROOT, target.replace('/', os.sep))
# Only overwrite files if they've been modified
if os.path.exists(path):
target_mtime = getmtime(path)
if not [1 for name in files if os.path.exists(name) and
getmtime(name) >= target_mtime]:
continue
print 'Combining %s...' % target
dirpath = os.path.dirname(path)
if not os.path.exists(dirpath):
os.makedirs(dirpath)
file = codecs.open(path, 'w', 'utf-8')
file.write(get_target_content(group, cache, **kwargs))
file.close()
if compressed:
compress_file(path)
| Python |
# -*- coding: utf-8 -*-
from os.path import getmtime
import codecs, os
def updatemessages():
from django.conf import settings
if not settings.USE_I18N:
return
from django.core.management.commands.compilemessages import compile_messages
if any([needs_update(path) for path in settings.LOCALE_PATHS]):
compile_messages()
LOCALE_PATHS = settings.LOCALE_PATHS
settings.LOCALE_PATHS = ()
cwd = os.getcwdu()
for app in settings.INSTALLED_APPS:
path = os.path.dirname(__import__(app, {}, {}, ['']).__file__)
locale = os.path.join(path, 'locale')
if os.path.isdir(locale):
# Copy Python translations into JavaScript translations
update_js_translations(locale)
if needs_update(locale):
os.chdir(path)
compile_messages()
settings.LOCALE_PATHS = LOCALE_PATHS
os.chdir(cwd)
def needs_update(locale):
for root, dirs, files in os.walk(locale):
po_files = [os.path.join(root, file)
for file in files if file.endswith('.po')]
for po_file in po_files:
mo_file = po_file[:-2] + 'mo'
if not os.path.exists(mo_file) or \
getmtime(po_file) > getmtime(mo_file):
return True
return False
def update_js_translations(locale):
for lang in os.listdir(locale):
base_path = os.path.join(locale, lang, 'LC_MESSAGES')
py_file = os.path.join(base_path, 'django.po')
js_file = os.path.join(base_path, 'djangojs.po')
modified = False
if os.path.exists(py_file) and os.path.exists(js_file):
py_lines, py_mapping = load_translations(py_file)
js_lines, js_mapping = load_translations(js_file)
for msgid in js_mapping:
if msgid in py_mapping:
py_index = py_mapping[msgid]
js_index = js_mapping[msgid]
if py_lines[py_index] != js_lines[js_index]:
modified = True
# Copy comment to JS, too
if js_index >= 2 and py_index >= 2:
if js_lines[js_index - 2].startswith('#') and \
py_lines[py_index - 2].startswith('#'):
js_lines[js_index - 2] = py_lines[py_index - 2]
js_lines[js_index] = py_lines[py_index]
if modified:
print 'Updating JS locale for %s' % os.path.join(locale, lang)
file = codecs.open(js_file, 'w', 'utf-8')
file.write(''.join(js_lines))
file.close()
def load_translations(path):
"""Loads translations grouped into logical sections."""
file = codecs.open(path, 'r', 'utf-8')
lines = file.readlines()
file.close()
mapping = {}
msgid = None
start = -1
resultlines = []
for index, line in enumerate(lines):
# Group comments
if line.startswith('#'):
if resultlines and resultlines[-1].startswith('#'):
resultlines[-1] = resultlines[-1] + lines[index]
else:
resultlines.append(lines[index])
continue
if msgid is not None and (not line.strip() or line.startswith('msgid ')):
mapping[msgid] = len(resultlines)
resultlines.append(''.join(lines[start:index]))
msgid = None
start = -1
if line.startswith('msgid '):
line = line[len('msgid'):].strip()
start = -1
msgid = ''
if start < 0 and line.startswith('"'):
msgid += line.strip()[1:-1]
resultlines.append(lines[index])
continue
if line.startswith('msgstr') and start < 0:
start = index
if start < 0:
if resultlines and not resultlines[-1].startswith('msgstr'):
resultlines[-1] = resultlines[-1] + lines[index]
else:
resultlines.append(lines[index])
if msgid and start:
mapping[msgid] = len(resultlines)
resultlines.append(''.join(lines[start:]))
return resultlines, mapping
| Python |
# -*- coding: utf-8 -*-
"""
This app combines media files specified in the COMBINE_MEDIA setting into one
single file. It's a dictionary mapping the combined name to a tuple of files
that should be combined:
COMBINE_MEDIA = {
'global/js/combined.js': (
'global/js/main.js',
'app/js/other.js',
),
'global/css/main.css': (
'global/css/base.css',
'app/css/app.css',
)
}
The files will automatically be combined if you use manage.py runserver.
Files that shouldn't be combined are simply copied. Also, all css and js files
get compressed with yuicompressor. The result is written in a folder named
_generated_media.
If the target is a JavaScript file whose name contains the string
'%(LANGUAGE_CODE)s' it'll automatically be internationalized and multiple
files will be generated (one for each language code).
"""
from django.core.management.base import NoArgsCommand
from optparse import make_option
from mediautils.generatemedia import generatemedia, updatemedia, MEDIA_ROOT
import os, shutil
class Command(NoArgsCommand):
help = 'Combines and compresses your media files and saves them in _generated_media.'
option_list = NoArgsCommand.option_list + (
make_option('--uncompressed', action='store_true', dest='uncompressed',
help='Do not run yuicompressor on generated media.'),
make_option('--update', action='store_true', dest='update',
help='Only update changed files instead of regenerating everything.'),
)
requires_model_validation = False
def handle_noargs(self, **options):
compressed = None
if options.get('uncompressed'):
compressed = False
if options.get('update'):
updatemedia(compressed)
else:
generatemedia(compressed)
| Python |
# -*- coding: utf-8 -*-
from django.core.management.base import NoArgsCommand, CommandError
from optparse import make_option
import os, cStringIO, gzip, mimetypes
class Command(NoArgsCommand):
help = 'Uploads your _generated_media folder to Amazon S3.'
option_list = NoArgsCommand.option_list + (
make_option('--production', action='store_true', dest='production',
help='Does a real upload instead of a simulation.'),
)
requires_model_validation = False
def handle_noargs(self, **options):
s3uploadmedia(options.get('production', False))
def submit_cb(bytes_so_far, total_bytes):
print ' %d bytes transferred / %d bytes total\r' % (bytes_so_far,
total_bytes),
def s3uploadmedia(production):
from django.conf import settings
from ragendja.apputils import get_app_dirs
try:
from boto.s3.connection import S3Connection
except ImportError:
raise CommandError('This command requires boto.')
bucket_name = settings.MEDIA_BUCKET
if production:
connection = S3Connection()
bucket = connection.get_bucket(bucket_name)
print 'Uploading to %s' % bucket_name
print '\nDeleting old files...'
if production:
for key in bucket:
key.delete()
print '\nUploading new files...'
base = os.path.abspath('_generated_media')
for root, dirs, files in os.walk(base):
for file in files:
path = os.path.join(root, file)
key_name = path[len(base)+1:].replace(os.sep, '/')
print 'Copying %s (%d bytes)' % (key_name,
os.path.getsize(path))
if production:
key = bucket.new_key(key_name)
fp = open(path, 'rb')
headers = {}
# Text files should be compressed to speed up site loading
if file.split('.')[-1] in ('css', 'ht', 'js'):
print ' GZipping...',
gzbuf = cStringIO.StringIO()
zfile = gzip.GzipFile(mode='wb', fileobj=gzbuf)
zfile.write(fp.read())
zfile.close()
fp.close()
print '%d bytes' % gzbuf.tell()
gzbuf.seek(0)
fp = gzbuf
headers['Content-Encoding'] = 'gzip'
headers['Content-Type'] = mimetypes.guess_type(file)[0]
if production:
key.set_contents_from_file(fp, headers=headers,
cb=submit_cb, num_cb=10, policy='public-read')
fp.close()
if not production:
print '=============================================='
print 'This was just a simulation.'
print 'Please use --production to enforce the update.'
print 'Warning: This will change the production site!'
print '=============================================='
| Python |
# -*- coding: utf-8 -*-
from django.http import HttpResponse, Http404
from django.views.decorators.cache import cache_control
from mediautils.generatemedia import get_targets, get_copy_targets, \
get_target_content, get_media_dirs
from mimetypes import guess_type
from ragendja.template import render_to_response
@cache_control(public=True, max_age=3600*24*60*60)
def get_file(request, path):
media_dirs = get_media_dirs()
data = {'media_dirs': media_dirs}
targets = get_targets(**data)
copy_targets = get_copy_targets(**data)
target_names = [target[0] for target in targets]
name = path.rsplit('/', 1)[-1]
cache = {}
if path in target_names:
target, kwargs, group = targets[target_names.index(path)]
content = get_target_content(group, cache, **kwargs)
elif path in copy_targets:
fp = open(copy_targets[path], 'rb')
content = fp.read()
fp.close()
else:
raise Http404('Media file not found: %s' % path)
return HttpResponse(content,
content_type=guess_type(name)[0] or 'application/octet-stream')
| Python |
# -*- coding: utf-8 -*-
from django.conf import settings
from mediautils.views import get_file
class MediaMiddleware(object):
"""Returns media files.
This is a middleware, so it can handle the request as early as possible
and thus with minimum overhead."""
def process_request(self, request):
if request.path.startswith(settings.MEDIA_URL):
path = request.path[len(settings.MEDIA_URL):]
return get_file(request, path)
return None
| Python |
from django.conf import settings
from django.core.cache import cache
from django.contrib.sites.models import Site
from ragendja.dbutils import db_create
from ragendja.pyutils import make_tls_property
_default_site_id = getattr(settings, 'SITE_ID', None)
SITE_ID = settings.__class__.SITE_ID = make_tls_property()
class DynamicSiteIDMiddleware(object):
"""Sets settings.SIDE_ID based on request's domain"""
def process_request(self, request):
# Ignore port if it's 80 or 443
if ':' in request.get_host():
domain, port = request.get_host().split(':')
if int(port) not in (80, 443):
domain = request.get_host()
else:
domain = request.get_host().split(':')[0]
# We cache the SITE_ID
cache_key = 'Site:domain:%s' % domain
site = cache.get(cache_key)
if site:
SITE_ID.value = site
else:
site = Site.all().filter('domain =', domain).get()
if not site:
# Fall back to with/without 'www.'
if domain.startswith('www.'):
fallback_domain = domain[4:]
else:
fallback_domain = 'www.' + domain
site = Site.all().filter('domain =', fallback_domain).get()
# Add site if it doesn't exist
if not site and getattr(settings, 'CREATE_SITES_AUTOMATICALLY',
True):
site = db_create(Site, domain=domain, name=domain)
site.put()
# Set SITE_ID for this thread/request
if site:
SITE_ID.value = str(site.key())
else:
SITE_ID.value = _default_site_id
cache.set(cache_key, SITE_ID.value, 5*60)
| Python |
# -*- coding: utf-8 -*-
"""
Imports urlpatterns from apps, so we can have nice plug-n-play installation. :)
"""
from django.conf.urls.defaults import *
from django.conf import settings
IGNORE_APP_URLSAUTO = getattr(settings, 'IGNORE_APP_URLSAUTO', ())
check_app_imports = getattr(settings, 'check_app_imports', None)
urlpatterns = patterns('')
for app in settings.INSTALLED_APPS:
if app == 'ragendja' or app.startswith('django.') or \
app in IGNORE_APP_URLSAUTO:
continue
appname = app.rsplit('.', 1)[-1]
try:
if check_app_imports:
check_app_imports(app)
module = __import__(app + '.urlsauto', {}, {}, [''])
except ImportError:
pass
else:
if hasattr(module, 'urlpatterns'):
urlpatterns += patterns('', (r'^%s/' % appname,
include(app + '.urlsauto')),)
if hasattr(module, 'rootpatterns'):
urlpatterns += module.rootpatterns
| Python |
from django.conf import settings
import os
def import_module(module_name):
return __import__(module_name, {}, {}, [''])
def import_package(package_name):
package = [import_module(package_name)]
if package[0].__file__.rstrip('.pyc').rstrip('.py').endswith('__init__'):
package.extend([import_module(package_name + '.' + name)
for name in list_modules(package[0])])
return package
def list_modules(package):
dir = os.path.normpath(os.path.dirname(package.__file__))
try:
return set([name.rsplit('.', 1)[0] for name in os.listdir(dir)
if not name.startswith('_') and name.endswith(('.py', '.pyc'))])
except OSError:
return []
def get_app_modules(module_name=None):
app_map = {}
for app in settings.INSTALLED_APPS:
appname = app.rsplit('.', 1)[-1]
try:
if module_name:
app_map[appname] = import_package(app + '.' + module_name)
else:
app_map[appname] = [import_module(app)]
except ImportError:
if module_name in list_modules(import_module(app)):
raise
return app_map
def get_app_dirs(subdir=None):
app_map = {}
for appname, module in get_app_modules().items():
dir = os.path.abspath(os.path.dirname(module[0].__file__))
if subdir:
dir = os.path.join(dir, subdir)
if os.path.isdir(dir):
app_map[appname] = dir
return app_map
| Python |
# -*- coding: utf-8 -*-
from django.utils._threading_local import local
def make_tls_property(default=None):
"""Creates a class-wide instance property with a thread-specific value."""
class TLSProperty(object):
def __init__(self):
self.local = local()
def __get__(self, instance, cls):
if not instance:
return self
return self.value
def __set__(self, instance, value):
self.value = value
def _get_value(self):
return getattr(self.local, 'value', default)
def _set_value(self, value):
self.local.value = value
value = property(_get_value, _set_value)
return TLSProperty()
def getattr_by_path(obj, attr, *default):
"""Like getattr(), but can go down a hierarchy like 'attr.subattr'"""
value = obj
for part in attr.split('.'):
if not hasattr(value, part) and len(default):
return default[0]
value = getattr(value, part)
if callable(value):
value = value()
return value
def subdict(data, *attrs):
"""Returns a subset of the keys of a dictionary."""
result = {}
result.update([(key, data[key]) for key in attrs])
return result
def equal_lists(left, right):
"""
Compares two lists and returs True if they contain the same elements, but
doesn't require that they have the same order.
"""
right = list(right)
if len(left) != len(right):
return False
for item in left:
if item in right:
del right[right.index(item)]
else:
return False
return True
def object_list_to_table(headings, dict_list):
"""
Converts objects to table-style list of rows with heading:
Example:
x.a = 1
x.b = 2
x.c = 3
y.a = 11
y.b = 12
y.c = 13
object_list_to_table(('a', 'b', 'c'), [x, y])
results in the following (dict keys reordered for better readability):
[
('a', 'b', 'c'),
(1, 2, 3),
(11, 12, 13),
]
"""
return [headings] + [tuple([getattr_by_path(row, heading, None)
for heading in headings])
for row in dict_list]
def dict_list_to_table(headings, dict_list):
"""
Converts dict to table-style list of rows with heading:
Example:
dict_list_to_table(('a', 'b', 'c'),
[{'a': 1, 'b': 2, 'c': 3}, {'a': 11, 'b': 12, 'c': 13}])
results in the following (dict keys reordered for better readability):
[
('a', 'b', 'c'),
(1, 2, 3),
(11, 12, 13),
]
"""
return [headings] + [tuple([row[heading] for heading in headings])
for row in dict_list]
| Python |
# -*- coding: utf-8 -*-
from django.test import TestCase
from google.appengine.ext import db
from pyutils import object_list_to_table, equal_lists
import os
class ModelTestCase(TestCase):
"""
A test case for models that provides an easy way to validate the DB
contents against a given list of row-values.
You have to specify the model to validate using the 'model' attribute:
class MyTestCase(ModelTestCase):
model = MyModel
"""
def validate_state(self, columns, *state_table):
"""
Validates that the DB contains exactly the values given in the state
table. The list of columns is given in the columns tuple.
Example:
self.validate_state(
('a', 'b', 'c'),
(1, 2, 3),
(11, 12, 13),
)
validates that the table contains exactly two rows and that their
'a', 'b', and 'c' attributes are 1, 2, 3 for one row and 11, 12, 13
for the other row. The order of the rows doesn't matter.
"""
current_state = object_list_to_table(columns,
self.model.all())[1:]
if not equal_lists(current_state, state_table):
print 'DB state not valid:'
print 'Current state:'
print columns
for state in current_state:
print state
print 'Should be:'
for state in state_table:
print state
self.fail('DB state not valid')
| Python |
from copy import deepcopy
import re
from django import forms
from django.utils.datastructures import SortedDict, MultiValueDict
from django.utils.html import conditional_escape
from django.utils.encoding import StrAndUnicode, smart_unicode, force_unicode
from django.utils.safestring import mark_safe
from django.forms.widgets import flatatt
from google.appengine.ext import db
class FakeModelIterator(object):
def __init__(self, fake_model):
self.fake_model = fake_model
def __iter__(self):
for item in self.fake_model.all():
yield (item.get_value_for_datastore(), unicode(item))
class FakeModelChoiceField(forms.ChoiceField):
def __init__(self, fake_model, *args, **kwargs):
self.fake_model = fake_model
kwargs['choices'] = ()
super(FakeModelChoiceField, self).__init__(*args, **kwargs)
def _get_choices(self):
return self._choices
def _set_choices(self, choices):
self._choices = self.widget.choices = FakeModelIterator(self.fake_model)
choices = property(_get_choices, _set_choices)
def clean(self, value):
value = super(FakeModelChoiceField, self).clean(value)
return self.fake_model.make_value_from_datastore(value)
class FakeModelMultipleChoiceField(forms.MultipleChoiceField):
def __init__(self, fake_model, *args, **kwargs):
self.fake_model = fake_model
kwargs['choices'] = ()
super(FakeModelMultipleChoiceField, self).__init__(*args, **kwargs)
def _get_choices(self):
return self._choices
def _set_choices(self, choices):
self._choices = self.widget.choices = FakeModelIterator(self.fake_model)
choices = property(_get_choices, _set_choices)
def clean(self, value):
value = super(FakeModelMultipleChoiceField, self).clean(value)
return [self.fake_model.make_value_from_datastore(item)
for item in value]
class FormWithSets(object):
def __init__(self, form, formsets=()):
self.form = form
setattr(self, '__module__', form.__module__)
setattr(self, '__name__', form.__name__ + 'WithSets')
setattr(self, '__doc__', form.__doc__)
self._meta = form._meta
fields = [(name, field) for name, field in form.base_fields.iteritems() if isinstance(field, FormSetField)]
formset_dict = dict(formsets)
newformsets = []
for name, field in fields:
if formset_dict.has_key(name):
continue
newformsets.append((name, {'formset':field.make_formset(form._meta.model)}))
self.formsets = formsets + tuple(newformsets)
def __call__(self, *args, **kwargs):
prefix = kwargs['prefix'] + '-' if 'prefix' in kwargs else ''
form = self.form(*args, **kwargs)
if 'initial' in kwargs:
del kwargs['initial']
formsets = []
for name, formset in self.formsets:
kwargs['prefix'] = prefix + name
instance = formset['formset'](*args, **kwargs)
if form.base_fields.has_key(name):
field = form.base_fields[name]
else:
field = FormSetField(formset['formset'].model, **formset)
formsets.append(BoundFormSet(field, instance, name, formset))
return type(self.__name__ + 'Instance', (FormWithSetsInstance, ), {})(self, form, formsets)
def pretty_name(name):
"Converts 'first_name' to 'First name'"
name = name[0].upper() + name[1:]
return name.replace('_', ' ')
table_sections_re = re.compile(r'^(.*?)(<tr>.*</tr>)(.*?)$', re.DOTALL)
table_row_re = re.compile(r'(<tr>(<th><label.*?</label></th>)(<td>.*?</td>)</tr>)', re.DOTALL)
ul_sections_re = re.compile(r'^(.*?)(<li>.*</li>)(.*?)$', re.DOTALL)
ul_row_re = re.compile(r'(<li>(<label.*?</label>)(.*?)</li>)', re.DOTALL)
p_sections_re = re.compile(r'^(.*?)(<p>.*</p>)(.*?)$', re.DOTALL)
p_row_re = re.compile(r'(<p>(<label.*?</label>)(.*?)</p>)', re.DOTALL)
label_re = re.compile(r'^(.*)<label for="id_(.*?)">(.*)</label>(.*)$')
hidden_re = re.compile(r'(<input type="hidden".* />)', re.DOTALL)
class BoundFormSet(StrAndUnicode):
def __init__(self, field, formset, name, args):
self.field = field
self.formset = formset
self.name = name
self.args = args
if self.field.label is None:
self.label = pretty_name(name)
else:
self.label = self.field.label
self.auto_id = self.formset.auto_id % self.formset.prefix
if args.has_key('attrs'):
self.attrs = args['attrs'].copy()
else:
self.attrs = {}
def __unicode__(self):
"""Renders this field as an HTML widget."""
return self.as_widget()
def as_widget(self, attrs=None):
"""
Renders the field by rendering the passed widget, adding any HTML
attributes passed as attrs. If no widget is specified, then the
field's default widget will be used.
"""
attrs = attrs or {}
auto_id = self.auto_id
if auto_id and 'id' not in attrs and not self.args.has_key('id'):
attrs['id'] = auto_id
try:
data = self.formset.as_table()
name = self.name
return self.render(name, data, attrs=attrs)
except Exception, e:
import traceback
return traceback.format_exc()
def render(self, name, value, attrs=None):
table_sections = table_sections_re.search(value).groups()
output = []
heads = []
current_row = []
first_row = True
first_head_id = None
prefix = 'id_%s-%%s-' % self.formset.prefix
for row, head, item in table_row_re.findall(table_sections[1]):
if first_row:
head_groups = label_re.search(head).groups()
if first_head_id == head_groups[1]:
first_row = False
output.append(current_row)
current_row = []
else:
heads.append('%s%s%s' % (head_groups[0], head_groups[2], head_groups[3]))
if first_head_id is None:
first_head_id = head_groups[1].replace('-0-','-1-')
current_row.append(item)
if not first_row and len(current_row) >= len(heads):
output.append(current_row)
current_row = []
if len(current_row) != 0:
raise Exception('Unbalanced render')
return mark_safe(u'%s<table%s><tr>%s</tr><tr>%s</tr></table>%s'%(
table_sections[0],
flatatt(attrs),
u''.join(heads),
u'</tr><tr>'.join((u''.join(x) for x in output)),
table_sections[2]))
class CachedQuerySet(object):
def __init__(self, get_queryset):
self.queryset_results = (x for x in get_queryset())
def __call__(self):
return self.queryset_results
class FormWithSetsInstance(object):
def __init__(self, master, form, formsets):
self.master = master
self.form = form
self.formsets = formsets
self.instance = form.instance
def __unicode__(self):
return self.as_table()
def is_valid(self):
result = self.form.is_valid()
for bf in self.formsets:
result = bf.formset.is_valid() and result
return result
def save(self, *args, **kwargs):
def save_forms(forms, obj=None):
for form in forms:
if not instance and form != self.form:
for row in form.forms:
row.cleaned_data[form.rel_name] = obj
form_obj = form.save(*args, **kwargs)
if form == self.form:
obj = form_obj
return obj
instance = self.form.instance
grouped = []
ungrouped = []
# cache the result of get_queryset so that it doesn't run inside the transaction
for bf in self.formsets:
if bf.formset.rel_name == 'parent':
grouped.append(bf.formset)
else:
ungrouped.append(bf.formset)
bf.formset_get_queryset = bf.formset.get_queryset
bf.formset.get_queryset = CachedQuerySet(bf.formset_get_queryset)
if grouped:
grouped.insert(0, self.form)
else:
ungrouped.insert(0, self.form)
obj = None
if grouped:
obj = db.run_in_transaction(save_forms, grouped)
obj = save_forms(ungrouped, obj)
for bf in self.formsets:
bf.formset.get_queryset = bf.formset_get_queryset
del bf.formset_get_queryset
return obj
def _html_output(self, form_as, normal_row, help_text_html, sections_re, row_re):
formsets = SortedDict()
for bf in self.formsets:
if bf.label:
label = conditional_escape(force_unicode(bf.label))
# Only add the suffix if the label does not end in
# punctuation.
if self.form.label_suffix:
if label[-1] not in ':?.!':
label += self.form.label_suffix
label = label or ''
else:
label = ''
if bf.field.help_text:
help_text = help_text_html % force_unicode(bf.field.help_text)
else:
help_text = u''
formsets[bf.name] = {'label': force_unicode(label), 'field': unicode(bf), 'help_text': help_text}
try:
output = []
data = form_as()
section_search = sections_re.search(data)
if formsets:
hidden = u''.join(hidden_re.findall(data))
last_formset_name, last_formset = formsets.items()[-1]
last_formset['field'] = last_formset['field'] + hidden
formsets[last_formset_name] = normal_row % last_formset
for name, formset in formsets.items()[:-1]:
formsets[name] = normal_row % formset
if not section_search:
output.append(data)
else:
section_groups = section_search.groups()
for row, head, item in row_re.findall(section_groups[1]):
head_search = label_re.search(head)
if head_search:
id = head_search.groups()[1]
if formsets.has_key(id):
row = formsets[id]
del formsets[id]
output.append(row)
for name, row in formsets.items():
if name in self.form.fields.keyOrder:
output.append(row)
return mark_safe(u'\n'.join(output))
except Exception,e:
import traceback
return traceback.format_exc()
def as_table(self):
"Returns this form rendered as HTML <tr>s -- excluding the <table></table>."
return self._html_output(self.form.as_table, u'<tr><th>%(label)s</th><td>%(help_text)s%(field)s</td></tr>', u'<br />%s', table_sections_re, table_row_re)
def as_ul(self):
"Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
return self._html_output(self.form.as_ul, u'<li>%(label)s %(help_text)s%(field)s</li>', u' %s', ul_sections_re, ul_row_re)
def as_p(self):
"Returns this form rendered as HTML <p>s."
return self._html_output(self.form.as_p, u'<p>%(label)s %(help_text)s</p>%(field)s', u' %s', p_sections_re, p_row_re)
def full_clean(self):
self.form.full_clean()
for bf in self.formsets:
bf.formset.full_clean()
def has_changed(self):
result = self.form.has_changed()
for bf in self.formsets:
result = bf.formset.has_changed() or result
return result
def is_multipart(self):
result = self.form.is_multipart()
for bf in self.formsets:
result = bf.formset.is_multipart() or result
return result
@property
def media(self):
return mark_safe(unicode(self.form.media) + u'\n'.join([unicode(f.formset.media) for f in self.formsets]))
from django.forms.fields import Field
from django.forms.widgets import Widget
from django.forms.models import inlineformset_factory
class FormSetWidget(Widget):
def __init__(self, field, attrs=None):
super(FormSetWidget, self).__init__(attrs)
self.field = field
def render(self, name, value, attrs=None):
if value is None: value = 'FormWithSets decorator required to render %s FormSet' % self.field.model.__name__
value = force_unicode(value)
final_attrs = self.build_attrs(attrs, name=name)
return mark_safe(conditional_escape(value))
class FormSetField(Field):
def __init__(self, model, widget=FormSetWidget, label=None, initial=None,
help_text=None, error_messages=None, show_hidden_initial=False,
formset_factory=inlineformset_factory, *args, **kwargs):
widget = widget(self)
super(FormSetField, self).__init__(required=False, widget=widget, label=label, initial=initial, help_text=help_text, error_messages=error_messages, show_hidden_initial=show_hidden_initial)
self.model = model
self.formset_factory = formset_factory
self.args = args
self.kwargs = kwargs
def make_formset(self, parent_model):
return self.formset_factory(parent_model, self.model, *self.args, **self.kwargs)
| Python |
# -*- coding: utf-8 -*-
from copy import deepcopy
from django.forms.forms import NON_FIELD_ERRORS
from django.template import Library
from django.utils.datastructures import SortedDict
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from ragendja.dbutils import prefetch_references
register = Library()
register.filter('prefetch_references', prefetch_references)
_js_escapes = {
'>': r'\x3E',
'<': r'\x3C',
'&': r'\x26',
'=': r'\x3D',
'-': r'\x2D',
';': r'\x3B',
}
@register.filter
def encodejs(value):
from django.utils import simplejson
from ragendja.json import LazyEncoder
value = simplejson.dumps(value, cls=LazyEncoder)
for bad, good in _js_escapes.items():
value = value.replace(bad, good)
return mark_safe(value)
@register.filter
def urlquerybase(url):
"""
Appends '?' or '&' to an url, so you can easily add extra GET parameters.
"""
if url:
if '?' in url:
url += '&'
else:
url += '?'
return url
@register.simple_tag
def htrans(value):
"""
Creates a "hidden" translation.
Translates a string, but doesn't add it to django.po. This is useful
if you use the same string in multiple apps and don't want to translate
it in each of them (the translations will get overriden by the last app,
anyway).
"""
return _(value)
@register.simple_tag
def exclude_form_fields(form=None, fields=None, as_choice='as_table',
global_errors=True):
fields=fields.replace(' ', '').split(',')
if not global_errors:
form.errors[NON_FIELD_ERRORS] = form.error_class()
fields_backup = deepcopy(form.fields)
for field in fields:
if field in form.fields:
del form.fields[field]
resulting_text = getattr(form, as_choice)()
form.fields = fields_backup
return resulting_text
@register.simple_tag
def include_form_fields(form=None, fields=None, as_choice='as_table',
global_errors=True):
fields=fields.replace(' ', '').split(',')
if not global_errors:
form.errors[NON_FIELD_ERRORS] = form.error_class()
fields_backup = deepcopy(form.fields)
form.fields = SortedDict()
for field in fields:
if field in fields_backup:
form.fields[field] = fields_backup[field]
resulting_text = getattr(form, as_choice)()
form.fields = fields_backup
return resulting_text
@register.simple_tag
def ordered_form(form=None, fields=None, as_choice='as_table'):
resulting_text = ''
if len(form.non_field_errors()) != 0:
fields_backup = deepcopy(form.fields)
form.fields = {}
resulting_text = getattr(form, as_choice)()
form.fields = fields_backup
resulting_text = resulting_text + include_form_fields(form, fields,
as_choice, False) + exclude_form_fields(form, fields, as_choice, False)
return resulting_text
| Python |
# -*- coding: utf-8 -*-
from django.conf import settings
from django.template import Library
from django.utils.html import escape
from google.appengine.api import users
register = Library()
@register.simple_tag
def google_login_url(redirect=settings.LOGIN_REDIRECT_URL):
return escape(users.create_login_url(redirect))
@register.simple_tag
def google_logout_url(redirect='/'):
prefixes = getattr(settings, 'LOGIN_REQUIRED_PREFIXES', ())
if any(redirect.startswith(prefix) for prefix in prefixes):
redirect = '/'
return escape(users.create_logout_url(redirect))
| Python |
from django.contrib.auth.models import *
from django.contrib.auth.models import DjangoCompatibleUser as User
| Python |
# -*- coding: utf-8 -*-
"""
Provides basic set of auth urls.
"""
from django.conf.urls.defaults import *
from django.conf import settings
urlpatterns = patterns('')
LOGIN = '^%s$' % settings.LOGIN_URL.lstrip('/')
LOGOUT = '^%s$' % settings.LOGOUT_URL.lstrip('/')
# If user set a LOGOUT_REDIRECT_URL we do a redirect.
# Otherwise we display the default template.
LOGOUT_DATA = {'next_page': getattr(settings, 'LOGOUT_REDIRECT_URL', None)}
# register auth urls depending on whether we use google or hybrid auth
if 'ragendja.auth.middleware.GoogleAuthenticationMiddleware' in \
settings.MIDDLEWARE_CLASSES:
urlpatterns += patterns('',
url(LOGIN, 'ragendja.auth.views.google_login',
name='django.contrib.auth.views.login'),
url(LOGOUT, 'ragendja.auth.views.google_logout', LOGOUT_DATA,
name='django.contrib.auth.views.logout'),
)
elif 'ragendja.auth.middleware.HybridAuthenticationMiddleware' in \
settings.MIDDLEWARE_CLASSES:
urlpatterns += patterns('',
url(LOGIN, 'ragendja.auth.views.hybrid_login',
name='django.contrib.auth.views.login'),
url(LOGOUT, 'ragendja.auth.views.hybrid_logout', LOGOUT_DATA,
name='django.contrib.auth.views.logout'),
)
# When faking a real function we always have to add the real function, too.
urlpatterns += patterns('',
url(LOGIN, 'django.contrib.auth.views.login'),
url(LOGOUT, 'django.contrib.auth.views.logout', LOGOUT_DATA,),
)
| Python |
# -*- coding: utf-8 -*-
from google.appengine.api import users
def google_user(request):
return {'google_user': users.get_current_user()}
| Python |
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from google.appengine.api import users
from google.appengine.ext import db
from ragendja.auth.models import EmailUserTraits
class GoogleUserTraits(EmailUserTraits):
@classmethod
def get_djangouser_for_user(cls, user):
django_user = cls.all().filter('user_id = ', user.user_id()).get()
if not django_user:
django_user = cls.all().filter('user = ', user).get()
if not django_user:
django_user = cls.create_djangouser_for_user(user)
django_user.is_active = True
user_put = False
if django_user.user != user:
django_user.user = user
user_put = True
user_id = user.user_id()
if django_user.user_id != user_id:
django_user.user_id = user_id
user_put = True
if getattr(settings, 'AUTH_ADMIN_USER_AS_SUPERUSER', True):
is_admin = users.is_current_user_admin()
if django_user.is_staff != is_admin or django_user.is_superuser != is_admin:
django_user.is_superuser = django_user.is_staff = is_admin
user_put = True
if not django_user.is_saved() or user_put:
django_user.put()
return django_user
class Meta:
abstract = True
class User(GoogleUserTraits):
"""Extended User class that provides support for Google Accounts."""
user = db.UserProperty(required=True)
user_id = db.StringProperty()
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
@property
def username(self):
return self.user.nickname()
@property
def email(self):
return self.user.email()
@classmethod
def create_djangouser_for_user(cls, user):
return cls(user=user, user_id=user.user_id())
| Python |
# -*- coding: utf-8 -*-
from django.contrib.auth.decorators import login_required
from functools import wraps
from ragendja.auth.views import google_redirect_to_login
from ragendja.template import render_to_response
def staff_only(view):
"""
Decorator that requires user.is_staff. Otherwise renders no_access.html.
"""
@login_required
def wrapped(request, *args, **kwargs):
if request.user.is_active and request.user.is_staff:
return view(request, *args, **kwargs)
return render_to_response(request, 'no_access.html')
return wraps(view)(wrapped)
def google_login_required(function):
def login_required_wrapper(request, *args, **kw):
if request.user.is_authenticated():
return function(request, *args, **kw)
return google_redirect_to_login(request.get_full_path())
return wraps(function)(login_required_wrapper)
| Python |
# -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.views import login, logout
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext as _
from google.appengine.api import users
from ragendja.template import render_to_response
def get_redirect_to(request, redirect_field_name):
redirect_to = request.REQUEST.get(redirect_field_name)
# Light security check -- make sure redirect_to isn't garbage.
if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
redirect_to = settings.LOGIN_REDIRECT_URL
return redirect_to
def google_login(request, template_name=None,
redirect_field_name=REDIRECT_FIELD_NAME):
redirect_to = get_redirect_to(request, redirect_field_name)
return HttpResponseRedirect(users.create_login_url(redirect_to))
def hybrid_login(request, template_name='registration/login.html',
redirect_field_name=REDIRECT_FIELD_NAME):
# Don't login using both authentication systems at the same time
if request.user.is_authenticated():
redirect_to = get_redirect_to(request, redirect_field_name)
return HttpResponseRedirect(redirect_to)
return login(request, template_name, redirect_field_name)
def google_logout(request, next_page=None,
template_name='registration/logged_out.html'):
if users.get_current_user():
# Redirect to this page until the session has been cleared.
logout_url = users.create_logout_url(next_page or request.path)
return HttpResponseRedirect(logout_url)
if not next_page:
return render_to_response(request, template_name,
{'title': _('Logged out')})
return HttpResponseRedirect(next_page)
def hybrid_logout(request, next_page=None,
template_name='registration/logged_out.html'):
if users.get_current_user():
return google_logout(request, next_page)
return logout(request, next_page, template_name)
def google_logout_then_login(request, login_url=None):
if not login_url:
login_url = settings.LOGIN_URL
return google_logout(request, login_url)
def hybrid_logout_then_login(request, login_url=None):
if not login_url:
login_url = settings.LOGIN_URL
return hybrid_logout(request, login_url)
def google_redirect_to_login(next, login_url=None, redirect_field_name=None):
return HttpResponseRedirect(users.create_login_url(next))
| Python |
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
class UserAdmin(admin.ModelAdmin):
fieldsets = (
(_('Personal info'), {'fields': ('user',)}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'user_permissions')}),
(_('Important dates'), {'fields': ('date_joined',)}),
(_('Groups'), {'fields': ('groups',)}),
)
list_display = ('email', 'username', 'is_staff')
list_filter = ('is_staff', 'is_superuser', 'is_active')
search_fields = ('user',)
filter_horizontal = ('user_permissions',)
| Python |
# Parts of this code are taken from Google's django-helper (license: Apache 2)
class LazyGoogleUser(object):
def __init__(self, middleware_class):
self._middleware_class = middleware_class
def __get__(self, request, obj_type=None):
if not hasattr(request, '_cached_user'):
from django.contrib.auth import get_user
from django.contrib.auth.models import AnonymousUser, User
from google.appengine.api import users
if self._middleware_class is HybridAuthenticationMiddleware:
request._cached_user = get_user(request)
else:
request._cached_user = AnonymousUser()
if request._cached_user.is_anonymous():
user = users.get_current_user()
if user:
request._cached_user = User.get_djangouser_for_user(user)
return request._cached_user
class GoogleAuthenticationMiddleware(object):
def process_request(self, request):
request.__class__.user = LazyGoogleUser(self.__class__)
class HybridAuthenticationMiddleware(GoogleAuthenticationMiddleware):
pass
| Python |
from django.utils.translation import ugettext_lazy as _
from google.appengine.ext import db
from ragendja.auth.google_models import GoogleUserTraits
class User(GoogleUserTraits):
"""User class that provides support for Django and Google Accounts."""
user = db.UserProperty()
user_id = db.StringProperty()
username = db.StringProperty(required=True, verbose_name=_('username'))
email = db.EmailProperty(verbose_name=_('e-mail address'))
first_name = db.StringProperty(verbose_name=_('first name'))
last_name = db.StringProperty(verbose_name=_('last name'))
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
@classmethod
def create_djangouser_for_user(cls, user):
return cls(user=user, email=user.email(), username=user.email(), user_id=user.user_id())
| Python |
# -*- coding: utf-8 -*-
"""
This is a set of utilities for faster development with Django templates.
render_to_response() and render_to_string() use RequestContext internally.
The app_prefixed_loader is a template loader that loads directly from the app's
'templates' folder when you specify an app prefix ('app/template.html').
The JSONResponse() function automatically converts a given Python object into
JSON and returns it as an HttpResponse.
"""
from django.conf import settings
from django.http import HttpResponse
from django.template import RequestContext, loader, \
TemplateDoesNotExist, Library, Node, Variable, generic_tag_compiler
from django.utils.functional import curry
from inspect import getargspec
from ragendja.apputils import get_app_dirs
import os
class Library(Library):
def context_tag(self, func):
params, xx, xxx, defaults = getargspec(func)
class ContextNode(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]
return func(context, *resolved_vars)
params = params[1:]
compile_func = curry(generic_tag_compiler, params, defaults, getattr(func, "_decorated_function", func).__name__, ContextNode)
compile_func.__doc__ = func.__doc__
self.tag(getattr(func, "_decorated_function", func).__name__, compile_func)
return func
# The following defines a template loader that loads templates from a specific
# app based on the prefix of the template path:
# get_template("app/template.html") => app/templates/template.html
# This keeps the code DRY and prevents name clashes.
def app_prefixed_loader(template_name, template_dirs=None):
packed = template_name.split('/', 1)
if len(packed) == 2 and packed[0] in app_template_dirs:
path = os.path.join(app_template_dirs[packed[0]], packed[1])
try:
return (open(path).read().decode(settings.FILE_CHARSET), path)
except IOError:
pass
raise TemplateDoesNotExist, template_name
app_prefixed_loader.is_usable = True
def render_to_string(request, template_name, data=None):
return loader.render_to_string(template_name, data,
context_instance=RequestContext(request))
def render_to_response(request, template_name, data=None, mimetype=None):
if mimetype is None:
mimetype = settings.DEFAULT_CONTENT_TYPE
original_mimetype = mimetype
if mimetype == 'application/xhtml+xml':
# Internet Explorer only understands XHTML if it's served as text/html
if request.META.get('HTTP_ACCEPT').find(mimetype) == -1:
mimetype = 'text/html'
response = HttpResponse(render_to_string(request, template_name, data),
content_type='%s; charset=%s' % (mimetype, settings.DEFAULT_CHARSET))
if original_mimetype == 'application/xhtml+xml':
# Since XHTML is served with two different MIME types, depending on the
# browser, we need to tell proxies to serve different versions.
from django.utils.cache import patch_vary_headers
patch_vary_headers(response, ['User-Agent'])
return response
def JSONResponse(pyobj):
from ragendja.json import JSONResponse as real_class
global JSONResponse
JSONResponse = real_class
return JSONResponse(pyobj)
def TextResponse(string=''):
return HttpResponse(string,
content_type='text/plain; charset=%s' % settings.DEFAULT_CHARSET)
# This is needed by app_prefixed_loader.
app_template_dirs = get_app_dirs('templates')
| Python |
# -*- coding: utf-8 -*-
from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder
from django.http import HttpResponse
from django.utils import simplejson
from django.utils.encoding import force_unicode
from django.utils.functional import Promise
class LazyEncoder(DjangoJSONEncoder):
def default(self, obj):
if isinstance(obj, Promise):
return force_unicode(obj)
return super(LazyEncoder, self).default(obj)
class JSONResponse(HttpResponse):
def __init__(self, pyobj, **kwargs):
super(JSONResponse, self).__init__(
simplejson.dumps(pyobj, cls=LazyEncoder),
content_type='application/json; charset=%s' %
settings.DEFAULT_CHARSET,
**kwargs)
| Python |
# -*- coding: utf-8 -*-
from django.http import HttpRequest
class RegisterVars(dict):
"""
This class provides a simplified mechanism to build context processors
that only add variables or functions without processing a request.
Your module should have a global instance of this class called 'register'.
You can then add the 'register' variable as a context processor in your
settings.py.
How to use:
>>> register = RegisterVars()
>>> def func():
... pass
>>> register(func) # doctest:+ELLIPSIS
<function func at ...>
>>> @register
... def otherfunc():
... pass
>>> register['otherfunc'] is otherfunc
True
Alternatively you can specify the name of the function with either of:
def func(...): ...
register(func, 'new_name')
@register('new_name')
def ...
You can even pass a dict or RegisterVars instance:
register(othermodule.register)
register({'myvar': myvar})
"""
def __call__(self, item=None, name=None):
# Allow for using a RegisterVars instance as a context processor
if isinstance(item, HttpRequest):
return self
if name is None and isinstance(item, basestring):
# @register('as_name') # first param (item) contains the name
name, item = item, name
elif name is None and isinstance(item, dict):
# register(somedict) or register(othermodule.register)
return self.update(item)
if item is None and isinstance(name, basestring):
# @register(name='as_name')
return lambda func: self(func, name)
self[name or item.__name__] = item
return item
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.