code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
from zope.interface import implements
from nevow import tags as T, util
from formal import iformal
from formal.util import render_cssid
class TextAreaWithSelect(object):
"""
A large text entry area that accepts newline characters.
<textarea>...</textarea>
"""
implements( iformal.IWidget )
cols = 48
rows = 6
def __init__(self, original, cols=None, rows=None, values=None):
self.original = original
self.values = values
if cols is not None:
self.cols = cols
if rows is not None:
self.rows = rows
def _renderTag(self, ctx, key, value, readonly):
html = []
tag=T.textarea(name=key, id=render_cssid(key), cols=self.cols, rows=self.rows)[value or '']
if readonly:
tag(class_='readonly', readonly='readonly')
html.append(tag)
if self.values is None:
return html
def renderOptions(ctx,options):
for value,label in options:
yield T.option(value=value)[label]
selecttrigger = T.select(name='%s__selecttrigger'%key, data=self.values)[ renderOptions ]
form = iformal.IForm( ctx )
js = T.xml("var x = document.getElementById('%(form)s');x.%(key)s.value += x.%(key)s__selecttrigger.options[x.%(key)s__selecttrigger.options.selectedIndex].value + "\\n";"%{'key':key,'form':form.name})
aonclick = T.a(onclick=js)[ 'add' ]
html.append(T.div(class_="add")[selecttrigger,aonclick])
return html
def render(self, ctx, key, args, errors):
if errors:
value = args.get(key, [''])[0]
else:
value = iformal.IStringConvertible(self.original).fromType(args.get(key))
return self._renderTag(ctx, key, value, False)
def renderImmutable(self, ctx, key, args, errors):
value = iformal.IStringConvertible(self.original).fromType(args.get(key))
return self._renderTag(ctx, key, value, True)
def processInput(self, ctx, key, args):
value = args.get(key, [''])[0].decode(util.getPOSTCharset(ctx))
value = iformal.IStringConvertible(self.original).fromType(value)
return self.original.validate(value)
| Python |
"""Adapters for converting to and from a type's value according to an
IConvertible protocol.
"""
from datetime import date, time
try:
import decimal
haveDecimal = True
except ImportError:
haveDecimal = False
from formal import iformal, validation
from zope.interface import implements
class _Adapter(object):
def __init__(self, original):
self.original = original
class NullConverter(_Adapter):
implements( iformal.IStringConvertible )
def fromType(self, value):
if value is None:
return None
return value
def toType(self, value):
if value is None:
return None
return value
class NumberToStringConverter(_Adapter):
implements( iformal.IStringConvertible )
cast = None
def fromType(self, value):
if value is None:
return None
return str(value)
def toType(self, value):
if value is not None:
value = value.strip()
if not value:
return None
# "Cast" the value to the correct type. For some strange reason,
# Python's decimal.Decimal type raises an ArithmeticError when it's
# given a dodgy value.
try:
value = self.cast(value)
except (ValueError, ArithmeticError):
raise validation.FieldValidationError("Not a valid number")
return value
class IntegerToStringConverter(NumberToStringConverter):
cast = int
class FloatToStringConverter(NumberToStringConverter):
cast = float
if haveDecimal:
class DecimalToStringConverter(NumberToStringConverter):
cast = decimal.Decimal
class BooleanToStringConverter(_Adapter):
implements( iformal.IStringConvertible )
def fromType(self, value):
if value is None:
return None
if value:
return 'True'
return 'False'
def toType(self, value):
if value is not None:
value = value.strip()
if not value:
return None
if value not in ('True', 'False'):
raise validation.FieldValidationError('%r should be either True or False'%value)
return value == 'True'
class DateToStringConverter(_Adapter):
implements( iformal.IStringConvertible )
def fromType(self, value):
if value is None:
return None
return value.isoformat()
def toType(self, value):
if value is not None:
value = value.strip()
if not value:
return None
return self.parseDate(value)
def parseDate(self, value):
try:
y, m, d = [int(p) for p in value.split('-')]
except ValueError:
raise validation.FieldValidationError('Invalid date')
try:
value = date(y, m, d)
except ValueError, e:
raise validation.FieldValidationError('Invalid date: '+str(e))
return value
class TimeToStringConverter(_Adapter):
implements( iformal.IStringConvertible )
def fromType(self, value):
if value is None:
return None
return value.isoformat()
def toType(self, value):
if value is not None:
value = value.strip()
if not value:
return None
return self.parseTime(value)
def parseTime(self, value):
if '.' in value:
value, ms = value.split('.')
else:
ms = 0
try:
parts = value.split(':')
if len(parts)<2 or len(parts)>3:
raise ValueError()
if len(parts) == 2:
h, m = parts
s = 0
else:
h, m, s = parts
h, m, s, ms = int(h), int(m), int(s), int(ms)
except:
raise validation.FieldValidationError('Invalid time')
try:
value = time(h, m, s, ms)
except ValueError, e:
raise validation.FieldValidationError('Invalid time: '+str(e))
return value
class DateToDateTupleConverter(_Adapter):
implements( iformal.IDateTupleConvertible )
def fromType(self, value):
if value is None:
return None, None, None
return value.year, value.month, value.day
def toType(self, value):
if value is None:
return None
try:
value = date(*value)
except (TypeError, ValueError), e:
raise validation.FieldValidationError('Invalid date: '+str(e))
return value
class SequenceToStringConverter(_Adapter):
implements( iformal.IStringConvertible)
def fromType(self, value):
if value is None:
return None
import cStringIO as StringIO
import csv
sf = StringIO.StringIO()
writer = csv.writer(sf)
writer.writerow(value)
sf.seek(0,0)
return sf.read().strip()
def toType(self, value):
if not value:
return None
import cStringIO as StringIO
import csv
sf = StringIO.StringIO()
csvReader = csv.reader(sf)
sf.write(value)
sf.seek(0,0)
return csvReader.next()
| Python |
import re
from zope.interface import implements
from nevow import inevow, tags
from formal import iformal
_IDENTIFIER_REGEX = re.compile('^[a-zA-Z_][a-zA-Z0-9_]*$')
def titleFromName(name):
def _():
it = iter(name)
last = None
while 1:
ch = it.next()
if ch == '_':
if last != '_':
yield ' '
elif last in (None,'_'):
yield ch.upper()
elif ch.isupper() and not last.isupper():
yield ' '
yield ch.upper()
else:
yield ch
last = ch
return ''.join(_())
def keytocssid(fieldKey, *extras):
return render_cssid(fieldKey, *extras)
def render_cssid(fieldKey, *extras):
"""
Render the CSS id for the form field's key.
"""
l = [tags.slot('formName'), '-', '-'.join(fieldKey.split('.'))]
for extra in extras:
l.append('-')
l.append(extra)
return l
def validIdentifier(name):
"""
Test that name is a valid Python identifier.
"""
return _IDENTIFIER_REGEX.match(name) is not None
class SequenceKeyLabelAdapter(object):
implements( iformal.IKey, iformal.ILabel )
def __init__(self, original):
self.original = original
def key(self):
return self.original[0]
def label(self):
return self.original[1]
class LazyResource(object):
implements(inevow.IResource)
def __init__(self, factory):
self.factory = factory
self._resource = None
def locateChild(self, ctx, segments):
return self.resource().locateChild(ctx, segments)
def renderHTTP(self, ctx):
return self.resource().renderHTTP(ctx)
def resource(self):
if self._resource is None:
self._resource = self.factory()
return self._resource
| Python |
"""
Widgets are small components that render form fields for inputing data in a
certain format.
"""
import itertools
from nevow import inevow, loaders, tags as T, util, url, static, rend
from nevow.i18n import _
from formal import converters, iformal, validation
from formal.util import render_cssid
from formal.form import widgetResourceURL, widgetResourceURLFromContext
from zope.interface import implements
from twisted.internet import defer
# Marker object for args that are not supplied
_UNSET = object()
class TextInput(object):
"""
A text input field.
<input type="text" ... />
"""
implements( iformal.IWidget )
inputType = 'text'
showValueOnFailure = True
def __init__(self, original):
self.original = original
def _renderTag(self, ctx, key, value, readonly):
tag=T.input(type=self.inputType, name=key, id=render_cssid(key), value=value)
if readonly:
tag(class_='readonly', readonly='readonly')
return tag
def render(self, ctx, key, args, errors):
if errors:
value = args.get(key, [''])[0]
else:
value = iformal.IStringConvertible(self.original).fromType(args.get(key))
if not self.showValueOnFailure:
value = None
return self._renderTag(ctx, key, value, False)
def renderImmutable(self, ctx, key, args, errors):
value = iformal.IStringConvertible(self.original).fromType(args.get(key))
return self._renderTag(ctx, key, value, True)
def processInput(self, ctx, key, args):
value = args.get(key, [''])[0].decode(util.getPOSTCharset(ctx))
value = iformal.IStringConvertible(self.original).toType(value)
return self.original.validate(value)
class Checkbox(object):
"""
A checkbox input field.
<input type="checkbox" ... />
"""
implements( iformal.IWidget )
def __init__(self, original):
self.original = original
def _renderTag(self, ctx, key, value, disabled):
tag = T.input(type='checkbox', name=key, id=render_cssid(key), value='True')
if value == 'True':
tag(checked='checked')
if disabled:
tag(class_='disabled', disabled='disabled')
return tag
def render(self, ctx, key, args, errors):
if errors:
value = args.get(key, [''])[0]
else:
value = iformal.IBooleanConvertible(self.original).fromType(args.get(key))
return self._renderTag(ctx, key, value, False)
def renderImmutable(self, ctx, key, args, errors):
value = iformal.IBooleanConvertible(self.original).fromType(args.get(key))
return self._renderTag(ctx, key, value, True)
def processInput(self, ctx, key, args):
value = args.get(key, [None])[0]
if not value:
value = 'False'
value = iformal.IBooleanConvertible(self.original).toType(value)
return self.original.validate(value)
class Password(TextInput):
"""
A text input field that hides the text.
<input type="password" ... />
"""
inputType = 'password'
showValueOnFailure = False
class TextArea(object):
"""
A large text entry area that accepts newline characters.
<textarea>...</textarea>
"""
implements( iformal.IWidget )
cols = 48
rows = 6
def __init__(self, original, cols=None, rows=None):
self.original = original
if cols is not None:
self.cols = cols
if rows is not None:
self.rows = rows
def _renderTag(self, ctx, key, value, readonly):
tag=T.textarea(name=key, id=render_cssid(key), cols=self.cols, rows=self.rows)[value or '']
if readonly:
tag(class_='readonly', readonly='readonly')
return tag
def render(self, ctx, key, args, errors):
if errors:
value = args.get(key, [''])[0]
else:
value = iformal.IStringConvertible(self.original).fromType(args.get(key))
return self._renderTag(ctx, key, value, False)
def renderImmutable(self, ctx, key, args, errors):
value = iformal.IStringConvertible(self.original).fromType(args.get(key))
return self._renderTag(ctx, key, value, True)
def processInput(self, ctx, key, args):
value = args.get(key, [''])[0].decode(util.getPOSTCharset(ctx))
value = iformal.IStringConvertible(self.original).fromType(value)
return self.original.validate(value)
class TextAreaList(object):
"""
A text area that allows a list of values to be entered, one per line. Any
empty lines are discarded.
"""
implements( iformal.IWidget )
cols = 48
rows = 6
def __init__(self, original, cols=None, rows=None):
self.original = original
if cols is not None:
self.cols = cols
if rows is not None:
self.rows = rows
def _renderTag(self, ctx, key, values, readonly):
value = '\n'.join(values)
tag=T.textarea(name=key, id=render_cssid(key), cols=self.cols, rows=self.rows)[value]
if readonly:
tag(class_='readonly', readonly='readonly')
return tag
def render(self, ctx, key, args, errors):
converter = iformal.IStringConvertible(self.original.type)
if errors:
values = args.get(key, [])
else:
values = args.get(key)
if values is not None:
values = [converter.fromType(v) for v in values]
else:
values = []
return self._renderTag(ctx, key, values, False)
def renderImmutable(self, ctx, key, args, errors):
converter = iformal.IStringConvertible(self.original.type)
values = args.get(key)
if values is not None:
values = [converter.fromType(v) for v in values]
else:
values = []
return self._renderTag(ctx, key, values, True)
def processInput(self, ctx, key, args):
# Get the whole string
value = args.get(key, [''])[0].decode(util.getPOSTCharset(ctx))
# Split into lines
values = value.splitlines()
# Strip each line
values = [v.strip() for v in values]
# Discard empty lines
values = [v for v in values if v]
# Convert values to correct type
converter = iformal.IStringConvertible(self.original.type)
values = [converter.toType(v) for v in values]
# Validate and return
return self.original.validate(values)
class CheckedPassword(object):
"""
Two password entry fields that must contain the same value to validate.
"""
implements( iformal.IWidget )
def __init__(self, original):
self.original = original
def render(self, ctx, key, args, errors):
if errors and not errors.getFieldError(key):
values = args.get(key)
else:
values = ('', '')
return [
T.input(type='password', name=key, id=render_cssid(key), value=values[0]),
T.br,
T.label(for_=render_cssid(key, 'confirm'))[' Confirm '],
T.input(type='password', name=key, id=render_cssid(key, 'confirm'), value=values[1]),
]
def renderImmutable(self, ctx, key, args, errors):
values = ('', '')
return [
T.input(type='password', name=key, id=render_cssid(key), value=values[0], class_='readonly', readonly='readonly'),
T.br,
T.label(for_=render_cssid(key, 'confirm'))[' Confirm '],
T.input(type='password', name=key, id=render_cssid(key, 'confirm'),
value=values[1], class_='readonly', readonly='readonly')
]
def processInput(self, ctx, key, args):
charset = util.getPOSTCharset(ctx)
pwds = [pwd.decode(charset) for pwd in args.get(key, [])]
if len(pwds) == 0:
pwd = ''
elif len(pwds) == 1:
raise validation.FieldValidationError('Please enter the password twice for confirmation.')
else:
if pwds[0] != pwds[1]:
raise validation.FieldValidationError('Passwords do not match.')
return self.original.validate(pwds[0])
class ChoiceBase(object):
"""
A base class for widgets that provide the UI to select one or more items
from a list.
options:
A sequence of objects adaptable to IKey and ILabel. IKey is used as the
<option>'s value attribute; ILabel is used as the <option>'s child.
IKey and ILabel adapters for tuple are provided.
noneOption:
An object adaptable to IKey and ILabel that is used to identify when
nothing has been selected.
"""
options = None
noneOption = None
def __init__(self, original, options=None, noneOption=_UNSET):
self.original = original
if options is not None:
self.options = options
if noneOption is not _UNSET:
self.noneOption = noneOption
def processInput(self, ctx, key, args):
charset = util.getPOSTCharset(ctx)
value = args.get(key, [''])[0].decode(charset)
value = iformal.IStringConvertible(self.original).toType(value)
if self.noneOption is not None and \
value == iformal.IKey(self.noneOption).key():
value = None
return self.original.validate(value)
class SelectChoice(ChoiceBase):
"""
A drop-down list of options.
<select>
<option value="...">...</option>
</select>
"""
implements( iformal.IWidget )
noneOption = ('', '')
def _renderTag(self, ctx, key, value, converter, disabled):
def renderOptions(ctx, data):
if self.noneOption is not None:
yield T.option(value=iformal.IKey(self.noneOption).key())[iformal.ILabel(self.noneOption).label()]
if data is None:
return
for item in data:
optValue = iformal.IKey(item).key()
optLabel = iformal.ILabel(item).label()
optValue = converter.fromType(optValue)
option = T.option(value=optValue)[optLabel]
if optValue == value:
option = option(selected='selected')
yield option
tag=T.select(name=key, id=render_cssid(key), data=self.options)[renderOptions]
if disabled:
tag(class_='disabled', disabled='disabled')
return tag
def render(self, ctx, key, args, errors):
converter = iformal.IStringConvertible(self.original)
if errors:
value = args.get(key, [''])[0]
else:
value = converter.fromType(args.get(key))
return self._renderTag(ctx, key, value, converter, False)
def renderImmutable(self, ctx, key, args, errors):
converter = iformal.IStringConvertible(self.original)
value = converter.fromType(args.get(key))
return self._renderTag(ctx, key, value, converter, True)
class SelectOtherChoice(object):
"""
A <select> widget that includes an "Other ..." option. When the other
option is selected an <input> field is enabled to allow free text entry.
Unlike SelectChoice, the options items are not a (value,label) tuple
because that makes no sense with the free text entry facility.
TODO:
* Make the Other option configurable in the JS
* Refactor, refactor, refactor
"""
implements(iformal.IWidget)
options = None
noneOption = ('', '')
otherOption = ('...', 'Other ...')
template = None
def __init__(self, original, options=None, otherOption=None):
self.original = original
if options is not None:
self.options = options
if otherOption is not None:
self.otherOption = otherOption
if self.template is None:
self.template = loaders.xmlfile(util.resource_filename('formal',
'html/SelectOtherChoice.html'))
def _valueFromRequestArgs(self, charset, key, args):
value = args.get(key, [''])[0].decode(charset)
if value == self.otherOption[0]:
value = args.get(key+'-other', [''])[0].decode(charset)
return value
def render(self, ctx, key, args, errors):
return self._render(ctx, key, args, errors, False)
def renderImmutable(self, ctx, key, args, errors):
return self._render(ctx, key, args, errors, True)
def _render(self, ctx, key, args, errors, immutable):
charset = util.getPOSTCharset(ctx)
converter = iformal.IStringConvertible(self.original)
if errors:
value = self._valueFromRequestArgs(charset, key, args)
else:
value = converter.fromType(args.get(key))
if value is None:
value = iformal.IKey(self.noneOption).key()
if immutable:
template = inevow.IQ(self.template).onePattern('immutable')
else:
template = inevow.IQ(self.template).onePattern('editable')
optionGen = template.patternGenerator('option')
selectedOptionGen = template.patternGenerator('selectedOption')
optionTags = []
selectOther = True
if self.noneOption is not None:
noneValue = iformal.IKey(self.noneOption).key()
if value == noneValue:
tag = selectedOptionGen()
selectOther = False
else:
tag = optionGen()
tag.fillSlots('value', noneValue)
tag.fillSlots('label', iformal.ILabel(self.noneOption).label())
optionTags.append(tag)
if self.options is not None:
for item in self.options:
if value == item:
tag = selectedOptionGen()
selectOther = False
else:
tag = optionGen()
tag.fillSlots('value', item)
tag.fillSlots('label', item)
optionTags.append(tag)
if selectOther:
tag = selectedOptionGen()
otherValue = value
else:
tag = optionGen()
otherValue = ''
tag.fillSlots('value', self.otherOption[0])
tag.fillSlots('label', self.otherOption[1])
optionTags.append(tag)
tag = template
tag.fillSlots('key', key)
tag.fillSlots('id', render_cssid(key))
tag.fillSlots('options', optionTags)
tag.fillSlots('otherValue', otherValue)
return tag
def processInput(self, ctx, key, args):
charset = util.getPOSTCharset(ctx)
value = self._valueFromRequestArgs(charset, key, args)
value = iformal.IStringConvertible(self.original).toType(value)
if self.noneOption is not None and value == iformal.IKey(self.noneOption).key():
value = None
return self.original.validate(value)
class RadioChoice(ChoiceBase):
"""
A list of options in the form of radio buttons.
<div class="radiobutton"><input type="radio" ... value="..."/><label>...</label></div>
"""
implements( iformal.IWidget )
def _renderTag(self, ctx, key, value, converter, disabled):
def renderOption(ctx, itemKey, itemLabel, num, selected):
cssid = render_cssid(key, num)
tag = T.input(name=key, type='radio', id=cssid, value=itemKey)
if selected:
tag = tag(checked='checked')
if disabled:
tag = tag(disabled='disabled')
return T.div(class_='radiobutton')[ tag, T.label(for_=cssid)[itemLabel] ]
def renderOptions(ctx, data):
# A counter to assign unique ids to each input
idCounter = itertools.count()
if self.noneOption is not None:
itemKey = iformal.IKey(self.noneOption).key()
itemLabel = iformal.ILabel(self.noneOption).label()
yield renderOption(ctx, itemKey, itemLabel, idCounter.next(), itemKey==value)
if not data:
return
for item in data:
itemKey = iformal.IKey(item).key()
itemLabel = iformal.ILabel(item).label()
itemKey = converter.fromType(itemKey)
yield renderOption(ctx, itemKey, itemLabel, idCounter.next(), itemKey==value)
return T.invisible(data=self.options)[renderOptions]
def render(self, ctx, key, args, errors):
converter = iformal.IStringConvertible(self.original)
if errors:
value = args.get(key, [''])[0]
else:
value = converter.fromType(args.get(key))
return self._renderTag(ctx, key, value, converter, False)
def renderImmutable(self, ctx, key, args, errors):
converter = iformal.IStringConvertible(self.original)
value = converter.fromType(args.get(key))
return self._renderTag(ctx, key, value, converter, True)
class DatePartsSelect(object):
"""
A date entry widget that uses three <input> elements for the day, month and
year parts.
The default entry format is the US (month, day, year) but can be switched to
the more common (day, month, year) by setting the dayFirst attribute to
True.
The start and end year can be passed through but default to 1970 and 2070.
The months default to non-zero prefixed numerics but can be passed as a list
of label, value pairs
"""
implements( iformal.IWidget )
dayFirst = False
days = [ (d,d) for d in xrange(1,32) ]
months = [ (m,m) for m in xrange(1,13) ]
yearFrom = 1970
yearTo = 2070
noneOption = ('', '')
def __init__(self, original, dayFirst=None, yearFrom=None, yearTo=None, months=None, noneOption=_UNSET):
self.original = original
if dayFirst is not None:
self.dayFirst = dayFirst
if yearFrom is not None:
self.yearFrom = yearFrom
if yearTo is not None:
self.yearTo = yearTo
if months is not None:
self.months = months
if noneOption is not _UNSET:
self.noneOption = noneOption
def _namer(self, prefix):
def _(part):
return '%s__%s' % (prefix,part)
return _
def _renderTag(self, ctx, year, month, day, namer, readonly):
years = [(v,v) for v in xrange(self.yearFrom,self.yearTo)]
months = self.months
days = self.days
options = []
if self.noneOption is not None:
options.append( T.option(value=self.noneOption[0])[self.noneOption[1]] )
for value in years:
if str(value[0]) == str(year):
options.append( T.option(value=value[0],selected='selected')[value[1]] )
else:
options.append( T.option(value=value[0])[value[1]] )
yearTag = T.select(name=namer('year'))[ options ]
options = []
if self.noneOption is not None:
options.append( T.option(value=self.noneOption[0])[self.noneOption[1]] )
for value in months:
if str(value[0]) == str(month):
options.append( T.option(value=value[0],selected='selected')[value[1]] )
else:
options.append( T.option(value=value[0])[value[1]] )
monthTag = T.select(name=namer('month'))[ options ]
options = []
if self.noneOption is not None:
options.append( T.option(value=self.noneOption[0])[self.noneOption[1]] )
for value in days:
if str(value[0]) == str(day):
options.append( T.option(value=value[0],selected='selected')[value[1]] )
else:
options.append( T.option(value=value[0])[value[1]] )
dayTag = T.select(name=namer('day'))[ options ]
if readonly:
tags = (yearTag, monthTag, dayTag)
for tag in tags:
tag(class_='readonly', readonly='readonly')
if self.dayFirst:
return dayTag, ' / ', monthTag, ' / ', yearTag, ' ', _('(day/month/year)')
else:
return monthTag, ' / ', dayTag, ' / ', yearTag, ' ', _('(month/day/year)')
def render(self, ctx, key, args, errors):
converter = iformal.IDateTupleConvertible(self.original)
namer = self._namer(key)
if errors:
year = args.get(namer('year'), [''])[0]
month = args.get(namer('month'), [''])[0]
day = args.get(namer('day'), [''])[0]
else:
year, month, day = converter.fromType(args.get(key))
return self._renderTag(ctx, year, month, day, namer, False)
def renderImmutable(self, ctx, key, args, errors):
converter = iformal.IDateTupleConvertible(self.original)
namer = self._namer(key)
year, month, day = converter.fromType(args.get(key))
return self._renderTag(ctx, year, month, day, namer, True)
def processInput(self, ctx, key, args):
namer = self._namer(key)
# Get the form field values as a (y,m,d) tuple
ymd = [args.get(namer(part), [''])[0].strip() for part in ('year', 'month', 'day')]
# Remove parts that were not entered.
ymd = [p for p in ymd if p]
# Nothing entered means None otherwise we need all three.
if not ymd:
ymd = None
elif len(ymd) != 3:
raise validation.FieldValidationError("Invalid date")
# So, we have what looks like a good attempt to enter a date.
if ymd is not None:
# Map to integers
try:
ymd = [int(p) for p in ymd]
except ValueError, e:
raise validation.FieldValidationError("Invalid date")
ymd = iformal.IDateTupleConvertible(self.original).toType(ymd)
return self.original.validate(ymd)
class DatePartsInput(object):
"""
A date entry widget that uses three <input> elements for the day, month and
year parts.
The default entry format is the US (month, day, year) but can be switched to
the more common (day, month, year) by setting the dayFirst attribute to
True.
By default the widget is designed to only accept unambiguous years, i.e.
the user must enter 4 character dates.
Many people find it convenient or even necessary to allow a 2 character
year. This can be allowed by setting the twoCharCutoffYear attribute to an
integer value between 0 and 99. Anything greater than or equal to the cutoff
year will be considered part of the 20th century (1900 + year); anything
less the cutoff year is a 21st century (2000 + year) date.
A typical twoCharCutoffYear value is 70 (i.e. 1970). However, that value is
somewhat arbitrary. It's the year that time began according to the PC, but
it doesn't mean much to your non-techie user.
dayFirst:
Make the day the first input field, i.e. day, month, year
twoCharCutoffYear:
Allow 2 char years and set the year where the century flips between
20th and 21st century.
"""
implements( iformal.IWidget )
dayFirst = False
twoCharCutoffYear = None
def __init__(self, original, dayFirst=None, twoCharCutoffYear=None):
self.original = original
if dayFirst is not None:
self.dayFirst = dayFirst
if twoCharCutoffYear is not None:
self.twoCharCutoffYear = twoCharCutoffYear
def _namer(self, prefix):
def _(part):
return '%s__%s' % (prefix,part)
return _
def _renderTag(self, ctx, year, month, day, namer, readonly):
yearTag = T.input(type="text", name=namer('year'), value=year, size=4)
monthTag = T.input(type="text", name=namer('month'), value=month, size=2)
dayTag = T.input(type="text", name=namer('day'), value=day, size=2)
if readonly:
tags = (yearTag, monthTag, dayTag)
for tag in tags:
tag(class_='readonly', readonly='readonly')
if self.dayFirst:
return dayTag, ' / ', monthTag, ' / ', yearTag, ' ', _('(day/month/year)')
else:
return monthTag, ' / ', dayTag, ' / ', yearTag, ' ', _('(month/day/year)')
def render(self, ctx, key, args, errors):
converter = iformal.IDateTupleConvertible(self.original)
namer = self._namer(key)
if errors:
year = args.get(namer('year'), [''])[0]
month = args.get(namer('month'), [''])[0]
day = args.get(namer('day'), [''])[0]
else:
year, month, day = converter.fromType(args.get(key))
return self._renderTag(ctx, year, month, day, namer, False)
def renderImmutable(self, ctx, key, args, errors):
converter = iformal.IDateTupleConvertible(self.original)
namer = self._namer(key)
year, month, day = converter.fromType(args.get(key))
return self._renderTag(ctx, year, month, day, namer, True)
def processInput(self, ctx, key, args):
namer = self._namer(key)
# Get the form field values as a (y,m,d) tuple
ymd = [args.get(namer(part), [''])[0].strip() for part in ('year', 'month', 'day')]
# Remove parts that were not entered.
ymd = [p for p in ymd if p]
# Nothing entered means None otherwise we need all three.
if not ymd:
ymd = None
elif len(ymd) != 3:
raise validation.FieldValidationError("Invalid date")
# So, we have what looks like a good attempt to enter a date.
if ymd is not None:
# If a 2-char year is allowed then prepend the century.
if self.twoCharCutoffYear is not None and len(ymd[0]) == 2:
try:
if int(ymd[0]) >= self.twoCharCutoffYear:
century = '19'
else:
century = '20'
ymd[0] = century + ymd[0]
except ValueError:
pass
# By now, we should have a year of at least 4 characters.
if len(ymd[0]) < 4:
if self.twoCharCutoffYear is not None:
msg = "Please enter a 2 or 4 digit year"
else:
msg = "Please enter a 4 digit year"
raise validation.FieldValidationError(msg)
# Map to integers
try:
ymd = [int(p) for p in ymd]
except ValueError, e:
raise validation.FieldValidationError("Invalid date")
ymd = iformal.IDateTupleConvertible(self.original).toType(ymd)
return self.original.validate(ymd)
class MMYYDatePartsInput(object):
"""
Two input fields for entering the month and year.
"""
implements( iformal.IWidget )
cutoffYear = 70
def __init__(self, original, cutoffYear=None):
self.original = original
if cutoffYear is not None:
self.cutoffYear = cutoffYear
def _namer(self, prefix):
def _(part):
return '%s__%s' % (prefix,part)
return _
def _renderTag(self, ctx, year, month, namer, readonly):
yearTag = T.input(type="text", name=namer('year'), value=year, size=2)
monthTag = T.input(type="text", name=namer('month'), value=month, size=2)
if readonly:
tags=(yearTag, monthTag)
for tag in tags:
tag(class_='readonly', readonly='readonly')
return monthTag, ' / ', yearTag, ' (mm/yy)'
def render(self, ctx, key, args, errors):
converter = iformal.IDateTupleConvertible(self.original)
namer = self._namer(key)
if errors:
year = args.get(namer('year'), [''])[0]
month = args.get(namer('month'), [''])[0]
# return a blank for the day
day = ''
else:
year, month, day = converter.fromType(args.get(key))
# if we have a year as default data, stringify it and only use last two digits
if year is not None:
year = str(year)[2:]
return self._renderTag(ctx, year, month, namer, False)
def renderImmutable(self, ctx, key, args, errors):
converter = iformal.IDateTupleConvertible(self.original)
year, month, day = converter.fromType(args.get(key))
namer = self._namer(key)
# if we have a year as default data, stringify it and only use last two digits
if year is not None:
year = str(year)[2:]
return self._renderTag(ctx, year, month, namer, True)
def processInput(self, ctx, key, args):
namer = self._namer(key)
value = [args.get(namer(part), [''])[0].strip() for part in ('year', 'month')]
value = [p for p in value if p]
if not value:
value = None
elif len(value) != 2:
raise validation.FieldValidationError("Invalid date")
if value is not None:
try:
value = [int(p) for p in value]
except ValueError, e:
raise validation.FieldValidationError("Invalid date")
if value[1] < 0 or value[1] > 99:
raise validation.FieldValidationError("Invalid year. Please enter a two-digit year.")
if value[0] > self.cutoffYear:
value[0] = 1900 + value[0]
else:
value[0] = 2000 + value[0]
value.append(1)
value = iformal.IDateTupleConvertible(self.original).toType( value )
return self.original.validate(value)
class CheckboxMultiChoice(object):
"""
Multiple choice list, rendered as a list of checkbox fields.
"""
implements( iformal.IWidget )
options = None
def __init__(self, original, options=None):
self.original = original
if options is not None:
self.options = options
def _renderTag(self, ctx, key, values, converter, disabled):
def renderer(ctx, options):
# loops through checkbox options and renders
for n,item in enumerate(options):
optValue = iformal.IKey(item).key()
optLabel = iformal.ILabel(item).label()
optValue = converter.fromType(optValue)
optid = render_cssid(key, n)
checkbox = T.input(type='checkbox', name=key, value=optValue,
id=optid)
if optValue in values:
checkbox = checkbox(checked='checked')
if disabled:
checkbox = checkbox(class_='disabled', disabled='disabled')
yield checkbox, T.label(for_=optid)[optLabel], T.br()
# Let Nevow worry if self.options is not already a list.
return T.invisible(data=self.options)[renderer]
def render(self, ctx, key, args, errors):
converter = iformal.IStringConvertible(self.original.type)
if errors:
values = args.get(key, [])
else:
values = args.get(key)
if values is not None:
values = [converter.fromType(v) for v in values]
else:
values = []
return self._renderTag(ctx, key, values, converter, False)
def renderImmutable(self, ctx, key, args, errors):
converter = iformal.IStringConvertible(self.original.type)
values = args.get(key)
if values is not None:
values = [converter.fromType(v) for v in values]
else:
values = []
return self._renderTag(ctx, key, values, converter, True)
def processInput(self, ctx, key, args):
charset = util.getPOSTCharset(ctx)
values = [v.decode(charset) for v in args.get(key, [])]
converter = iformal.IStringConvertible(self.original.type)
values = [converter.toType(v) for v in values]
return self.original.validate(values)
class FileUploadRaw(object):
implements( iformal.IWidget )
def __init__(self, original):
self.original = original
def _renderTag(self, ctx, key, disabled):
tag=T.input(name=key, id=render_cssid(key),type='file')
if disabled:
tag(class_='disabled', disabled='disabled')
return tag
def render(self, ctx, key, args, errors):
if errors:
value = args.get(key, [''])[0]
else:
value = iformal.IFileConvertible(self.original).fromType(args.get(key))
return self._renderTag(ctx, key, False)
def renderImmutable(self, ctx, key, args, errors):
value = iformal.IFileConvertible(self.original).fromType(args.get(key))
return self._renderTag(ctx, key, True)
def processInput(self, ctx, key, args):
fileitem = inevow.IRequest(ctx).fields[key]
name = fileitem.filename.decode(util.getPOSTCharset(ctx))
value = (name, fileitem.file)
value = iformal.IFileConvertible(self.original).fromType(value)
return self.original.validate(value)
class FileUpload(object):
implements( iformal.IWidget )
def __init__(self, original, fileHandler, preview=None):
self.original = original
self.fileHandler = fileHandler
self.preview = preview
def _namer(self, prefix):
def _(part):
return '%s__%s' % (prefix,part)
return _
def _renderTag(self, ctx, key, value, namer, disabled):
name = self.fileHandler.getUrlForFile(value)
if name:
if self.preview == 'image':
yield T.p[value,T.img(src=self.fileHandler.getUrlForFile(value))]
else:
yield T.p[value]
else:
yield T.p[T.strong['nothing uploaded']]
yield T.input(name=namer('value'),value=value,type='hidden')
tag=T.input(name=key, id=render_cssid(key),type='file')
if disabled:
tag(class_='disabled', disabled='disabled')
yield tag
def render(self, ctx, key, args, errors):
namer = self._namer(key)
if errors:
fileitem = inevow.IRequest(ctx).fields[key]
name = fileitem.filename.decode(util.getPOSTCharset(ctx))
if name:
value = name
else:
namer = self._namer(key)
value = args.get(namer('value'))[0]
else:
value = iformal.IStringConvertible(self.original).fromType(args.get(key))
return self._renderTag(ctx, key, value, namer, False)
def renderImmutable(self, ctx, key, args, errors):
namer = self._namer(key)
value = iformal.IStringConvertible(self.original).fromType(args.get(key))
return self._renderTag(ctx, key, value, namer, True)
def processInput(self, ctx, key, args):
fileitem = inevow.IRequest(ctx).fields[key]
name = fileitem.filename.decode(util.getPOSTCharset(ctx))
if name:
value = self.fileHandler.storeFile( fileitem.file, name )
else:
namer = self._namer(key)
value = args.get(namer('value'))[0]
value = iformal.IStringConvertible(self.original).fromType(value)
return self.original.validate(value)
class FileUploadWidget(object):
"""
File upload widget that carries the uploaded file around until the form
validates.
The widget uses the resource manager to save the file to temporary storage
until the form validates. This makes file uploads behave like most of the
other widgets, i.e. the value is kept when a form is redisplayed due to
validation errors.
"""
implements( iformal.IWidget )
FROM_RESOURCE_MANAGER = 'rm'
FROM_CONVERTIBLE = 'cf'
convertibleFactory = converters.NullConverter
def _namer(self, prefix):
def _(part):
return '%s__%s' % (prefix,part)
return _
def __init__( self, original, convertibleFactory=None, originalKeyIsURL=False, removeable=False ):
self.original = original
if convertibleFactory is not None:
self.convertibleFactory = convertibleFactory
self.originalKeyIsURL = originalKeyIsURL
self.removeable = removeable
def _blankField( self, field ):
"""
Convert empty strings into None.
"""
if field and field == '':
return None
return field
def _getFromArgs( self, args, name ):
"""
Get the first value of 'name' from 'args', or None.
"""
rv = args.get( name )
if rv:
rv = rv[0]
return rv
def render(self, ctx, key, args, errors):
"""
Render the data.
This either renders a link to the original file, if specified, and
no new file has been uploaded. Or a link to the uploaded file.
The request to get the data should be routed to the getResouce
method.
"""
form = iformal.IForm( ctx )
namer = self._namer( key )
resourceIdName = namer( 'resource_id' )
originalIdName = namer( 'original_id' )
# get the resource id first from the resource manager
# then try the request
resourceId = form.resourceManager.getResourceId( key )
if resourceId is None:
resourceId = self._getFromArgs( args, resourceIdName )
resourceId = self._blankField( resourceId )
# Get the original key from a hidden field in the request,
# then try the request file.data initial data.
originalKey = self._getFromArgs( args, originalIdName )
if not errors and not originalKey:
originalKey = args.get( key )
originalKey = self._blankField( originalKey )
# if we have a removeable attribute, generate the html
if self.removeable is True:
checkbox = T.input(type='checkbox', name='%s_remove'%key, id=render_cssid('%s_remove'%key),class_='upload-checkbox-remove',value='remove')
if args.get('%s_remove'%key, [None])[0] is not None:
checkbox = checkbox = checkbox(checked='checked')
removeableHtml = T.p[ 'check to remove', checkbox]
else:
removeableHtml = ''
if resourceId:
# Have an uploaded file, so render a link to the uploaded file
tmpURL = widgetResourceURL(form.name).child(key).child( self.FROM_RESOURCE_MANAGER ).child(resourceId)
value = form.resourceManager.getResourceForWidget( key )
yield [ T.p[T.a(href=tmpURL)[value[2]]], removeableHtml]
elif originalKey:
# The is no uploaded file, but there is an original, so render a
# URL to it
if self.originalKeyIsURL:
tmpURL = originalKey
yield [ T.p[T.img(src=tmpURL)], removeableHtml ]
else:
# Copy the data to the resource manager and render from there
resourceId = self._storeInResourceManager(ctx, key, originalKey)
tmpURL = widgetResourceURL(form.name).child(key).child( self.FROM_RESOURCE_MANAGER ).child(resourceId)
yield [ T.p[T.a(href=tmpURL)[originalKey[2]]], removeableHtml]
else:
# No uploaded file, no original
yield T.p[T.strong['Nothing uploaded']]
yield T.input(name=key, id=render_cssid(key),type='file')
# Id of uploaded file in the resource manager
yield T.input(name=resourceIdName,value=resourceId,type='hidden')
if originalKey and self.originalKeyIsURL:
# key of the original that can be used to get a file later
yield T.input(name=originalIdName,value=originalKey,type='hidden')
def renderImmutable(self, ctx, key, args, errors):
form = iformal.IForm(ctx)
namer = self._namer(key)
originalIdName = namer('original_id')
# Get the original key from a hidden field in the request,
# then try the request form.data initial data.
originalKey = self._getFromArgs( args, originalIdName )
if not errors and not originalKey:
originalKey = args.get( key )
originalKey = self._blankField( originalKey )
if originalKey:
# The is no uploaded file, but there is an original, so render a
# URL to it
if self.originalKeyIsURL:
tmpURL = originalKey
yield T.p[T.img(src=tmpURL)]
else:
# Store the file in the resource manager and render from there
resourceId = self._storeInResourceManager(ctx, key, originalKey)
tmpURL = widgetResourceURL(form.name).child(key).child( self.FROM_RESOURCE_MANAGER ).child(resourceId)
yield [ T.p[T.a(href=tmpURL)[originalKey[2]]]]
else:
# No uploaded file, no original
yield T.p[T.strong['Nothing uploaded']]
if originalKey:
# key of the original that can be used to get a file later
yield T.input(name=originalIdName,value=originalKey,type='hidden')
def processInput(self, ctx, key, args):
"""
Process the request, storing any uploaded file in the
resource manager.
"""
resourceManager = iformal.IForm( ctx ).resourceManager
# Ping the resource manager with any resource ids that I know
self._registerWithResourceManager( key, args, resourceManager )
fileitem = inevow.IRequest(ctx).fields[key]
name = fileitem.filename.decode(util.getPOSTCharset(ctx))
if name:
# Store the uploaded file in the resource manager
resourceManager.setResource( key, fileitem.file, name )
# Validating against an uploaded file. Should the fact that there is
# original file meet a required field validation?
value = resourceManager.getResourceForWidget( key )
value = self.convertibleFactory(self.original).toType( value )
# check to see if we should remove this
if self.removeable is True:
remove = args.get('%s_remove'%key, [None])[0]
if remove is not None:
value = (None,None,None)
return self.original.validate( value )
def _registerWithResourceManager( self, key, args, resourceManager ):
"""
If there is a resource id in the request, then let the
resource manager know about it.
"""
namer = self._namer( key )
resourceIdName = namer( 'resource_id' )
resourceId = self._getFromArgs( args, resourceIdName )
resourceId = self._blankField( resourceId )
if resourceId:
resourceManager.register( key, resourceId )
def getResource( self, ctx, key, segments ):
"""
Return an Resource that contains the image, either a file
from the resource manager, or a data object from the convertible.
"""
if segments[0] == self.FROM_RESOURCE_MANAGER:
# Resource manager can provide a path so return a static.File
# instance that points to the file
rm = iformal.IForm( ctx ).resourceManager
(mimetype, path, fileName) = rm.getResourcePath( segments[1] )
inevow.IRequest(ctx).setHeader('Cache-Control',
'no-cache, must-revalidate, no-store')
return static.Data(file(path).read(), str(mimetype)), ()
elif segments[0] == self.FROM_CONVERTIBLE:
# The convertible can provide a file like object so create a
# static.Data instance with the data from the convertible.
def _( result ):
mimetype, filelike, fileName = result
data = filelike.read()
filelike.close()
return static.Data( data, mimetype ), []
d = defer.maybeDeferred( self.convertibleFactory(self.original).fromType, segments[1], context=ctx )
d.addCallback( _ )
return d
else:
return None
def _storeInResourceManager(self, ctx, key, originalKey):
resourceManager = iformal.IForm( ctx ).resourceManager
resourceManager.setResource( key, originalKey[1], originalKey[2] )
resourceId = resourceManager.getResourceId( key )
return resourceId
class Hidden(object):
"""
A hidden form field.
"""
__implements__ = iformal.IWidget,
inputType = 'hidden'
def __init__(self, original):
self.original = original
def render(self, ctx, key, args, errors):
if errors:
value = args.get(key, [''])
if isinstance(value, list):
value = value[0]
else:
value = iformal.IStringConvertible(self.original).fromType(args.get(key))
return T.input(type=self.inputType, name=key, id=render_cssid(key), value=value)
def renderImmutable(self, ctx, key, args, errors):
return self.render(ctx, key, args, errors)
def processInput(self, ctx, key, args):
value = args.get(key, [''])[0].decode(util.getPOSTCharset(ctx))
value = iformal.IStringConvertible(self.original).toType(value)
return self.original.validate(value)
__all__ = [
'Checkbox', 'CheckboxMultiChoice', 'CheckedPassword', 'FileUploadRaw',
'Password', 'SelectChoice', 'TextArea', 'TextInput', 'DatePartsInput',
'DatePartsSelect', 'MMYYDatePartsInput', 'Hidden', 'RadioChoice',
'SelectOtherChoice', 'FileUpload', 'FileUploadWidget', 'TextAreaList',
]
| Python |
import re
from zope.interface import implements
from formal import iformal
class FormsError(Exception):
"""
Base class for all Forms errors. A single string, message, is accepted and
stored as an attribute.
The message is not passed on to the Exception base class because it doesn't
seem to be able to handle unicode at all.
"""
def __init__(self, message):
Exception.__init__(self, message)
self.message = message
class FormError(FormsError):
"""
Form validation error. Raise this, typically from a submit callback, to
signal that the form (not an individual field) failed to validate.
"""
pass
class FieldError(FormsError):
"""
Base class for field-related exceptions. The failure message and the failing
field name are stored as attributes.
"""
def __init__(self, message, fieldName=None):
FormsError.__init__(self, message)
self.fieldName = fieldName
class FieldValidationError(FieldError):
"""
Exception that signals that a field failed to validate.
"""
pass
class FieldRequiredError(FieldValidationError):
"""
Exception that signals that a field that is marked as required was not
entered.
"""
pass
class RequiredValidator(object):
implements(iformal.IValidator)
def validate(self, field, value):
if value is None:
raise FieldRequiredError, 'Required'
class LengthValidator(object):
"""Validate the length of the value is within a given range.
"""
implements(iformal.IValidator)
def __init__(self, min=None, max=None):
self.min = min
self.max = max
assert self.min is not None or self.max is not None
def validationErrorMessage(self, field):
if self.min is not None and self.max is None:
return 'Must be longer than %r characters'%(self.min,)
if self.min is None and self.max is not None:
return 'Must be shorter than %r characters'%(self.max,)
return 'Must be between %r and %r characters'%(self.min, self.max)
def validate(self, field, value):
if value is None:
return
length = len(value)
if self.min is not None and length < self.min:
raise FieldValidationError, self.validationErrorMessage(field)
if self.max is not None and length > self.max:
raise FieldValidationError, self.validationErrorMessage(field)
class RangeValidator(object):
"""Validate the size of the value is within is given range.
"""
implements(iformal.IValidator)
def __init__(self, min=None, max=None):
self.min = min
self.max = max
assert self.min is not None or self.max is not None
def validationErrorMessage(self, field):
if self.min is not None and self.max is None:
return 'Must be greater than %r'%(self.min,)
if self.min is None and self.max is not None:
return 'Must be less than %r'%(self.max,)
return 'Must be between %r and %r'%(self.min, self.max)
def validate(self, field, value):
if value is None:
return
if self.min is not None and value < self.min:
raise FieldValidationError, self.validationErrorMessage(field)
if self.max is not None and value > self.max:
raise FieldValidationError, self.validationErrorMessage(field)
class PatternValidator(object):
"""Validate the value is a certain pattern.
The required pattern is defined as a regular expression. The regex will be
compiled automatically if necessary.
"""
implements(iformal.IValidator)
def __init__(self, regex):
self.regex = regex
def validate(self, field, value):
if value is None:
return
# If it doesn't look like a regex object then compile it now
if not hasattr(self.regex, 'match'):
self.regex = re.compile(self.regex)
if self.regex.match(value) is None:
raise FieldValidationError, 'Invalid format'
class CallableValidator(object):
"""
A validator that delegates the validation of non-None values to a callable
with the same signature as IValidator.validate.
"""
implements(iformal.IValidator)
def __init__(self, callable):
self.callable = callable
def validate(self, field, value):
if value is None:
return
self.callable(field, value)
__all__ = [
'FormError', 'FieldError', 'FieldValidationError', 'FieldRequiredError',
'RequiredValidator', 'LengthValidator', 'RangeValidator', 'PatternValidator',
'CallableValidator',
]
| Python |
from nevow import url
import formal
from formal.examples import main
class ActionButtonsPage(main.FormExamplePage):
title = 'Action Button'
description = 'Example of non-validating button, buttons with non-default labels, etc'
def form_example(self, ctx):
form = formal.Form()
form.addField('aString', formal.String(required=True))
form.addAction(self.submitted, label="Click, click, clickety-click!")
form.addAction(self.redirect, 'back', validate=False)
return form
def submitted(self, ctx, form, data):
print form, data
def redirect(self, ctx, form, data):
return url.rootaccessor(ctx)
| Python |
import formal
from formal.examples import main
# Let the examples run if docutils is not installed
try:
import docutils
except ImportError:
import warnings
warnings.warn("docutils is not installed")
docutilsAvailable = False
else:
docutilsAvailable = True
if docutilsAvailable:
from docutils.writers.html4css1 import Writer, HTMLTranslator
from docutils import nodes
class CustomisedHTMLTranslator(HTMLTranslator):
def visit_newdirective_node(self, node):
self.body.append('<div>Some HTML with a %s parameter</div>\n'%(node.attributes['parameter'],))
def depart_newdirective_node(self, node):
pass
class newdirective_node(nodes.General, nodes.Inline, nodes.TextElement):
pass
def newdirective(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
return [newdirective_node('', parameter=arguments[0])]
newdirective.arguments = (1, 0, 0)
newdirective.options = None
from docutils.parsers.rst import directives
directives.register_directive('newdirective', newdirective)
class ReSTWidgetFormPage(main.FormExamplePage):
title = 'ReST widget'
description = 'The ReST widget captures ReST and previews as HTML.'
def form_example(self, ctx):
form = formal.Form()
form.addField('restString', formal.String(required=True),
widgetFactory=formal.ReSTTextArea)
if docutilsAvailable:
w = Writer()
w.translator_class = CustomisedHTMLTranslator
form.addField('customRestString', formal.String(required=True),
formal.widgetFactory(formal.ReSTTextArea, restWriter=w))
form.addAction(self.submitted)
return form
def submitted(self, ctx, form, data):
print form, data
| Python |
from zope.interface import implements
from twisted.internet import defer
import formal
from formal import iformal
from formal.examples import main
# A not-too-good regex for matching an IP address.
IP_ADDRESS_PATTERN = '^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$'
class ValidatorFormPage(main.FormExamplePage):
title = 'Custom form validation'
description = 'Example of installing additional validators and writing a new one'
def form_example(self, ctx):
form = formal.Form()
# This actually installs a RequiredValidator for you.
form.addField('required', formal.String(required=True))
# Exactly the same as above, only with a "manually" installed validator.
form.addField('required2', formal.String(validators=[formal.RequiredValidator()]))
# Check for a minimum length, if anything entered.
form.addField('atLeastFiveChars', formal.String(validators=[formal.LengthValidator(min=5)]))
# Check for a minimum length, if anything entered.
form.addField('ipAddress', formal.String(strip=True, validators=[formal.PatternValidator(regex=IP_ADDRESS_PATTERN)]))
# Check for the word 'silly'
form.addField('silly', formal.String(validators=[SillyValidator()]))
# Check age is between 18 and 30
form.addField('ohToBeYoungAgain', formal.Integer(validators=[formal.RangeValidator(min=18, max=30)]))
form.addField('deferred', formal.String(validators=[DeferredValidator()]))
form.addAction(self.submitted)
return form
def submitted(self, ctx, form, data):
print form, data
class SillyValidator(object):
"""
A pointless example that checks a specific word, 'silly', is entered.
"""
implements(iformal.IValidator)
word = u'silly'
def validate(self, field, value):
if value is None:
return
if value.lower() != self.word.lower():
raise formal.FieldValidationError(u'You must enter \'%s\''%self.word)
class DeferredValidator(object):
"""
Just to demonstrate the validators can be deferred.
"""
def validate(self, field, value):
if value == 'fail':
return defer.fail(formal.FieldValidationError(u"You triggered a failure"))
return defer.succeed(None)
| Python |
import formal
from formal.examples import main
class SimpleFormPage(main.FormExamplePage):
title = 'Simple Form'
description = 'Probably the simplest form possible.'
def form_example(self, ctx):
form = formal.Form()
form.addField('aString', formal.String())
form.addAction(self.submitted)
return form
def submitted(self, ctx, form, data):
print form, data
| Python |
try:
import decimal
haveDecimal = True
except ImportError:
haveDecimal = False
import formal
from formal.examples import main
class TypesFormPage(main.FormExamplePage):
title = 'Form Types'
description = 'Example of using different typed fields.'
def form_example(self, ctx):
form = formal.Form()
form.addField('aString', formal.String())
form.addField('aInteger', formal.Integer())
form.addField('aFloat', formal.Float())
if haveDecimal:
form.addField('aDecimal', formal.Decimal())
form.addField('aBoolean', formal.Boolean())
form.addField('aDate', formal.Date())
form.addField('aTime', formal.Time())
form.addAction(self.submitted)
return form
def submitted(self, ctx, form, data):
print data
| Python |
from datetime import date
import formal
from formal.examples import main
class MissingFormPage(main.FormExamplePage):
title = 'Missing Values'
description = 'Providing default values when missing'
def form_example(self, ctx):
form = formal.Form()
form.addField('aString', formal.String(missing='<nothing>'))
form.addField('aDate', formal.Date(missing=date(2005, 8, 1)))
form.addAction(self.submitted)
return form
def submitted(self, ctx, form, data):
print data
| Python |
import formal
from formal.examples import main
class FileUploadFormPage(main.FormExamplePage):
title = 'File Upload'
description = 'Uploading a file'
def form_example(self, ctx):
form = formal.Form()
form.addField('file', formal.File())
form.addAction(self.submitted)
return form
def submitted(self, ctx, form, data):
print form, data
| Python |
import pkg_resources
from zope.interface import implements
from twisted.python import reflect
from nevow import appserver, inevow, loaders, rend, static, tags as T, url
import formal
DOCTYPE = T.xml('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">')
CHARSET = T.xml('<meta http-equiv="content-type" content="text/html; charset=utf-8" />')
examples = [
'formal.examples.simple.SimpleFormPage',
'formal.examples.types.TypesFormPage',
'formal.examples.required.RequiredFormPage',
'formal.examples.missing.MissingFormPage',
'formal.examples.prepopulate.PrepopulateFormPage',
'formal.examples.group.GroupFormPage',
'formal.examples.stanstyle.StanStyleFormPage',
'formal.examples.fileupload.FileUploadFormPage',
'formal.examples.smartupload.SmartUploadFormPage',
'formal.examples.selections.SelectionFormPage',
'formal.examples.datestimes.DatesTimesFormPage',
'formal.examples.actionbuttons.ActionButtonsPage',
'formal.examples.validator.ValidatorFormPage',
'formal.examples.restwidget.ReSTWidgetFormPage',
'formal.examples.nofields.NoFieldsFormPage',
'formal.examples.hidden.HiddenFieldsFormPage',
'formal.examples.textareawithselect.TextAreaWithSelectFormPage',
'formal.examples.richtextarea.RichTextAreaFormPage',
]
def makeSite():
root = RootPage()
site = appserver.NevowSite(root, logPath="web.log")
return site
class RootPage(rend.Page):
"""
Main page that lists the examples and makes the example page a child
resource.
"""
docFactory = loaders.stan(
T.invisible[
DOCTYPE,
T.html[
T.head[
CHARSET,
T.title['Forms Examples'],
T.link(rel='stylesheet', type='text/css', href=url.root.child('examples.css')),
],
T.body[
T.directive('examples'),
],
],
],
)
def render_examples(self, ctx, data):
for name in examples:
cls = reflect.namedAny(name)
yield T.div(class_='example')[
T.h1[T.a(href=url.here.child(name))[cls.title]],
T.p[cls.description],
]
def childFactory(self, ctx, name):
if name in examples:
cls = reflect.namedAny(name)
return cls()
class FormExamplePage(formal.ResourceMixin, rend.Page):
"""
A base page for the actual examples. The page renders something sensible,
including the title example and description. It also include the "example"
form in an appropriate place.
Each example page is expected to provide the title and description
attributes as well as a form_example method that builds and returns a
formal.Form instance.
"""
docFactory = loaders.stan(
T.invisible[
DOCTYPE,
T.html[
T.head[
CHARSET,
T.title(data=T.directive('title'), render=rend.data),
T.link(rel='stylesheet', type='text/css', href=url.root.child('examples.css')),
T.link(rel='stylesheet', type='text/css', href=url.root.child('formal.css')),
T.script(type='text/javascript', src='js/formal.js'),
],
T.body[
T.h1(data=T.directive('title'), render=rend.data),
T.p(data=T.directive('description'), render=rend.data),
T.directive('form example'),
],
],
],
)
def data_title(self, ctx, data):
return self.title
def data_description(self, ctx, data):
return self.description
# Add child_ attributes
examples_css = pkg_resources.resource_filename('formal.examples', 'examples.css')
setattr(RootPage, 'child_examples.css', static.File(examples_css))
setattr(RootPage, 'child_formal.css', formal.defaultCSS)
setattr(RootPage, 'child_js', formal.formsJS)
if __name__ == '__main__':
import sys
from twisted.internet import reactor
from twisted.python import log
if len(sys.argv) > 1:
port = int(sys.argv[1])
else:
port = 8000
log.startLogging(sys.stdout)
site = makeSite()
reactor.listenTCP(port, site)
reactor.run()
| Python |
import formal
from formal.examples import main
class SmartUploadFormPage(main.FormExamplePage):
title = 'Smart File Upload'
description = 'Smart uploading of files where the file is "carried across" when the validation fails'
def form_example(self, ctx):
form = formal.Form()
form.addField('required', formal.String(required=True))
form.addField('file', formal.File(), formal.FileUploadWidget)
form.addField('removeableFile', formal.File(), formal.widgetFactory(formal.FileUploadWidget, removeable=True ) )
form.addAction(self.submitted)
return form
def submitted(self, ctx, form, data):
print form, data
| Python |
import formal
from formal.examples import main
class GroupFormPage(main.FormExamplePage):
title = 'Field Group Form'
description = 'Groups of fields on a form'
def form_example(self, ctx):
def makeAddressGroup(name):
address = formal.Group(name)
address.add(formal.Field('address', formal.String()))
address.add(formal.Field('city', formal.String()))
address.add(formal.Field('postalCode', formal.String()))
return address
def makePersonGroup(name):
person = formal.Group(name, cssClass=name)
person.add(formal.Field('name', formal.String(required=True)))
person.add(formal.Field('dateOfBirth', formal.Date(required=True)))
person.add(makeAddressGroup('address'))
return person
form = formal.Form()
form.add(formal.Field('before', formal.String()))
form.add(makePersonGroup('me'))
form.add(makePersonGroup('you'))
form.add(formal.Field('after', formal.String()))
form.addAction(self.submitted)
return form
def submitted(self, ctx, form, data):
print form, data
| Python |
import formal
from formal.examples import main
class HiddenFieldsFormPage(main.FormExamplePage):
title = 'Hidden Fields Form'
description = 'A form with a hidden field.'
def form_example(self, ctx):
form = formal.Form()
form.addField('hiddenString', formal.String(), widgetFactory=formal.Hidden)
form.addField('hiddenInt', formal.Integer(), widgetFactory=formal.Hidden)
form.addField('visibleString', formal.String())
form.addAction(self.submitted)
form.data = {
'hiddenString': 'foo',
'hiddenInt': 1,
}
return form
def submitted(self, ctx, form, data):
print data
| Python |
from datetime import datetime
import formal
from formal.examples import main
class PrepopulateFormPage(main.FormExamplePage):
title = 'Prepopulate'
description = 'Example of prepopulating form fields'
def form_example(self, ctx):
form = formal.Form()
form.addField('aString', formal.String())
form.addField('aTime', formal.Time())
form.addAction(self.submitted)
form.data = {
'aTime': datetime.utcnow().time(),
}
return form
def submitted(self, ctx, form, data):
print data
| Python |
import formal
from formal.examples import main
from formal import RichText
class RichTextAreaFormPage(main.FormExamplePage):
title = 'Rich Text widget'
description = 'The Rich widget captures a textarea value and a type.'
def form_example(self, ctx):
form = formal.Form()
form.addField('RichTextString', formal.RichTextType(required=True),
widgetFactory = formal.widgetFactory(formal.RichTextArea, parsers=[('plain','Plain Text'),('reverseplain','Reversed Plain Text')]))
form.addField('RichTextStringNotRequired', formal.RichTextType(),
widgetFactory = formal.widgetFactory(formal.RichTextArea, parsers=[('plain','Plain Text'),('reverseplain','Reversed Plain Text'),('html','XHTML')]))
form.addField('RichTextStringOnlyOneParser', formal.RichTextType(required=True),
widgetFactory = formal.widgetFactory(formal.RichTextArea, parsers=[('markdown','MarkDown')]))
form.addAction(self.submitted)
return form
def submitted(self, ctx, form, data):
print form,data
| Python |
import formal
from formal.examples import main
class DatesTimesFormPage(main.FormExamplePage):
title = 'Dates'
description = 'Date entry examples'
def form_example(self, ctx):
form = formal.Form()
form.addField('isoFormatDate', formal.Date(), formal.TextInput)
form.addField('datePartsSelect', formal.Date(), formal.widgetFactory(formal.DatePartsSelect, dayFirst=True))
form.addField('monthFirstDate', formal.Date(), formal.DatePartsInput)
form.addField('dayFirstDate', formal.Date(), formal.widgetFactory(formal.DatePartsInput, dayFirst=True))
form.addField('monthYearDate', formal.Date(), formal.MMYYDatePartsInput)
form.addField('twoCharYearDate', formal.Date(), formal.widgetFactory(formal.DatePartsInput, twoCharCutoffYear=70))
form.addField('time', formal.Time())
form.addAction(self.submitted)
return form
def submitted(self, ctx, form, data):
print form, data
| Python |
from twisted.internet import defer
from datetime import date
import formal
from formal.examples import main
# A boring list of (value, label) pairs.
strings = [
('foo', 'Foo'),
('bar', 'Bar'),
]
# A list of dates with meaningful names.
dates = [
(date(2005, 01, 01), 'New Year Day'),
(date(2005, 11, 06), 'My Birthday'),
(date(2005, 12, 25), 'Christmas Day'),
]
tuples = [
(('a',1), 'a1'),
(('b',1), 'b1'),
(('c',1), 'c1'),
]
def data_strings(ctx, data):
# Let's defer it, just for fun.
return defer.succeed(strings)
# A different "none" option tuple
differentNone = ('none value', '- select -')
class SelectionFormPage(main.FormExamplePage):
title = 'Selection widgets'
description = 'Example of the various selection widgets'
def form_example(self, ctx):
form = formal.Form()
form.addField('required', formal.String(required=True))
form.addField('oneString', formal.String(),
formal.widgetFactory(formal.SelectChoice, options=strings))
form.addField('anotherString', formal.String(),
formal.widgetFactory(formal.SelectChoice, options=data_strings))
form.addField('oneMoreString', formal.String(required=True),
formal.widgetFactory(formal.RadioChoice, options=data_strings))
form.addField('oneDate', formal.Date(),
formal.widgetFactory(formal.SelectChoice, options=dates))
form.addField('multipleStrings', formal.Sequence(formal.String()),
formal.widgetFactory(formal.CheckboxMultiChoice,
options=data_strings))
form.addField('multipleDates', formal.Sequence(formal.Date()),
formal.widgetFactory(formal.CheckboxMultiChoice, options=dates))
form.addField('multipleTuples', formal.Sequence(formal.Sequence()),
formal.widgetFactory(formal.CheckboxMultiChoice,
options=tuples))
form.addField('differentNoneSelect', formal.String(),
formal.widgetFactory(formal.SelectChoice, options=strings,
noneOption=differentNone))
form.addField('differentNoneRadios', formal.String(),
formal.widgetFactory(formal.RadioChoice, options=data_strings,
noneOption=differentNone))
form.addField('selectOther', formal.String(),
formal.widgetFactory(formal.SelectOtherChoice, options=['Mr',
'Mrs']))
form.addField('selectOtherCustomOther', formal.String(),
formal.widgetFactory(formal.SelectOtherChoice, options=['Mr',
'Mrs'], otherOption=('...','Other (Please Enter)')))
form.addField('selectOtherRequired', formal.String(required=True),
formal.widgetFactory(formal.SelectOtherChoice, options=['Mr',
'Mrs']))
form.addField('multiselect', formal.String(),
formal.widgetFactory(formal.MultiselectChoice, options=strings))
form.addAction(self.submitted)
return form
def submitted(self, ctx, form, data):
print form, data
| Python |
import formal
from formal.examples import main
class NoFieldsFormPage(main.FormExamplePage):
title = 'Form With no Fields'
description = 'A form with no fields, just button(s). (Just to prove ' \
'it works.)'
def form_example(self, ctx):
form = formal.Form()
form.addAction(self.submitted)
return form
def submitted(self, ctx, form, data):
print form, data
| Python |
from formal import Field, Form, Group, String
from formal.examples import main
class StanStyleFormPage(main.FormExamplePage):
title = 'Stan-Style Form'
description = 'Building a Form in a stan style'
def form_example(self, ctx):
form = Form()[
Group("me")[
Field("firstNames", String()),
Field("lastName", String()),
],
Group("you")[
Field("firstNames", String()),
Field("lastName", String()),
],
]
form.addAction(self.submitted)
return form
def submitted(self, ctx, form, data):
print data
| Python |
import formal
from formal.examples import main
from formal.widgets.textareawithselect import TextAreaWithSelect
class TextAreaWithSelectFormPage(main.FormExamplePage):
title = 'Text area with select'
description = 'text area with a select box to append new info'
def form_example(self, ctx):
form = formal.Form()
form.addField('myTextArea', formal.String(),
formal.widgetFactory(TextAreaWithSelect,values=(('aval','alabel'),('bval','blabel')) ))
form.addAction(self.submitted)
return form
def submitted(self, ctx, form, data):
print form, data
| Python |
import formal
from formal.examples import main
class RequiredFormPage(main.FormExamplePage):
title = 'Required Fields'
description = 'Demonstration of required fields'
def form_example(self, ctx):
form = formal.Form()
form.addField('name', formal.String(required=True))
form.addField('age', formal.Integer())
form.addAction(self.submitted)
return form
def submitted(self, ctx, form, data):
print data
| Python |
from zope.interface import Interface
class IType(Interface):
def validate(self, value):
pass
class IStructure(Interface):
pass
class IWidget(Interface):
def render(self, ctx, key, args, errors):
pass
def renderImmutable(self, ctx, key, args, errors):
pass
def processInput(self, ctx, key, args):
pass
class IFormFactory(Interface):
def formFactory(self, ctx, name):
pass
class IFormData(Interface):
pass
class IFormErrors(Interface):
pass
class IKey(Interface):
def key(self):
pass
class ILabel(Interface):
def label(self):
pass
class IConvertible(Interface):
def fromType(self, value):
pass
def toType(self, value):
pass
class IStringConvertible(IConvertible):
pass
class IBooleanConvertible(IConvertible):
pass
class IDateTupleConvertible(IConvertible):
pass
class IFileConvertible(IConvertible):
pass
class ISequenceConvertible(IConvertible):
pass
class IForm( Interface ):
pass
class IValidator(Interface):
def validate(self, field, value):
pass
| Python |
"""A package (for Nevow) for defining the schema, validation and rendering of
HTML forms.
"""
version_info = (0, 12, 0)
version = '.'.join([str(i) for i in version_info])
from nevow import static
from formal.types import *
from formal.validation import *
from formal.widget import *
from formal.widgets.restwidget import *
from formal.widgets.multiselect import *
from formal.widgets.richtextarea import *
from formal.form import Form, Field, Group, ResourceMixin, renderForm
from formal import iformal
def widgetFactory(widgetClass, *a, **k):
def _(original):
return widgetClass(original, *a, **k)
return _
try:
import pkg_resources
except ImportError:
import os.path
defaultCSS = static.File(os.path.join(os.path.split(__file__)[0], 'formal.css'))
formsJS = static.File(os.path.join(os.path.split(__file__)[0], 'js'))
else:
from formal.util import LazyResource
defaultCSS = LazyResource(lambda: static.File(pkg_resources.resource_filename('formal', 'formal.css')))
formsJS = LazyResource(lambda: static.File(pkg_resources.resource_filename('formal', 'js')))
del LazyResource
# Register standard adapters
from twisted.python.components import registerAdapter
from formal import converters
from formal.util import SequenceKeyLabelAdapter
registerAdapter(TextInput, String, iformal.IWidget)
registerAdapter(TextInput, Integer, iformal.IWidget)
registerAdapter(TextInput, Float, iformal.IWidget)
registerAdapter(Checkbox, Boolean, iformal.IWidget)
registerAdapter(DatePartsInput, Date, iformal.IWidget)
registerAdapter(TextInput, Time, iformal.IWidget)
registerAdapter(FileUploadRaw, File, iformal.IWidget)
registerAdapter(TextAreaList, Sequence, iformal.IWidget)
registerAdapter(SequenceKeyLabelAdapter, tuple, iformal.IKey)
registerAdapter(SequenceKeyLabelAdapter, tuple, iformal.ILabel)
registerAdapter(converters.NullConverter, String, iformal.IStringConvertible)
registerAdapter(converters.DateToDateTupleConverter, Date, iformal.IDateTupleConvertible)
registerAdapter(converters.BooleanToStringConverter, Boolean, iformal.IBooleanConvertible)
registerAdapter(converters.BooleanToStringConverter, Boolean, iformal.IStringConvertible)
registerAdapter(converters.IntegerToStringConverter, Integer, iformal.IStringConvertible)
registerAdapter(converters.FloatToStringConverter, Float, iformal.IStringConvertible)
registerAdapter(converters.DateToStringConverter, Date, iformal.IStringConvertible)
registerAdapter(converters.TimeToStringConverter, Time, iformal.IStringConvertible)
registerAdapter(converters.NullConverter, File, iformal.IFileConvertible)
registerAdapter(converters.NullConverter, Sequence, iformal.ISequenceConvertible)
registerAdapter(converters.SequenceToStringConverter, Sequence, iformal.IStringConvertible)
try:
Decimal
except NameError:
pass
else:
registerAdapter(TextInput, Decimal, iformal.IWidget)
registerAdapter(converters.DecimalToStringConverter, Decimal, iformal.IStringConvertible)
del SequenceKeyLabelAdapter
del registerAdapter
| Python |
from twisted.application import internet, service
from nevow import appserver
from formal.examples import main
application = service.Application('examples')
service = internet.TCPServer(8000, main.makeSite())
service.setServiceParent(application)
| Python |
from setuptools import setup, find_packages
setup(
name='formal',
version='0.16.0',
description='HTML forms framework for Nevow',
author='Matt Goodall',
author_email='matt@pollenation.net',
packages=find_packages(),
include_package_data=True,
zip_safe = True,
)
| Python |
# sample Python program to set IPTC data in a JPEG file.
# This puts IPTC data in a format suitable for Flickr to get metadata
# about the photo; it is probably wrong for other uses.
import sys
from optparse import OptionParser
import iptcdata
def check_for_dataset(f, rs):
for ds in f.datasets:
if (ds.record, ds.tag) == rs:
return ds
return None
usage = "set_iptc.py [-c caption] [-t tag,tag,...] [-T title] filename"
parser = OptionParser(usage, version="0.1")
parser.add_option("-c", "--caption", dest="caption", action="store",
type="string", help="Caption data for photo")
parser.add_option("-t", "--tags", dest="tags", action="store",
type="string", help="Tags")
parser.add_option("-T", "--title", dest="title", action="store",
type="string", help="Title for photo")
(options, args) = parser.parse_args()
try:
f = iptcdata.open(args[0])
except IndexError:
print usage
sys.exit(1)
# first do the "title" which flickr wants as a "headline"
if (options.title):
# we want to replace this record set if it is there
print "Setting \'Headline\' to %s" % (options.title)
rs = iptcdata.find_record_by_name("Headline")
ds = check_for_dataset(f, rs)
if (ds == None):
ds = f.add_dataset(rs)
ds.value = options.title
# a "caption" gives the caption
if (options.caption):
#also want just one caption
print "Setting \'Caption\' to %s" % (options.caption)
rs = iptcdata.find_record_by_name("Caption")
ds = check_for_dataset(f, rs)
if (ds == None):
ds = f.add_dataset(rs)
ds.value = options.caption
# now just add tags, as keywords
if (options.tags):
tags = options.tags.split(",")
rs = iptcdata.find_record_by_name("Keywords")
for tag in tags:
print "Setting \'Keyword\' to %s" % (tag)
ds = f.add_dataset(rs)
ds.value = tag
f.save()
f.close()
| Python |
import gdata.photos.service
import gdata.media
import gdata.geo
import urllib
username = "tbfoote@gmail.com"
gd_client = gdata.photos.service.PhotosService()
gd_client.email = username
gd_client.password = 'none'
gd_client.source = 'tullys-exampleApp-1'
gd_client.ProgrammaticLogin()
#album = gd_client.InsertAlbum(title='New album', summary='This is an album')
print "All albums:"
albums = gd_client.GetUserFeed(user=username)
for album in albums.entry:
print 'title: %s, number of photos: %s, id: %s' % (album.title.text,
album.numphotos.text, album.gphoto_id.text)
print "all photos:"
photos = gd_client.GetFeed(
'/data/feed/api/user/%s/albumid/%s?kind=photo' % (
username, album.gphoto_id.text))
for photo in photos.entry:
print 'Photo title:', photo.title.text
print "Getting recent photos"
photos = gd_client.GetUserFeed(kind='photo', limit='10')
for photo in photos.entry:
print 'Recently added photo title:', photo.title.text
#print help(photo)
#url = photo.GetMediaURL()
#urllib.urlretrieve(url, photo.title.text)
#gd_client.Delete(album)
#album_url = '/data/feed/api/user/%s/albumid/%s' % (username, album.gphoto_id.text)
#photo = gd_client.InsertPhotoSimple(album_url, 'New Photo',
# 'Uploaded using the API', 'DSCN4074.jpg', content_type='image/jpeg')
| Python |
#!/usr/bin/env python
#small example program to print out IPTC data from a file
import sys
import iptcdata
try:
f = iptcdata.open(sys.argv[1])
except IndexError:
print "show_iptc.py filename"
if (len(f.datasets) == 0):
print "No IPTC data!"
sys.exit(0)
for ds in f.datasets:
print "Tag: %d\nRecord: %d" % (ds.record, ds.tag)
print "Title: %s" % (ds.title)
descr = iptcdata.get_tag_description(record=ds.record, tag=ds.tag)
print "Description: %s" % (descr)
print "Value: %s" % (ds.value)
print
f.close()
| Python |
#!/usr/bin/env python
import gdata.photos.service
import gdata.media
#import gdata.geo
import sys, os
from optparse import OptionParser
import yaml
import urllib
import iptcdata
import getpass
def check_for_dataset(f, rs):
for ds in f.datasets:
if (ds.record, ds.tag) == rs:
return ds
return None
def check_local_dir(dir_name):
local_dir = os.path.normpath(dir_name)
if not os.path.isdir(local_dir):
print "ERROR: Directory does not exist: %s "%local_dir
###\todo make this except
sys.exit(0)
else:
return local_dir
def find_local_files(a_dir):
a_dir = check_local_dir(a_dir)
images = []
for root, dir, files in os.walk(a_dir):
#print root
#print dir
#print files
for f in files:
fname = os.path.join(root, f)
if fname.startswith(a_dir):
fname = fname[len(a_dir)+1:] # +1 for /
#print fname
basename, ext = os.path.splitext(f)
if ext == '.jpg':
images.append(fname)
#print "appending image %s"%fname
return images
class WebAlbumUploader:
def __init__(self, username, password):
self.username = username
self.password = password
self.slash_str = '>'
self.program_name = 'Tullys WebAlbum Uploader'
self.setup_google_client()
def setup_google_client(self):
self.gd_client = gdata.photos.service.PhotosService()
self.gd_client.email = self.username
self.gd_client.password = self.password
self.gd_client.source = self.program_name
self.gd_client.ProgrammaticLogin()
def list_album_names(self, album_username):
albums = self.gd_client.GetUserFeed(user=album_username)
return set([a.title.text for a in albums.entry])
def find_album(self, album_name, album_username, auto_create=False):
albums = self.gd_client.GetUserFeed(user=album_username)
for album in albums.entry:
if album.title.text == album_name:
return album
if auto_create:
return self.gd_client.InsertAlbum(title=album_name, access="private")
#return self.gd_client.InsertAlbum(title=album_name, access="private", summary='Web Album Uploader Album')
def get_photo_list_from_server(self, album_url):
if not self.gd_client:
return None
return self.gd_client.GetFeed('%s?kind=photo' % (album_url))
def upload_tags(self, filename, gphoto):
try:
iptc_handle = iptcdata.open(filename)
except:
print "iptcdata failed to open %s"%filename
return
if (len(iptc_handle.datasets) == 0):
print "No IPTC data!"
#sys.exit(0)
new_tags = []
for ds in iptc_handle.datasets:
#print "Tag: %d, Record: %d" %(ds.record, ds.tag)
#print "Title: %s"%ds.title
#descr = iptcdata.get_tag_description(record=ds.record, tag=ds.tag)
#print "Description: %s" % (descr)
#print "Value: %s" % (ds.value)
if ds.title == 'Keywords':
new_tags.append(ds.value)
new_tags_str = ', '.join(new_tags)
if not gphoto.media:
gphoto.media = gdata.media.Group()
if not gphoto.media.keywords:
gphoto.media.keywords = gdata.media.Keywords()
#if new keywords upload them again
if not gphoto.media.keywords.text == new_tags_str: ###\todo need to check for title and caption too
print "Uploading Tags"
print "Old tags ", gphoto.media.keywords.text
print "New tags ", new_tags_str
gphoto.media.keywords.text = new_tags_str
gphoto = self.gd_client.UpdatePhotoMetadata(gphoto)
else:
print "Tags up to date."
iptc_handle.close()
def download_tags(self, filename, gphoto):
print "downloading tags for ", filename
try:
iptc_handle = iptcdata.open(filename)
print "Opented iptchandle", filename
except:
print "iptcdata open failed on %s"%filename
return
if (len(iptc_handle.datasets) == 0):
print "No IPTC data!"
#sys.exit(0)
if not gphoto.media:
gphoto.media = gdata.media.Group()
if not gphoto.media.keywords:
gphoto.media.keywords = gdata.media.Keywords()
if gphoto.media.keywords.text:
web_tags = set(gphoto.media.keywords.text.split(', '))
else:
web_tags = set() # this could return, but we need to save and close
old_tags = set()
for ds in iptc_handle.datasets:
#print "Tag: %d, Record: %d" %(ds.record, ds.tag)
#print "Title: %s"%ds.title
#descr = iptcdata.get_tag_description(record=ds.record, tag=ds.tag)
#print "Description: %s" % (descr)
#print "Value: %s" % (ds.value)
if ds.title == 'Keywords':
if ds.value in web_tags:
old_tags.add(ds.value)
new_tags = web_tags - old_tags
rs = iptcdata.find_record_by_name("Keywords")
for tag in new_tags:
ds = iptc_handle.add_dataset(rs)
ds.value = tag
print "adding tag %s"%(tag)
try:
iptc_handle.save()
iptc_handle.close()
print "Closed iptc handle %s"%filename
except:
print "iptcdata save or close failed on %s"%filename
def upload(self, album_name, local_dir, album_user=False):
if not album_user:
album_user = self.username
album_ref = self.find_album(album_name, album_user, True)
if not album_ref:
print >> sys.stderr, "No album found into which to upload."
return False
album_url = '/data/feed/api/user/%s/albumid/%s' % (album_user, album_ref.gphoto_id.text)
for local_filename in find_local_files(os.path.join(local_dir, album_name)):
fullfilename = os.path.join(local_dir, album_name, local_filename)
#print "Looking to upload %s"%i
match_found = False
photo = None
for p in self.get_photo_list_from_server(album_url).entry:
if p.title.text.replace(self.slash_str,'/') == local_filename:
#print "found photo %s"%local_filename
photo = p
break
else:
#print "%s didn't match %s"%(p.title.text, local_filename)
pass
if not photo:
print "Uploading photo %s"%local_filename
print fullfilename
photo = self.gd_client.InsertPhotoSimple(album_url, local_filename.replace('/',self.slash_str),
'Caption: Uploaded using the API', fullfilename, content_type='image/jpeg')
else:
print "Photo %s already uploaded"%fullfilename
self.upload_tags(fullfilename, photo)
return True
def download(self, album_name, local_dir, album_user=False):
print "downloading ", album_name
if not album_user:
album_user = self.username
album_ref = self.find_album(album_name, album_user, False)
if not album_ref:
print "Failed to find album, %s on username %s "%(album_name, album_user)
return False
album_url = '/data/feed/api/user/%s/albumid/%s' % (album_user, album_ref.gphoto_id.text)
for p in self.get_photo_list_from_server(album_url).entry:
filename = p.title.text.replace(self.slash_str,'/')
fullname = os.path.join(local_dir, album_name, filename)
if not os.path.exists(os.path.dirname(fullname)):
os.makedirs(os.path.dirname(fullname))
if not os.path.exists(fullname):
urllib.urlretrieve(p.GetMediaURL(), fullname)
print "Saved %s: "%fullname
else:
print "Already Present, Skipped: %s"%fullname
self.download_tags(fullname, p)
###\todo check for size/checksum and date if older replace
if __name__ == '__main__':
parser = OptionParser(usage="usage: %prog COMMAND FILES", prog='upload')
# parser.add_option("--username", dest="username", default='',
# type="string", help="username to use")
# parser.add_option("--password", dest="password", default='',
# type="string", help="password to use")
# parser.add_option("--album_name", dest="album_name", default='',
# type="string", help="album_name to use")
# parser.add_option("--local_dir", dest="local_dir", default='.',
# type="string", help="local_dir to use")
options, args = parser.parse_args()
possible_cmds = ["upload", "download", "downloadall"]
if len(args) < 1:
parser.error("Please enter a command")
cmd = args[0]
if cmd not in possible_cmds:
parser.error("Command must be either 'upload' or 'download'")
if len(args) < 2:
parser.error("Command %s requires additional arguments of yaml files"%cmd)
yaml_files = args[1:]
for f in yaml_files:
if not os.path.exists(f):
parser.error("File: %s doesn't exits."%f)
with open(f) as fh:
file_text = fh.read()
try:
file_map = yaml.load(file_text)
except yaml.YAMLError, exc:
parser.error("Failed parsing yaml while processing %s\n"%path, exc)
#print "yaml result is ", file_map
required_fields = set(["username", "album", "album_username", "local_path"])
missing_fields = required_fields - set(file_map.keys())
extra_fields = set(file_map.keys()) - required_fields
#print "missing fields = ", missing_fields
#print "extra fields = ", extra_fields
password = getpass.getpass("Please enter password for username %s:"%file_map["username"])
uploader = WebAlbumUploader(file_map["username"], password)
if cmd == "upload":
uploader.upload(file_map["album"], file_map["local_path"], file_map["album_username"])
if cmd == "download":
uploader.download(file_map["album"], file_map["local_path"], file_map["album_username"])
if cmd == "downloadall":
albums = uploader.list_album_names(file_map["album_username"])
for a in albums:
print "album name", a, " of ",albums
uploader.download(a, file_map["local_path"], file_map["album_username"])
| Python |
#!/usr/bin/env python
import subprocess
import os
from optparse import OptionParser
def run(cmd_str):
cmd = cmd_str.split()
print "Running cmd: %s"%cmd
subprocess.check_call(cmd)
parser = OptionParser()
parser.add_option("-o", "--outdir", dest="outdir",
help="write files to outdir", metavar="DIRECTORY")
parser.add_option("-i", "--indir", dest="indir",
help="read files from indir", metavar="DIRECTORY")
#parser.add_option("-q", "--quiet",
# action="store_false", dest="verbose", default=True,
# help="don't print status messages to stdout")
(options, args) = parser.parse_args()
if not options.outdir:
parser.warn("Using outdir of '.'")
if not os.path.exists(options.outdir):
os.makedirs(options.outdir)
files = []
for a in args:
if not os.path.exists(a):
print "Argument '%s' invalid"%a
continue
files.append(a)
if options.indir:
for a in [os.path.join(options.indir, e) for e in os.listdir(options.indir)]:
if os.path.isfile(a):
files.append(a)
else:
print a, "is not a file"
for f in files:
basename = os.path.basename(f)
(filename, ext) = os.path.splitext(basename)
outfile = "%s"%os.path.join(options.outdir, filename+".tiff")
try:
cmd = "convert %s %s"%(f, outfile)
run(cmd)
cmd = "exiftool -tagsfromfile %s -overwrite_original_in_place -exif:all %s"%(f, outfile)
run(cmd)
except CalledProcessError, ex:
print "Failed %s"%ex
| Python |
# Used successfully in Python2.5 with matplotlib 0.91.2 and PyQt4 (and Qt 4.3.3)
from distutils.core import setup
import py2exe
# We need to import the glob module to search for all files.
import glob
# We need to exclude matplotlib backends not being used by this executable. You may find
# that you need different excludes to create a working executable with your chosen backend.
# We also need to include include various numerix libraries that the other functions call.
opts = {
'py2exe': { "includes" : [ "matplotlib.backends", "matplotlib.backends.backend_qt4agg",
"matplotlib.figure","pylab", "numpy", "matplotlib.numerix.fft",
"matplotlib.numerix.linear_algebra", "matplotlib.numerix.random_array",
"matplotlib.backends.backend_tkagg"],
'excludes': ['_gtkagg', '_tkagg', '_agg2', '_cairo', '_cocoaagg',
'_fltkagg', '_gtk', '_gtkcairo', ],
'dll_excludes': ['libgdk-win32-2.0-0.dll',
'libgobject-2.0-0.dll']#,'bundle_files': 2,'optimize': 2
}
}
## opts = {
## 'py2exe': { "includes" : ["sip", "PyQt4._qt", "matplotlib.backends", "matplotlib.backends.backend_qt4agg",
## "matplotlib.figure","pylab", "numpy", "matplotlib.numerix.fft",
## "matplotlib.numerix.linear_algebra", "matplotlib.numerix.random_array",
## "matplotlib.backends.backend_tkagg"],
## 'excludes': ['_gtkagg', '_tkagg', '_agg2', '_cairo', '_cocoaagg',
## '_fltkagg', '_gtk', '_gtkcairo', ],
## 'dll_excludes': ['libgdk-win32-2.0-0.dll',
## 'libgobject-2.0-0.dll']
## }
## }
# Save matplotlib-data to mpl-data ( It is located in the matplotlib\mpl-data
# folder and the compiled programs will look for it in \mpl-data
# note: using matplotlib.get_mpldata_info
data_files = [(r'mpl-data', glob.glob(r'C:\Python25\Lib\site-packages\matplotlib\mpl-data\*.*')),
# Because matplotlibrc does not have an extension, glob does not find it (at least I think that's why)
# So add it manually here:
(r'mpl-data', [r'C:\Python25\Lib\site-packages\matplotlib\mpl-data\matplotlibrc']),
(r'mpl-data\images',glob.glob(r'C:\Python25\Lib\site-packages\matplotlib\mpl-data\images\*.*')),
(r'mpl-data\fonts',glob.glob(r'C:\Python25\Lib\site-packages\matplotlib\mpl-data\fonts\*.*'))]
# for console program use 'console = [{"script" : "scriptname.py"}]
setup(windows=[{"script" : "formak.py"}], options=opts, data_files=data_files)
## ** searching for required modules ***
## Traceback (most recent call last):
## File "setup.py", line 35, in <module>
## setup(windows=[{"script" : "formak.py"}], options=opts, data_files=data_fi
## les)
## File "C:\Python25\lib\distutils\core.py", line 151, in setup
## dist.run_commands()
## File "C:\Python25\lib\distutils\dist.py", line 974, in run_commands
## self.run_command(cmd)
## File "C:\Python25\lib\distutils\dist.py", line 994, in run_command
## cmd_obj.run()
## File "C:\Python25\Lib\site-packages\py2exe\build_exe.py", line 243, in run
## self._run()
## File "C:\Python25\Lib\site-packages\py2exe\build_exe.py", line 296, in _run
## self.find_needed_modules(mf, required_files, required_modules)
## File "C:\Python25\Lib\site-packages\py2exe\build_exe.py", line 1297, in find_n
## eeded_modules
## mf.import_hook(mod)
## File "C:\Python25\Lib\site-packages\py2exe\mf.py", line 719, in import_hook
## return Base.import_hook(self,name,caller,fromlist,level)
## File "C:\Python25\Lib\site-packages\py2exe\mf.py", line 136, in import_hook
## q, tail = self.find_head_package(parent, name)
## File "C:\Python25\Lib\site-packages\py2exe\mf.py", line 204, in find_head_pack
## age
##
## ImportError: No module named sip
## D:\python\formak>
| Python |
import UserModel
import LinRel
import os
'''
-----------------------------------------------------------------------------------------
Class to test the performance of LinRel algorithm
For using, determine:
File = 'features_lewis'
numberofImages = 1000
setsize = 10
expnumber = 100
Writes statistics to /Statistics/filename number_of_images_LinRel.average(chosen,minimum)
------------------------------------------------------------------------------------------
'''
class Experiment(object):
MAXDISTANCE = 0.01
MAXITERATIONS = 100
def __init__(self, filename, number_of_images, setsize=10):
self.setsize = setsize
self.number_of_images = number_of_images
self.user = UserModel.UserModel(self.number_of_images, self.setsize, filename)
self.target = self.user.getTarget()
print 'Target = ', self.target
self.path = os.path.dirname(__file__) + '-files/'
self.input_average = self.path + filename + str(self.number_of_images) + '_' + 'LR.average'
self.input_chosen = self.path + filename + str(self.number_of_images) + '_' + 'LR.chosen'
self.input_minimum = self.path + filename + str(self.number_of_images) + '_' + 'LR.minimum'
self.lr = LinRel.LinRel(filename, number_of_images)
def Run(self):
average_distances = []
chosen_distances = []
minimum_distances = []
chosen_image = None
# chosen_dist = 1
iteration = 1
# First iteration
images = self.lr.ChooseFirstImageSet(setsize)
# print 'Images = ', images
chosen_image, relevance_scores, average_dist, chosen_dist, minimum_dist = self.user.Select(images)
# print 'Chosen image = ', chosen_image
average_distances.append(average_dist)
chosen_distances.append(chosen_dist)
minimum_distances.append(minimum_dist)
while(chosen_dist > Experiment.MAXDISTANCE) and iteration < Experiment.MAXITERATIONS:
# print 'Iteration ', iteration
iteration += 1
#In oder to check how random algorithms performs comparing to LinRel
#images = self.lr.ChooseFirstImageSet(setsize)
images = self.lr.LinRel(images, relevance_scores, setsize)
# print 'Images = ', images
chosen_image, relevance_scores, average_dist, chosen_dist, minimum_dist = self.user.Select(images)
# Collect statistics
average_distances.append(average_dist)
chosen_distances.append(chosen_dist)
minimum_distances.append(minimum_dist)
# print 'Chosen image = ', chosen_image
Terminated = False
if iteration < Experiment.MAXITERATIONS:
print 'We have found the target!'
print 'Number of iterations = ', iteration
Terminated = True
while len(chosen_distances) < Experiment.MAXITERATIONS:
average_distances.append(0)
chosen_distances.append(0)
minimum_distances.append(0)
return Terminated, average_distances, chosen_distances, minimum_distances, iteration
File = 'features-1000'
numberofImages = 1000
setsize = 10
expnumber = 100
iterations = 0
for i in range(expnumber):
exp = Experiment(File, numberofImages, setsize)
Terminated, average_distance, chosen_distance, minimum_distance, iteration = exp.Run()
iterations += iteration
if i==0:
# Clear files
f=open(exp.input_average, 'w')
f.writelines('')
f.close()
f=open(exp.input_chosen, 'w')
f.writelines('')
f.close()
f=open(exp.input_minimum, 'w')
f.writelines('')
f.close()
str_average_distance = map(str, average_distance)
average_distance_write = ' '.join(str_average_distance)+'\n'
f=open(exp.input_average, 'a')
f.writelines(average_distance_write)
str_chosen_distance = map(str, chosen_distance)
chosen_distance_write = ' '.join(str_chosen_distance)+'\n'
f=open(exp.input_chosen, 'a')
f.writelines(chosen_distance_write)
str_minimum_distance = map(str, minimum_distance)
minimum_distance_write = ' '.join(str_minimum_distance)+'\n'
f=open(exp.input_minimum, 'a')
f.writelines(minimum_distance_write)
print 'Average number of iteration = ', 1.0*iterations/expnumber | Python |
import numpy
import os
from scipy import spatial
import math
'''#########################################################'''
'''################## Initialisation ##################'''
'''#########################################################'''
# Number of model vectors
grid_nodes_num = 3
grid_dimentionality = 2
clusters_num = grid_nodes_num**grid_dimentionality
datafile = os.path.dirname(__file__) + '-files/features-100'
'''##########################################################################'''
'''################## Distances between model vectors ##################'''
'''##########################################################################'''
'''# initialise model vectors
if grid_dimentionality == 1:
model_vectors = numpy.arange(clusters_num).reshape(grid_nodes_num)
if grid_dimentionality == 2:
model_vectors = numpy.arange(clusters_num).reshape(grid_nodes_num, grid_nodes_num)
if grid_dimentionality == 3:
model_vectors = numpy.arange(clusters_num).reshape(grid_nodes_num, grid_nodes_num, grid_nodes_num)'''
# Store SQUARED distances between vector models
grid_distances = numpy.zeros((clusters_num,clusters_num))
if grid_dimentionality == 1:
model1 = 0
for x1 in range(grid_nodes_num):
model2 = 0
for x2 in range(grid_nodes_num):
squared_distance = (x1-x2)**2
grid_distances[model1,model2]=squared_distance
model2 += 1
model1 += 1
if grid_dimentionality == 2:
model1 = 0
for x1 in range(grid_nodes_num):
for y1 in range(grid_nodes_num):
model2 = 0
for x2 in range(grid_nodes_num):
for y2 in range(grid_nodes_num):
squared_distance = (x1-x2)**2+(y1-y2)**2
grid_distances[model1,model2]=squared_distance
model2 += 1
model1 += 1
if grid_dimentionality == 3:
model1 = 0
for x1 in range(grid_nodes_num):
for y1 in range(grid_nodes_num):
for z1 in range(grid_nodes_num):
model2 = 0
for x2 in range(grid_nodes_num):
for y2 in range(grid_nodes_num):
for z2 in range(grid_nodes_num):
squared_distance = (x1-x2)**2+(y1-y2)**2+(z1-z2)**2
grid_distances[model1,model2]=squared_distance
model2 += 1
model1 += 1
'''-------------------------------- Step 1 --------------------------------------'''
'''##############################################################################'''
'''################## Load data, initialise model vectors ##################'''
'''##############################################################################'''
def Init(datafile):
datapoint = numpy.loadtxt(datafile)
datapoints_num = datapoint.shape[0]
datapoints_dimensionality = datapoints.shape[1]
model_vectors = numpy.zeros((clusters_num, datapoints_dimensionality))
for dimension in range(datapoints_dimensionality):
maxvalue = numpy.max(datapoints[:,dimension])
minvalue = numpy.min(datapoints[:,dimension])
vector = numpy.random.uniform(minvalue, maxvalue, clusters_num)
model_vectors[:,dimension] = vector.T
return datapoints, model_vectors
def AssignDatapoints(datapoints, model_vectors):
cluster_to_datapoint = dict()
distances_datapoints_to_clusters = spatial.distance.cdist(datapoints, model_vectors)
datapoint_to_cluster = numpy.argmin(distances_datapoints_to_clusters, axis=1)
for cluster in range(clusters_num):
cluster_to_datapoint[cluster] = numpy.where(datapoint_to_cluster==cluster)[0]
return datapoint_to_cluster, cluster_to_datapoint
sigma0 = 1
lambda_time = 0.5
def AssignModelvectors(datapoints,cluster_to_datapoint, time):
sigma = sigma0*math.exp(-time/lambda_time)
numpy.exp(-grid_distances/(2.0*sigma))
datapoints, model_vectors = Init(datafile)
AssignDatapoints(datapoints, model_vectors) | Python |
from ete2 import Tree
import UserModel
import MCTS
import os
class Experiment(object):
MAXDISTANCE = 0.01
MAXITERATIONS = 100
def __init__(self, filename, number_of_images, setsize=10):
self.setsize = setsize
self.number_of_images = number_of_images
self.user = UserModel.UserModel(self.number_of_images, self.setsize, filename)
self.target = self.user.getTarget()
#print 'Target image = ', self.user.target
#self.mcts = MCTS.OMC(filename, proximity_type, clustering_type, number_of_images, self.target)
self.treesearch = MCTS.GAMMA(filename, number_of_images, self.target)
def Run(self):
chosen_image = None
chosen_distance = 1
iteration = 0
'''images = self.mcts.RandomImages(self.setsize)
chosen_image = self.user.Select(images)
self.mcts.ModifyTree(images, chosen_image)'''
avnodes = []
while(chosen_distance > Experiment.MAXDISTANCE) and iteration < Experiment.MAXITERATIONS:
iteration += 1
# print 'Iteration number', iteration
images, avnodes_to_chosen_image = self.treesearch.ChooseImages(self.setsize)
avnodes.append(avnodes_to_chosen_image)
#print 'Images = ', images
# chosen_image, chosen_distance = self.user.Select(images)
chosen_image, relevance_scores, average_distance, chosen_distance, minimum_distance = self.user.Select(images)
#print 'Chosen image = ', chosen_image
distance_to_target = self.treesearch.ModifyTree(images, chosen_image)
##### print distance_to_target
#print 'We have found the target!'
print 'Number of iterations = ', iteration
Terminated = False
if iteration < Experiment.MAXITERATIONS:
Terminated = True
return Terminated, avnodes, iteration
File = 'features-1000'
NumberofImages = 1000
setsize = 10
fileResultAvNodes = os.path.dirname(__file__) + '-files/' + 'AvegerageNodes1' + File
#f=open(fileResultAvNodes, 'w')
#f.writelines('')
#f.close()
expnumber = 100
iterations = 0
for i in range(expnumber):
print 'Experiment number = ', i
exp = Experiment(File, NumberofImages, setsize)
Terminated, avnode, iteration = exp.Run()
iterations += iteration
if Terminated:
while len(avnode) < Experiment.MAXITERATIONS:
avnode.append(0)
stravnode = map(str, avnode)
avnodewrite = ' '.join(stravnode)+'\n'
f=open(fileResultAvNodes, 'a')
f.writelines(avnodewrite)
else:
print 'Failed'
f.close()
print (1.0*iterations/expnumber) | Python |
import numpy
import os
from ete2 import Tree
'''filename = os.path.dirname(__file__) + '-files/' + 'test'
mu, sigma = 1.5, 1
s11 = numpy.random.normal(mu, sigma, 100)
mu, sigma = 3.5, 0.8
s12 = numpy.random.normal(mu, sigma, 100)
mu, sigma = 4.5, 1.2
s13 = numpy.random.normal(mu, sigma, 100)
mu, sigma = 7.5, 1
s14 = numpy.random.normal(mu, sigma, 100)
s1 = numpy.hstack((s11, s12, s13, s14))
mu, sigma = 10, 1.3
s21 = numpy.random.normal(mu, sigma, 100)
mu, sigma = 10.5, 1
s22 = numpy.random.normal(mu, sigma, 100)
mu, sigma = 4, 1.1
s23 = numpy.random.normal(mu, sigma, 100)
mu, sigma = 4.5, 1
s24 = numpy.random.normal(mu, sigma, 100)
s2 = numpy.hstack((s21, s22, s23, s24))
numpy.savetxt(filename, zip(s1,s2))
print numpy.load(filename+'.npy')'''
'''print Tree(os.path.dirname(__file__) + '-files/' + 'test_tree.nw')'''
'''data = numpy.loadtxt(os.path.dirname(__file__) + '-files/features-5000_Euclidean.dist')
print data
numpy.save(os.path.dirname(__file__) + '-files/features-5000_Euclidean.dist', data)
'''
'''data = numpy.load(os.path.dirname(__file__) + '-files/features-1000_Euclidean.dist.npy')
print data'''
print Tree(os.path.dirname(__file__) + '-files/features-100_tree.nw') | Python |
from ete2 import Tree
import numpy
import math
import linecache
import os
from scipy.io.numpyio import fwrite
'''
-----------------------------------------------------------------------------------------------------------------
class PathProximity helps to calculate distances between pathes in the tree
INPUT: tree in the file self.tree
OUTPUT: call function CalculateDistance() and it will return a numpy matrix of distances
distances can be written to a file for example: numpy.save(output, distance) and read numpy.load(output + '.npy')
------------------------------------------------------------------------------------------------------------------
'''
class PathProximity(object):
def __init__(self, filename, number_of_images):
self.number_of_images = number_of_images
self.tree = Tree(filename + '_tree.nw')
def PathDistance(self, image1, image2):
node1 = self.tree.search_nodes(name = str(image1))[0]
node2 = self.tree.search_nodes(name = str(image2))[0]
root = self.tree.get_tree_root()
ancestor = self.tree.get_common_ancestor(node1, node2)
root_ancestor = self.tree.get_distance(root, ancestor, topology_only=True)
root_node1 = self.tree.get_distance(root, node1, topology_only=True)
root_node2 = self.tree.get_distance(root, node2, topology_only=True)
return 1-((2*root_ancestor)/(root_node1+root_node2))
def CalculateDistances(self):
imageSet1 = range(self.number_of_images)
imageSet2 = range(self.number_of_images)
path_distances = numpy.zeros((len(imageSet1), len(imageSet2)))
for image1 in imageSet1:
print 'image1 = ', image1
i = 0
for image2 in imageSet2:
path_distances[image1, i] = self.PathDistance(image1, image2)
i += 1
return path_distances
filename = os.path.dirname(__file__) + '-files/' + 'features-100'
number_of_images = 100
pp = PathProximity(filename, number_of_images)
distance = pp.CalculateDistances()
numpy.save(filename + '_tree-distances', distance)
numpy.savetxt(filename + '_txt_tree-distances', distance)
class SimpleProximity(object):
INPUT_PATH = os.path.dirname(__file__) + '/Input/'
L = 0.5
def __init__(self, filename, proximity_type, number_of_images):
self.number_of_images = number_of_images
self.proximity_type = proximity_type
self.input = SimpleProximity.INPUT_PATH + filename + str(number_of_images)
def PathDistance(self, image1, image2):
vector1 = numpy.array(self.GetVector(image1))
vector2 = numpy.array(self.GetVector(image2))
if self.proximity_type == 'Euclidean':
distance = math.sqrt(sum((vector1 - vector2)**2))
elif self.proximity_type == 'Manhattan':
distance = sum(abs(vector1-vector2))
elif self.proximity_type == 'Maximum':
distance = max(vector1-vector2)
elif self.proximity_type == 'Mahalanoibis':
matrix = numpy.vstack((vector1,vector2)).T
covariance = numpy.cov(matrix)
distance = math.sqrt(numpy.dot(numpy.dot((vector1-vector2),numpy.linalg.pinv(covariance)),(vector1-vector2).T))
elif self.proximity_type == 'Cosine':
distance = 1-numpy.dot(vector1, vector2)/(math.sqrt(sum((vector1)**2))*math.sqrt(sum((vector2)**2)))
distance = numpy.exp(-(distance)/(2*(SimpleProximity.L**2)))
return distance
def GetVector(self, number):
# Get vector from line #number from file input
# number starts from 1
line = linecache.getline(self.input, number+1)
return map(float, line.split())
def SetDistances(self, imageSet1, imageSet2):
distances = numpy.zeros((len(imageSet1), len(imageSet2)))
for image1 in imageSet1:
i = 0
for image2 in imageSet2:
distances[image1, i] = self.PathDistance(image1, image2)
i += 1
return distances
# Calculate kernel
'''
file = 'features_lewis'
number_of_images = 1000
output = os.path.dirname(__file__) + '/ProximityMatrix/' + file + str(number_of_images) + '_kernel.dist'
sp = SimpleProximity(file, 'Euclidean', number_of_images)
distancematrix = sp.SetDistances(range(number_of_images), range(number_of_images))
numpy.savetxt(output, distancematrix) '''
'''
filename = 'features_lewis'
proximity_type = 'Euclidean'
clustering_type = 'kmeans'
number_of_images = 1000
pp = PathProximity(filename, proximity_type, clustering_type, number_of_images)
distance = pp.CalculateDistances()
#for image1 in range(number_of_images):
# for image2 in range(number_of_images):
# pp.path_distances[image1, image2] = pp.PathDistance(image1, image2)
# print image1
output = os.path.dirname(__file__) + '/ProximityMatrix/'+str(number_of_images) +'_' + proximity_type + '_' + clustering_type + '.treekernel'
numpy.save(output, distance)
print numpy.load(output + '.npy')
''' | Python |
import random
import linecache
import numpy
import os
'''
----------------------------------------------------------------------------------------------------------
User model used in all sets of experiments
Uses distances (always Euclidean) from /ProximityMatrix/ + filename + number_of_images + '_Euclidean.dist'
The main method Select takes a list of objects and returns
chosen_image, relevance_scores, average_distance, chosen_distance, minimum_distance
----------------------------------------------------------------------------------------------------------
'''
class UserModel(object):
SHARPNESS = -1
PATH_PROXIMITY = os.path.dirname(__file__) + '/ProximityMatrix/'
NOISE = 0.3
def __init__(self, number_of_images, setsize, filename):
self.filename = filename
self.number_of_images = number_of_images
self.setsize = setsize
self.target = random.randint(0, self.number_of_images-1)
#self.target = 0
''' Distance file can be path kernel or Euclidean distances
-----------------------------------------------------------------------------------------------------------'''
'''self.distance_file = os.path.dirname(__file__) + '-files/' + filename + '_tree-distances.npy'''
self.distance_file = os.path.dirname(__file__) + '-files/' + filename + '_Euclidean.dist.npy'
self.distance_matrix = numpy.load(self.distance_file)
def getTarget(self):
return self.target
def Select(self, images):
# print images
relevance_scores = dict()
average_distance = 0
minimum_distance = 0
distances_line = self.GetVector(self.target)
distances_to_target = []
for image in images:
distances_to_target.append(distances_line[image])
# print 'distance to target ', distances_to_target
distances_to_target = numpy.array((distances_to_target))
average_distance = numpy.mean(distances_to_target)
minimum_distance = numpy.min(distances_to_target)
# print 'Average distance to target = ', average_distance
similarities_to_target = distances_to_target**UserModel.SHARPNESS
probabilities = (1-UserModel.NOISE)*similarities_to_target/sum(similarities_to_target)+UserModel.NOISE/self.setsize
chosen_index, relevance = self.Sample(probabilities)
i = 0
for image in images:
relevance_scores[image] = relevance[i]
i += 1
chosen_image = images[chosen_index]
chosen_distance = distances_to_target[chosen_index]
if self.target in images:
chosen_image = self.target
chosen_distance = 0
return chosen_image, relevance_scores, average_distance, chosen_distance, minimum_distance
def Sample (self, probabilities):
# print 'Probabilities = ', probabilities
relevance_scores = []
r = random.random()
cumulative_sum = probabilities[0]
index = 0
while cumulative_sum < r:
relevance_scores.append(0)
index += 1
cumulative_sum = cumulative_sum + probabilities[index]
chosen_image = index
relevance_scores.append(1)
while len(relevance_scores)<len(probabilities):
relevance_scores.append(0)
return chosen_image, relevance_scores
def GetVector(self, number):
# Get vector from line #number from file input
# number starts from 1
''' Distance file can be path kernel or Euclidean distances
-----------------------------------------------------------------------------------------------------------
distance_file = UserModel.PATH_PROXIMITY + self.filename + str(self.number_of_images) + '_Euclidean.dist' '
line = linecache.getline(distance_file, number+1)
return map(float, line.split())'''
return self.distance_matrix[number]
| Python |
import numpy
import linecache
import os
import random
'''
LinRel algorithm
Uses distance matrix from '/ProximityMatrix/features_lewis1000_Euclidean.dist'
The algorithm is called in ExperimentLinRel
'''
class LinRel(object):
MU = 0.5
C = 0.4
E = 0.001
def __init__(self, filename, N):
self.number_of_images = N
self.previous_images = []
self.images_presented = numpy.array(())
self.relevance_scores = numpy.array(())
self.input = os.path.dirname(__file__) + '-files/'+ filename + '_Euclidean.dist.npy'
self.distances = numpy.load(self.input)
'''self.input = os.path.dirname(__file__) + '-files/'+ filename
self.distances = numpy.loadtxt(self.input)'''
def ChooseFirstImageSet(self, setsize):
chosen_images = []
while len(chosen_images) < setsize:
image = random.randint(0, self.number_of_images-1)
if image not in chosen_images:
chosen_images.append(image)
# save images as been presented
self.previous_images = chosen_images
return chosen_images
def GetImageVector(self, number):
'''# Get vector from line #number from file input
# number starts from 1
line = linecache.getline(self.input, number+1)
image = numpy.array((map(float, line.split())))
# return numpy.exp(image)
return numpy.array(image)'''
return self.distances[number]
# for sample-docs
#return map(float, line.split()[1:])
# Learning function
# User_feedback is a dictionary with keywords and their weighs about which we got the feedback
def LinRel(self, images, relevance_scores, setsize):
selectioncriteria = []
# Matrix representing topic models for documents that have already been presented
for image in relevance_scores.keys():
imagevector = self.GetImageVector(image)
# For all keywords from user feedback, add them to arrays of keywords_presented and the user feedback about them to relevance_scores
if (numpy.shape(self.images_presented)[0]==0):
self.images_presented = imagevector
self.relevance_scores = numpy.array(relevance_scores[image])
else:
self.images_presented = numpy.vstack((self.images_presented, imagevector))
self.relevance_scores = numpy.hstack((self.relevance_scores, relevance_scores[image]))
# LinRel computations
# Diagonal matrix with mu on the diagonal
Mu = LinRel.MU*numpy.eye(numpy.shape(self.images_presented)[1])
# temporary variable which is the same for all images
temp = numpy.linalg.inv(numpy.dot(self.images_presented.T, self.images_presented)+Mu)
# For all the keywords
for image in range(self.number_of_images):
# Keyword representation in terms of article tf-idf for every keyword
xI = self.GetImageVector(image)
aI = numpy.dot(numpy.dot(xI,temp),self.images_presented.T)
# Calculate the criteria by which to decide with document to choose next
# Upper confidence bound on score of the keyword
# To prevent 0 feedback on the first iteration we add small number E to relevance scores values
# But still the relevance scores values are not changed and words are put into the stop list when they get 0
#selectioncriteria.append(float(numpy.dot(aI, self.relevance_scores.T+LinRel.E)+LinRel.C/2*numpy.dot(aI, aI.T)))
selectioncriteria.append(float(numpy.dot(aI, self.relevance_scores.T)+LinRel.C/2*numpy.dot(aI, aI.T)))
chosen_images = []
indeces = numpy.argsort(numpy.array(selectioncriteria))
i = 0
while len(chosen_images) < setsize:
# starting from the last image
image = indeces[len(indeces)-i-1]
if image not in self.previous_images:
chosen_images.append(image)
i += 1
self.previous_images = chosen_images
return chosen_images | Python |
import linecache
import math
import numpy
from scipy import spatial
import os
'''
---------------------------------------------------------------------------------
Class to calculate distances for instances in lines of file self.input
Writes the result in ProximityMatrix folder, filename depends on type of distance
possible types: Euclidean, Manhattan, Maximum, Mahalanoibis, Cosine, LinRel
To run it create an object of class Proximity with filename parameter:
p = Proximity('sample-docs1000')
Call the finction CalculateDistance with distance type parameter
p.CalculateDistance('LinRel')
----------------------------------------------------------------------------------
'''
class Proximity(object):
def __init__(self, filename):
self.input = filename
def GetNumberofLines():
lines = 0
for line in open(self.input):
lines += 1
return lines
def GetNumberofColumns():
line = linecache.getline(self.input, 1)
return len(line.split())
self.output = ''
self.lines = GetNumberofLines()
# for sample-docs
self.columns = GetNumberofColumns() - 1
# self.columns = GetNumberofColumns()
self.ProximityMatrix = numpy.zeros((self.lines, self.lines))
def GetVector(self, number):
# Get vector from line #number from file input
# number starts from 1
line = linecache.getline(self.input, number)
# for sample-docs
return map(float, line.split()[1:])
# return map(float, line.split())
def CalculateDistance(self, type):
self.ClearOutput(type)
ImagesVectors = numpy.zeros((self.lines, self.columns))
print 'Start reading file'
for i in range(1,self.lines+1):
ImagesVectors[i :] = self.GetVector(i)
print 'Start calculating distances'
for i in range(self.lines):
print 'Calculating distance = ', i
strdistance = ''
vector1 = ImagesVectors[i,:]
distances = []
for j in range(self.lines):
vector2 = ImagesVectors[j,:]
distance = self.Distance(type, vector1, vector2)
distances.append(distance)
self.ProximityMatrix[i,:] = distances
numpy.savetxt(self.output, self.ProximityMatrix)
def ClearFile(self, filename):
f=open(filename, 'w')
f.writelines('')
f.close()
def ClearOutput(self, type):
if type == 'Euclidean':
self.output = self.input +'_Euclidean.dist'
elif type == 'Manhattan':
self.output = self.input +'_Manhattan.dist'
elif type == 'Maximum':
self.output = self.input +'_Maximum.dist'
elif type == 'Mahalanoibis':
self.output = self.input + '_Mahalanoibis.dist'
elif type == 'Cosine':
self.output = self.input +'_Cosine.dist'
elif type == 'LinRel':
self.output = self.input +'_LinRel.dist'
self.ClearFile(self.output)
def Distance(self, type, vector1, vector2):
if type == 'Euclidean':
distance = math.sqrt(sum((vector1 - vector2)**2))
elif type == 'Manhattan':
distance = sum(abs(vector1-vector2))
elif type == 'Maximum':
distance = max(vector1-vector2)
elif type == 'Mahalanoibis':
matrix = numpy.vstack((vector1,vector2)).T
covariance = numpy.cov(matrix)
distance = math.sqrt(numpy.dot(numpy.dot((vector1-vector2),numpy.linalg.pinv(covariance)),(vector1-vector2).T))
elif type == 'Cosine':
distance = 1-numpy.dot(vector1, vector2)/(math.sqrt(sum((vector1)**2))*math.sqrt(sum((vector2)**2)))
elif type == 'LinRel':
distance = numpy.sqrt(sum((numpy.exp(vector1)-numpy.exp(vector2))**2))
return distance
#p = Proximity('features_lewis5000')
#p.CalculateDistance('Euclidean')
'''p = Proximity('sample-docs1000')
p.CalculateDistance('LinRel')'''
infile = os.path.dirname(__file__) + '-files/test'
p = Proximity(infile)
p.CalculateDistance('Euclidean') | Python |
'''
---------------------------------------------------------------------------------------------------
Name takes origine from Monte Carlo Tree Search
From Monte Carlo Tree Search takes only idea of navigating through the tree when looking for target
Includes a number of classes for different search strategies:
RANDOM - Randomly sample each path
THOMPSON - Use Thompson sampling strategy to generate paths
OMC - Objective Monte Carlo
UCT - UCB for trees - upper confidence bounds for trees
All methods use tree structure from:
/Tree/ + filename + number_of_images + proximity_type + clustering_type + .nw
---------------------------------------------------------------------------------------------------
'''
from ete2 import Tree
import random
import numpy
import math
import scipy.special
import os
class RANDOM(object):
TREE_PATH = '/home/konyushk/workspace/MCTS/Tree/'
def __init__(self, filename, proximity_type, clustering_type, number_of_images, target):
self.previous_images = []
self.number_of_images = number_of_images
self.tree = Tree(UCT.TREE_PATH + filename + str(self.number_of_images) + '_' + proximity_type + '_' + clustering_type + '.nw')
self.chosen_node = None
self.target = target
def ModifyTree(self, images, chosen_image):
node = self.tree.search_nodes(name = str(chosen_image))[0]
self.chosen_node = node
self.previous_images = images[:]
target_node = self.tree.search_nodes(name = str(self.target))[0]
nodes_to_target_from_chosen = self.tree.get_distance(target_node, self.chosen_node, topology_only=True)
return nodes_to_target_from_chosen
def ChooseImages(self, setsize):
nodes_to_chosen_image = 0
images = []
while len(images) < setsize:
current_node = self.tree.get_tree_root()
while not current_node.is_leaf():
max_selection_criteria = 0
for node in current_node.get_children():
selection_criteria = random.random()
if selection_criteria > max_selection_criteria:
max_selection_criteria = selection_criteria
max_node = node
current_node = max_node
if int(current_node.name) not in images:
if int(current_node.name) not in self.previous_images:
nodes_to_chosen_image += self.tree.get_distance(current_node, self.chosen_node, topology_only=True)
images.append(int(current_node.name))
avnodes_to_chosen_image = nodes_to_chosen_image/setsize
return images, avnodes_to_chosen_image
class THOMPSON(object):
TREE_PATH = '/home/konyushk/workspace/MCTS/Tree/'
ALPHA = 1
BETA = 1
def __init__(self, filename, proximity_type, clustering_type, number_of_images, target):
self.previous_images = []
self.number_of_images = number_of_images
self.tree = Tree(THOMPSON.TREE_PATH + filename + str(self.number_of_images) + '_' + proximity_type + '_' + clustering_type + '.nw')
self.chosen_node = None
# Add alpha and beta features to the tree
for node in self.tree.traverse('postorder'):
prior_success = 10/float(len(node.get_leaves()))
#node.add_features(alpha = THOMPSON.ALPHA, beta = THOMPSON.BETA, isUpdated = False)
node.add_features(alpha = prior_success, beta = THOMPSON.BETA, isUpdated = False)
self.target = target
def ModifyTree(self, images, chosen_image):
for node in self.tree.traverse('postorder'):
node.isUpdated = False
self.previous_images = images[:]
images.remove(chosen_image)
not_chosen_images = images
node = self.tree.search_nodes(name = str(chosen_image))[0]
self.chosen_node = node
node = node.up
# print 'Chosen image parameters = ', node.alpha, ', ', node.beta
while node:
node.alpha += 1
node.isUpdated = True
node = node.up
for image in not_chosen_images:
node = self.tree.search_nodes(name = str(image))[0]
node = node.up
while node:
if node.isUpdated == False:
node.beta += 1
node.isUpdated = True
node = node.up
target_node = self.tree.search_nodes(name = str(self.target))[0]
nodes_to_target_from_chosen = self.tree.get_distance(target_node, self.chosen_node, topology_only=True)
return nodes_to_target_from_chosen
def ChooseImages(self, setsize):
nodes_to_chosen_image = 0
images = []
while len(images) < setsize:
current_node = self.tree.get_tree_root()
while not current_node.is_leaf():
max_selection_criteria = 0
for node in current_node.get_children():
selection_criteria = random.betavariate(node.alpha, node.beta)
if selection_criteria > max_selection_criteria:
max_selection_criteria = selection_criteria
max_node = node
current_node = max_node
#print current_node.name
if int(current_node.name) not in images:
if int(current_node.name) not in self.previous_images:
nodes_to_chosen_image += self.tree.get_distance(current_node, self.chosen_node, topology_only=True)
images.append(int(current_node.name))
avnodes_to_chosen_image = nodes_to_chosen_image/setsize
return images, avnodes_to_chosen_image
class OMC():
TREE_PATH = '/home/konyushk/workspace/MCTS/Tree/'
def __init__(self, filename, proximity_type, clustering_type, number_of_images, target):
self.previous_images = []
self.number_of_images = number_of_images
self.tree = Tree(OMC.TREE_PATH + filename + str(self.number_of_images) + '_' + proximity_type + '_' + clustering_type + '.nw')
#print len(self.tree.get_leaves())
self.chosen_node = None
for node in self.tree.traverse('postorder'):
node.add_features(value = [], isUpdated = False)
node.value.append(1)
node.value.append(0)
self.target = target
def ModifyTree(self, images, chosen_image):
for node in self.tree.traverse('postorder'):
node.isUpdated = False
self.previous_images = images[:]
images.remove(chosen_image)
not_chosen_images = images
node = self.tree.search_nodes(name = str(chosen_image))[0]
self.chosen_node = node
node = node.up
while node:
node.value.append(1)
node.isUpdated = True
node = node.up
'''for node in self.tree.traverse('postorder'):
if node.isUpdated == False:
node.value.append(0)
for node in self.tree.traverse('postorder'):
node.isUpdated = False'''
for image in not_chosen_images:
node = self.tree.search_nodes(name = str(image))[0]
node = node.up
while node:
if node.isUpdated == False:
node.value.append(0)
node.isUpdated = True
node = node.up
'''for node in self.tree.traverse('postorder'):
if node.isUpdated == False:
node.value.append(1)'''
#print self.target
target_node = self.tree.search_nodes(name = str(self.target))[0]
nodes_to_target_from_chosen = self.tree.get_distance(target_node, self.chosen_node, topology_only=True)
return nodes_to_target_from_chosen
def ChooseImages(self, setsize):
nodes_to_chosen_image = 0
images = []
while len(images) < setsize:
current_node = self.tree.get_tree_root()
while not current_node.is_leaf():
best_value = 0
for node in current_node.get_children():
if numpy.mean(numpy.array(node.value)) > best_value:
best_value = numpy.mean(numpy.array(node.value))
Urgency = dict()
Fairness = dict()
for node in current_node.get_children():
Urgency[node] = scipy.special.erfc((best_value-numpy.mean(numpy.array(node.value)))/(math.sqrt(2)*numpy.std(numpy.array((node.value)))))
for node in current_node.get_children():
Fairness[node] = Urgency[node]/float(sum(Urgency.values()))
current_node = self.Sample(Fairness)
if (int(current_node.name) not in images) and (int(current_node.name) not in self.previous_images):
nodes_to_chosen_image += self.tree.get_distance(current_node, self.chosen_node, topology_only=True)
images.append(int(current_node.name))
avnodes_to_chosen_image = nodes_to_chosen_image/setsize
return images, avnodes_to_chosen_image
def Sample (self, probabilities):
r = random.random()
cumulative_sum = 0
for node in probabilities:
if cumulative_sum < r:
cumulative_sum = cumulative_sum + probabilities[node]
chosen_node = node
else:
break
return chosen_node
class UCT(object):
TREE_PATH = '/home/konyushk/workspace/MCTS/Tree/'
C = 0.2
def __init__(self, filename, proximity_type, clustering_type, number_of_images, target):
self.n = 1
self.previous_images = []
self.number_of_images = number_of_images
self.tree = Tree(THOMPSON.TREE_PATH + filename + str(self.number_of_images) + '_' + proximity_type + '_' + clustering_type + '.nw')
self.chosen_node = None
# Add alpha and beta features to the tree
for node in self.tree.traverse('postorder'):
node.add_features(value = [], isUpdated = False)
node.value.append(1)
self.target = target
def ModifyTree(self, images, chosen_image):
self.n += 1
for node in self.tree.traverse('postorder'):
node.isUpdated = False
self.previous_images = images[:]
images.remove(chosen_image)
not_chosen_images = images
node = self.tree.search_nodes(name = str(chosen_image))[0]
self.chosen_node = node
node = node.up
while node:
node.value.append(1)
node.isUpdated = True
node = node.up
for image in not_chosen_images:
node = self.tree.search_nodes(name = str(image))[0]
node = node.up
while node:
if node.isUpdated == False:
node.value.append(0)
node.isUpdated = True
node = node.up
target_node = self.tree.search_nodes(name = str(self.target))[0]
nodes_to_target_from_chosen = self.tree.get_distance(target_node, self.chosen_node, topology_only=True)
return nodes_to_target_from_chosen
def ChooseImages(self, setsize):
nodes_to_chosen_image = 0
images = []
while len(images) < setsize:
current_node = self.tree.get_tree_root()
while not current_node.is_leaf():
selection_criteria = dict()
Fairness = dict()
for node in current_node.get_children():
value = numpy.array((node.value))
ni = len(node.value)
avalue = numpy.mean(value)
vi = 1 / float(ni) * sum(value**2) - avalue**2 + math.sqrt(2 * math.log(self.n) / float(ni))
selection_criteria[node] = avalue + UCT.C * math.sqrt(math.log(self.n) / float(ni) * min(1/4,vi))
#print selection_criteria[node]
for node in current_node.get_children():
Fairness[node] = selection_criteria[node]/float(sum(selection_criteria.values()))
current_node = self.Sample(Fairness)
if int(current_node.name) not in images:
if int(current_node.name) not in self.previous_images:
nodes_to_chosen_image += self.tree.get_distance(current_node, self.chosen_node, topology_only=True)
images.append(int(current_node.name))
avnodes_to_chosen_image = nodes_to_chosen_image/setsize
return images, avnodes_to_chosen_image
def Sample (self, probabilities):
r = random.random()
cumulative_sum = 0
for node in probabilities:
if cumulative_sum < r:
cumulative_sum = cumulative_sum + probabilities[node]
chosen_node = node
else:
break
return chosen_node
class GAMMA(object):
ALPHA = 1
def __init__(self, filename, number_of_images, target):
'''Distances (can be tree distances)-----------------------------------------------------------------'''
self.distances = 1.0/(numpy.load(os.path.dirname(__file__) + '-files/'+ filename + '_tree-distances.npy')+0.3)
self.previous_images = []
self.number_of_images = number_of_images
self.tree = Tree(os.path.dirname(__file__) + '-files/'+ filename + '_tree.nw')
#print self.tree
prior_success_for_one = 1.0/number_of_images
self.chosen_node = None
# Add alpha and beta features to the tree
for node in self.tree.traverse('postorder'):
prior_success = prior_success_for_one*float(len(node.get_leaves()))
node.add_features(alpha = prior_success*len(node))
self.target = target
self.iteration_number = 1
def ModifyTree(self, images, chosen_image):
self.previous_images = images[:]
# for all leaves
for image in range(self.number_of_images):
# find the leaf
node = self.tree.search_nodes(name = str(image))[0]
# take the distance to the chosen one
distance_to_selected = self.distances[chosen_image][image]
# update the path by this value from 0 to 1
while node:
node.alpha += distance_to_selected
node = node.up
self.iteration_number += 1
target_node = self.tree.search_nodes(name = str(self.target))[0]
nodes_to_target_from_chosen = self.tree.get_distance(target_node, self.chosen_node, topology_only=True)
return nodes_to_target_from_chosen
def ChooseImages(self, setsize):
nodes_to_chosen_image = 0
images = []
while len(images) < setsize:
current_node = self.tree.get_tree_root()
while not current_node.is_leaf():
max_selection_criteria = 0
for node in current_node.get_children():
#coef = node.alpha/(self.iteration_number*len(node))
coef = node.alpha/len(node)
#print coef
#print coef
selection_criteria = (numpy.random.gamma(coef, scale=0.1))
#selection_criteria = random.gammavariate(node.alpha/(self.iteration_number*len(node)),1)
#print selection_criteria
if selection_criteria > max_selection_criteria:
max_selection_criteria = selection_criteria
max_node = node
current_node = max_node
#print current_node.name
if int(current_node.name) not in images:
if int(current_node.name) not in self.previous_images:
nodes_to_chosen_image += self.tree.get_distance(current_node, self.chosen_node, topology_only=True)
images.append(int(current_node.name))
avnodes_to_chosen_image = nodes_to_chosen_image/setsize
return images, avnodes_to_chosen_image
| Python |
'''
-----------------------------
This file contains 3 classes:
AgglomerativeClustering,
DivisiveHierarchicalKMeans,
KMeansClustering
-----------------------------
'''
import numpy
import linecache
from ete2 import Tree
import random
import math
import os
'''
---------------------------------------------------------------------------------------
This class is used to cluster objects using distance matrix from ProximityMatrix folder
For more information on obtaining proximities see Proximity file
OUTPUT: a tree written to Tree folder
The algorithm used - agglomerative bottom up merging of clusters
For calculating distances between clusters can use one of three types of distances:
Maximum, Minimum and UPGMA (weighted average)
USAGE:
cl = Clustering.AgglomerativeClustering('features_lewis37900', 'Manhattan')
cl.Clustering('Maximum')
----------------------------------------------------------------------------------------
'''
class AgglomerativeClustering(object):
def __init__(self, file, distance_type):
print 'Start initialisation'
self.file = file
self.distance_type = distance_type
self.path1 = os.path.dirname(__file__) + '/ProximityMatrix/'
self.path2 = os.path.dirname(__file__) + '/Tree/'
#self.path1 = 'ProximityMatrix/'
#self.path2 = 'Tree/'
self.input = self.path1 + file + '_' + distance_type + '.dist'
def GetNumberofLines():
lines = 0
for line in open(self.input):
lines += 1
return lines
self.lines = GetNumberofLines()
self.hierarchical_clustering = Tree()
self.ProximityMatrix = numpy.zeros((self.lines, self.lines))
# Index list keeps track of indeces of merged images
self.Forest = []
for i in range(self.lines):
t = Tree()
t.add_child(name=i)
self.Forest.append(t)
self.LoadProximityMatrix()
def LoadProximityMatrix(self):
self.ProximityMatrix = numpy.genfromtxt(self.input, unpack=True)
for i in range(self.lines):
# print 'Reading distances = ', i
# self.ProximityMatrix[i :] = self.GetVector(i+1)
self.ProximityMatrix[i,i] = numpy.inf
def GetVector(self, number):
# Get vector from line #number from file input
# number starts from 1
line = linecache.getline(self.input, number)
return map(float, line.split())
def Clustering(self, clustering_type):
print 'Start clustering'
i = 1
while self.ProximityMatrix.size != 1:
print 'Clustering = ', i
#print self.ProximityMatrix
clusters_to_merge, mindistance = self.Merge(clustering_type)
#print clusters_to_merge
self.ModifyTree(clusters_to_merge, mindistance)
i = i+1
for tree in self.Forest:
print tree
tree.write(outfile = self.path2 + self.file + '_' + self.distance_type + '_' + clustering_type + '.nw')
def Merge(self, clustering_type):
minval = numpy.argmin(self.ProximityMatrix)
mindistance = numpy.min(self.ProximityMatrix)
clusters_to_merge = numpy.array(numpy.unravel_index(minval, self.ProximityMatrix.shape))
# print clusters_to_merge
# print self.ProximityMatrix
# print self.CalculateNewDistances(type, clusters_to_merge)
new_distances = self.CalculateNewDistances(clustering_type, clusters_to_merge)
self.ProximityMatrix = numpy.vstack((self.ProximityMatrix,new_distances))
new_distances = numpy.append(new_distances,numpy.inf)
self.ProximityMatrix = numpy.column_stack((self.ProximityMatrix, new_distances))
# print self.ProximityMatrix
self.ProximityMatrix = numpy.delete(self.ProximityMatrix, clusters_to_merge, 0)
self.ProximityMatrix = numpy.delete(self.ProximityMatrix, clusters_to_merge, 1)
return clusters_to_merge, mindistance
def ModifyTree(self, clusters_to_merge, mindistance):
if clusters_to_merge[0]>clusters_to_merge[1]:
cluster1 = self.Forest.pop(clusters_to_merge[0])
cluster2 = self.Forest.pop(clusters_to_merge[1])
else:
cluster1 = self.Forest.pop(clusters_to_merge[1])
cluster2 = self.Forest.pop(clusters_to_merge[0])
new_tree = Tree()
new_tree.add_child(cluster1, dist=mindistance)
new_tree.add_child(cluster2, dist=mindistance)
self.Forest.append(new_tree)
#for i in self.Forest:
# print i
def CalculateNewDistances(self, type, clusters_to_merge):
if type == 'Maximum':
distance = numpy.max(self.ProximityMatrix[clusters_to_merge], axis=0)
elif type == 'Minimum':
distance = numpy.min(self.ProximityMatrix[clusters_to_merge], axis=0)
elif type == 'UPGMA':
distance = numpy.mean(self.ProximityMatrix[clusters_to_merge], axis=0)
return distance
'''
---------------------------------------------------------------------------------------------------------------
Another class for clustering, it's advantage that it allows to have non-binary structure of classes
Uses KMeansClustering as sub rutine, Silhouette measure is calculated to decide on number of clusters at a level
For calculating Silhouette needs to have a file with pairwise distances
CLUSTERS_NUMBER determines possible size of the cluster
REPEAT determines how many times each clustering will be performed (to avoid wrong clustering due to initialization)
MAXIMAGES how many images at max could be in the cluster so that we try clustering according to CLUSTERS_NUMBER,
otherwise do binary clustering
USAGE:
clustering = DivisiveHierarchicalKMeans(filename)
images = clustering.GetInitialImages()
clustering.TreeCluster(images, range(len(images)))
tree = clustering.hierarchical_clustering
# Wrtie the result to a file
tree.write(outfile = '/home/konyushk/workspace/MCTS/Tree/' + file + '_Euclidean' + '_kmeans.nw')
----------------------------------------------------------------------------------------------------------------
'''
class DivisiveHierarchicalKMeans(object):
CLUSTERS_NUMBER = [2, 3, 4, 5]
REPEAT = 3
PROGRESS = 0
MAXIMAGES = 1001
def __init__(self, file):
self.file = file
self.input = file
def GetNumberofLines():
lines = 0
for line in open(self.input):
lines += 1
return lines
def GetNumberofColumns():
line = linecache.getline(self.input, 1)
return len(line.split())
self.lines = GetNumberofLines()
self.columns = GetNumberofColumns()
self.hierarchical_clustering = Tree()
for i in range(self.lines):
self.hierarchical_clustering.add_child(name=i)
def GetInitialImages(self):
print 'Start reading images'
images = numpy.zeros((self.lines, self.columns))
for i in range(self.lines):
images[i :] = self.GetVector(i+1)
print 'Images read'
return images
def GetVector(self, number):
line = linecache.getline(self.input, number)
return map(float, line.split())
def TreeCluster(self, images, image_names):
if len(images) < DivisiveHierarchicalKMeans.MAXIMAGES:
silhouette_cn = dict()
for cn in DivisiveHierarchicalKMeans.CLUSTERS_NUMBER:
silhouette = numpy.zeros((DivisiveHierarchicalKMeans.REPEAT))
for i in range(DivisiveHierarchicalKMeans.REPEAT):
kmclustering = KMeansClustering(images, cn, self.file)
clusters , centroids, silhouette[i] = kmclustering.KMeans()
silhouette_cn[cn] = numpy.mean(silhouette)
best_clusters_number = max(silhouette_cn, key=silhouette_cn.get)
kmclustering = KMeansClustering(images, best_clusters_number, self.file)
clusters , centroids, silhouette[i] = kmclustering.KMeans()
else:
kmclustering = KMeansClustering(images, 2, self.file)
clusters , centroids = kmclustering.BasicKMeans()
for cluster in clusters:
if len(clusters[cluster]) >= DivisiveHierarchicalKMeans.CLUSTERS_NUMBER[-1]:
# print cluster
branch = Tree()
#branch = subtree.add_child()
NodeAdded = False
i = 0
for image in clusters[cluster]:
i += 1
# print i
actual_image_name = image_names[image]
old_node = self.hierarchical_clustering.search_nodes(name = str(actual_image_name))[0]
if NodeAdded != True:
old_node.add_sister(branch)
NodeAdded = True
branch.add_child(name = actual_image_name)
old_node.delete()
new_images = images[clusters[cluster],:]
image_names = numpy.array(image_names)
new_image_names = image_names[clusters[cluster]]
self.TreeCluster(new_images, new_image_names)
#print len(self.hierarchical_clustering.get_leaves())
else:
DivisiveHierarchicalKMeans.PROGRESS += len(clusters[cluster])
#print DivisiveHierarchicalKMeans.PROGRESS
branch = Tree()
NodeAdded = False
for image in clusters[cluster]:
actual_image_name = image_names[image]
'''new'''
old_node = self.hierarchical_clustering.search_nodes(name = str(actual_image_name))[0]
if NodeAdded != True:
old_node.add_sister(branch)
NodeAdded = True
branch.add_child(name = actual_image_name)
old_node.delete()
'''
branch.add_child(name = actual_image_name)
old_node = self.hierarchical_clustering.search_nodes(name = str(actual_image_name))[0]
old_parent = old_node.up
old_node.delete()
old_parent.add_child(branch)'''
class KMeansClustering(object):
E = 0.0000001
def __init__(self, images, clusters_number, file):
self.file = file
self.images = images
self.clusters_number = clusters_number
self.columns = numpy.size(images, axis=1)
self.lines = numpy.size(images, axis=0)
self.silhouette = 0
self.InitializeCentroids()
self.clusters = dict()
self.clusters_list = []
def InitializeCentroids(self):
self.centroids = numpy.zeros((self.clusters_number, self.columns))
self.old_centroids = self.centroids
centroid_indeces = []
while len(centroid_indeces) < self.clusters_number:
centroid_index = random.randint(0, self.lines-1)
if centroid_index not in centroid_indeces:
centroid_indeces.append(centroid_index)
i = 0
for centroid_index in centroid_indeces:
#self.centroids[i,:] = numpy.array(self.GetVector(centroid_index))
self.centroids[i,:] = self.images[centroid_index, :]
i += 1
def BasicKMeans(self):
# print 'Basic K-means started!'
old_SSE = 0
difference = 1
while difference > KMeansClustering.E:
# print 'Iteration started'
SSE = self.AssignImages()
# print 'Assigning images done'
self.UpdateCentroids()
# print 'Centroids Updated'
difference = abs(old_SSE - SSE)
old_SSE = SSE
# print 'Centroids = ', self.centroids
# print 'Clusters = ', self.clusters
# print 'SSE = ', SSE
# for cluster in self.clusters:
# print cluster, ' ', len(self.clusters[cluster])
# print 'K-means finished!'
return self.clusters, self.centroids
def KMeans(self):
# print 'K-means started!'
old_SSE = 0
difference = 1
while difference > KMeansClustering.E:
# print 'Iteration started'
SSE = self.AssignImages()
# print 'Assigning images done'
self.UpdateCentroids()
# print 'Centroids Updated'
difference = abs(old_SSE - SSE)
old_SSE = SSE
# print 'Centroids = ', self.centroids
# print 'Clusters = ', self.clusters
# print 'SSE = ', SSE
# for cluster in self.clusters:
# print cluster, ' ', len(self.clusters[cluster])
# print 'K-means finished!'
# print 'Calculating Silhoette started'
self.CalculteSilhouette(self.file)
# print 'Silhouette = ', self.silhouette
return self.clusters, self.centroids, self.silhouette
def AssignImages(self):
self.clusters.clear()
image_index = 0
SSE = 0
for image in self.images:
distances = numpy.zeros((1, len(self.centroids)))
i = 0
for centroid in self.centroids:
distances[0, i] = self.Distance('Euclidean', image, centroid)
i += 1
self.clusters_list.append(numpy.argmin(distances))
SSE += numpy.min(distances)**2
if numpy.argmin(distances) in self.clusters:
self.clusters[numpy.argmin(distances)].append(image_index)
else:
self.clusters[numpy.argmin(distances)] = [image_index]
image_index += 1
# if one of the clusters ended up with an empty one
while len(self.clusters) < self.clusters_number:
new_centroid = random.randint(0, self.lines-1)
self.clusters[len(self.clusters)] = [new_centroid]
for cluster in self.clusters:
if new_centroid in self.clusters[cluster]:
self.clusters[cluster].remove(new_centroid)
self.clusters[len(self.clusters)] = [new_centroid]
break
return SSE
def Distance(self, type, vector1, vector2):
if type == 'Euclidean':
distance = math.sqrt(sum((vector1 - vector2)**2))
elif type == 'Manhattan':
distance = sum(abs(vector1-vector2))
elif type == 'Maximum':
distance = max(vector1-vector2)
elif type == 'Mahalanoibis':
matrix = numpy.vstack((vector1,vector2)).T
covariance = numpy.cov(matrix)
distance = math.sqrt(numpy.dot(numpy.dot((vector1-vector2),numpy.linalg.pinv(covariance)),(vector1-vector2).T))
elif type == 'Cosine':
distance = 1-numpy.dot(vector1, vector2)/(math.sqrt(sum((vector1)**2))*math.sqrt(sum((vector2)**2)))
return distance
def UpdateCentroids(self):
self.centroids = numpy.zeros((self.clusters_number, self.columns))
for cluster in self.clusters:
images_in_clusters = self.images[self.clusters[cluster]]
self.centroids[cluster, :] = numpy.mean(images_in_clusters, axis=0)
def CalculteSilhouette(self, filename):
file = filename + '_Euclidean.dist'
silhouette = []
for image in range(self.lines):
distances = numpy.array(self.GetVector(file, image + 1))
image_cluster = self.clusters_list[image]
images_in_same_cluster = self.clusters[image_cluster]
#print image
#print self.clusters[image_cluster]
a = numpy.mean(distances[images_in_same_cluster])
distances_other_clusters = []
for cluster in self.clusters:
if cluster != image_cluster:
images_in_cluster = self.clusters[cluster]
distances_other_clusters.append(numpy.mean(distances[images_in_cluster]))
b = min(distances_other_clusters)
silhouette.append((b - a) / max(a, b))
self.silhouette = sum(silhouette)/len(silhouette)
def GetVector(self, file, number):
line = linecache.getline(file, number)
return map(float, line.split())
'''clustering = DivisiveHierarchicalKMeans('test')
images = clustering.GetInitialImages()
clustering.TreeCluster(images, range(len(images)))
tree = clustering.hierarchical_clustering
print tree'''
inf = os.path.dirname(__file__) + '-files/test'
clustering = DivisiveHierarchicalKMeans(inf)
images = clustering.GetInitialImages()
clustering.TreeCluster(images, range(len(images)))
tree = clustering.hierarchical_clustering
outf = inf + '_tree.nw'
tree.write(outfile = outf) | Python |
#############
#
# Author: Harry Eakins
# Date: 9th April 2009
# Description: Function generates random strings
#
#############
from random import choice
import string
def randStringGen(length=15):
letters = string.ascii_letters + string.digits
randString = ''
for i in range(length):
randString += choice(letters)
return randString
| Python |
from anki.hooks import addHook
from anki.db import *
from anki.models import Model, CardModel, FieldModel
import anki.stdmodels
# Create a defualt model called "English" for use with the English Helper plugin
def EnglishModel():
m = Model(_("English"))
tempFieldModel = FieldModel(u'English Word', False, False)
tempFieldModel.editFontSize = 14
m.addFieldModel(tempFieldModel)
tempFieldModel = FieldModel(u'Chinese Definition', False, False)
tempFieldModel.editFontSize = 16
m.addFieldModel(tempFieldModel)
tempFieldModel = FieldModel(u'English Definition', False, False)
tempFieldModel.editFontSize = 14
m.addFieldModel(tempFieldModel)
tempFieldModel = FieldModel(u'English Pronunciation', False, False)
tempFieldModel.editFontSize = 14
m.addFieldModel(tempFieldModel)
tempFieldModel = FieldModel(u'Example Sentence', False, False)
tempFieldModel.editFontSize = 14
m.addFieldModel(tempFieldModel)
m.addCardModel(CardModel(u"Recognition",
u"%(English Word)s",
u"%(Chinese Definition)s<br />%(English Definition)s<br />%(English Pronunciation)s \
<br /><font color='red'>%(Example Sentence)s</font>"))
m.tags = u"English"
return m
anki.stdmodels.models['English'] = EnglishModel
###### Resize fields #####
# Because the definition field should be bigger than the word field etc
def resize(widget, field):
if field.name == "English Word":
widget.setFixedHeight(35)
elif field.name == "Chinese Definition":
widget.setFixedHeight(50)
elif field.name == "English Definition":
widget.setMaximumHeight(500)
elif field.name == "Example Sentence":
widget.setFixedHeight(100)
elif field.name == "English Pronunciation":
widget.setFixedHeight(30)
addHook("makeField", resize)
| Python |
import urllib, re
# Returns a pronunciation wav file from Merriam-Webster.com
# If no audio found, returns None
def getAudio(word):
try:
# Download the dictionary webpage
webpage = urllib.urlopen("http://www.merriam-webster.com/dictionary/" + word)
# webpage = open(word + ".html")
# Convert to html string
html = webpage.read()
# Find the wav file identifiers
reg = re.compile("Main Entry:.*?return au\('([^']*)'[^']*'([^']*)'\);")
ids = reg.findall(html)[0]
# Download audio play webpage
audioWebPage = urllib.urlopen("http://www.merriam-webster.com/cgi-bin/audio.pl?" + ids[0] + "=" + ids[1])
# audioWebPage = open("audio.pl " + ids[0] + "=" + ids[1] + ".html")
audioHtml = audioWebPage.read()
# Find the URL for the wav file
reg = re.compile('<A HREF="(http[^"]*)"')
audioURL = reg.findall(audioHtml)[0]
# Download the audio
audioFile = urllib.urlopen(audioURL)
except:
return None # Could not get audio file for some reason
return audioFile
| Python |
# -*- coding: utf-8 -*-
"""
Copyright 2008 Serge Matveenko
This file is part of PyStarDict.
PyStarDict 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 3 of the License, or
(at your option) any later version.
PyStarDict 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 PyStarDict. If not, see <http://www.gnu.org/licenses/>.
@author: Serge Matveenko <s@matveenko.ru>
"""
import gzip
import hashlib
import re
from struct import unpack
class _StarDictIfo():
"""
The .ifo file has the following format:
StarDict's dict ifo file
version=2.4.2
[options]
Note that the current "version" string must be "2.4.2" or "3.0.0". If it's not,
then StarDict will refuse to read the file.
If version is "3.0.0", StarDict will parse the "idxoffsetbits" option.
[options]
---------
In the example above, [options] expands to any of the following lines
specifying information about the dictionary. Each option is a keyword
followed by an equal sign, then the value of that option, then a
newline. The options may be appear in any order.
Note that the dictionary must have at least a bookname, a wordcount and a
idxfilesize, or the load will fail. All other information is optional. All
strings should be encoded in UTF-8.
Available options:
bookname= // required
wordcount= // required
synwordcount= // required if ".syn" file exists.
idxfilesize= // required
idxoffsetbits= // New in 3.0.0
author=
email=
website=
description= // You can use <br> for new line.
date=
sametypesequence= // very important.
"""
def __init__(self, dict_prefix, container):
ifo_filename = '%s.ifo' % dict_prefix
try:
_file = open(ifo_filename)
except IOError:
raise Exception('%s file does not exists' % ifo_filename)
# skipping ifo header
_file.readline()
_line = _file.readline().split('=')
if _line[0] == 'version':
self.version = _line[1]
else:
raise Exception('ifo has invalid format')
_config = {}
for _line in _file:
_line_splited = _line.split('=')
_config[_line_splited[0]] = _line_splited[1]
self.bookname = _config.get('bookname', None).strip()
if self.bookname is None: raise Exception('ifo has no bookname')
self.wordcount = _config.get('wordcount', None)
if self.wordcount is None: raise Exception('ifo has no wordcount')
self.wordcount = int(self.wordcount)
if self.version == '3.0.0':
try:
_syn = open('%s.syn' % dict_prefix)
self.synwordcount = _config.get('synwordcount', None)
if self.synwordcount is None:
raise Exception('ifo has no synwordcount but .syn file exists')
self.synwordcount = int(self.synwordcount)
except IOError:
pass
self.idxfilesize = _config.get('idxfilesize', None)
if self.idxfilesize is None: raise Exception('ifo has no idxfilesize')
self.idxfilesize = int(self.idxfilesize)
self.idxoffsetbits = _config.get('idxoffsetbits', 32)
self.idxoffsetbits = int(self.idxoffsetbits)
self.author = _config.get('author', '').strip()
self.email = _config.get('email', '').strip()
self.website = _config.get('website', '').strip()
self.description = _config.get('description', '').strip()
self.date = _config.get('date', '').strip()
self.sametypesequence = _config.get('sametypesequence', '').strip()
class _StarDictIdx():
"""
The .idx file is just a word list.
The word list is a sorted list of word entries.
Each entry in the word list contains three fields, one after the other:
word_str; // a utf-8 string terminated by '\0'.
word_data_offset; // word data's offset in .dict file
word_data_size; // word data's total size in .dict file
"""
def __init__(self, dict_prefix, container):
idx_filename = '%s.idx' % dict_prefix
idx_filename_gz = '%s.gz' % idx_filename
try:
file = open(idx_filename, 'rb')
except IOError:
try:
file = gzip.open(idx_filename_gz, 'rb')
except IOError:
raise Exception('.idx file does not exists')
""" check file size """
self._file = file.read()
if file.tell() != container.ifo.idxfilesize:
raise Exception('size of the .idx file is incorrect')
""" prepare main dict and parsing parameters """
self._idx = {}
idx_offset_bytes_size = int(container.ifo.idxoffsetbits / 8)
idx_offset_format = {4: 'L', 8: 'Q',}[idx_offset_bytes_size]
idx_cords_bytes_size = idx_offset_bytes_size + 4
""" parse data via regex """
record_pattern = r'([\d\D]+?\x00[\d\D]{%s})' % idx_cords_bytes_size
matched_records = re.findall(record_pattern, self._file)
""" check records count """
if len(matched_records) != container.ifo.wordcount:
raise Exception('words count is incorrect')
""" unpack parsed records """
for matched_record in matched_records:
c = matched_record.find('\x00') + 1
record_tuple = unpack('!%sc%sL' % (c, idx_offset_format),
matched_record)
word, cords = record_tuple[:c-1], record_tuple[c:]
self._idx[word] = cords
def __getitem__(self, word):
"""
returns tuple (word_data_offset, word_data_size,) for word in .dict
@note: here may be placed flexible search realization
"""
return self._idx[tuple(word)]
def __contains__(self, k):
"""
returns True if index has a word k, else False
"""
return tuple(k) in self._idx
def __eq__(self, y):
"""
returns True if hashlib(x.idx) is equal to hashlib(y.idx), else False
"""
return hashlib.new(self._file).digest() == hashlib.new(y._file).digest()
def __ne__(self, y):
"""
returns True if hashlib(x.idx) is not equal to hashlib(y.idx), else False
"""
return not self.__eq__(y)
class _StarDictDict():
"""
The .dict file is a pure data sequence, as the offset and size of each
word is recorded in the corresponding .idx file.
If the "sametypesequence" option is not used in the .ifo file, then
the .dict file has fields in the following order:
==============
word_1_data_1_type; // a single char identifying the data type
word_1_data_1_data; // the data
word_1_data_2_type;
word_1_data_2_data;
...... // the number of data entries for each word is determined by
// word_data_size in .idx file
word_2_data_1_type;
word_2_data_1_data;
......
==============
It's important to note that each field in each word indicates its
own length, as described below. The number of possible fields per
word is also not fixed, and is determined by simply reading data until
you've read word_data_size bytes for that word.
Suppose the "sametypesequence" option is used in the .idx file, and
the option is set like this:
sametypesequence=tm
Then the .dict file will look like this:
==============
word_1_data_1_data
word_1_data_2_data
word_2_data_1_data
word_2_data_2_data
......
==============
The first data entry for each word will have a terminating '\0', but
the second entry will not have a terminating '\0'. The omissions of
the type chars and of the last field's size information are the
optimizations required by the "sametypesequence" option described
above.
If "idxoffsetbits=64", the file size of the .dict file will be bigger
than 4G. Because we often need to mmap this large file, and there is
a 4G maximum virtual memory space limit in a process on the 32 bits
computer, which will make we can get error, so "idxoffsetbits=64"
dictionary can't be loaded in 32 bits machine in fact, StarDict will
simply print a warning in this case when loading. 64-bits computers
should haven't this limit.
Type identifiers
----------------
Here are the single-character type identifiers that may be used with
the "sametypesequence" option in the .idx file, or may appear in the
dict file itself if the "sametypesequence" option is not used.
Lower-case characters signify that a field's size is determined by a
terminating '\0', while upper-case characters indicate that the data
begins with a network byte-ordered guint32 that gives the length of
the following data's size(NOT the whole size which is 4 bytes bigger).
'm'
Word's pure text meaning.
The data should be a utf-8 string ending with '\0'.
'l'
Word's pure text meaning.
The data is NOT a utf-8 string, but is instead a string in locale
encoding, ending with '\0'. Sometimes using this type will save disk
space, but its use is discouraged.
'g'
A utf-8 string which is marked up with the Pango text markup language.
For more information about this markup language, See the "Pango
Reference Manual."
You might have it installed locally at:
file:///usr/share/gtk-doc/html/pango/PangoMarkupFormat.html
't'
English phonetic string.
The data should be a utf-8 string ending with '\0'.
Here are some utf-8 phonetic characters:
θʃŋʧðʒæıʌʊɒɛəɑɜɔˌˈːˑṃṇḷ
æɑɒʌәєŋvθðʃʒɚːɡˏˊˋ
'x'
A utf-8 string which is marked up with the xdxf language.
See http://xdxf.sourceforge.net
StarDict have these extention:
<rref> can have "type" attribute, it can be "image", "sound", "video"
and "attach".
<kref> can have "k" attribute.
'y'
Chinese YinBiao or Japanese KANA.
The data should be a utf-8 string ending with '\0'.
'k'
KingSoft PowerWord's data. The data is a utf-8 string ending with '\0'.
It is in XML format.
'w'
MediaWiki markup language.
See http://meta.wikimedia.org/wiki/Help:Editing#The_wiki_markup
'h'
Html codes.
'r'
Resource file list.
The content can be:
img:pic/example.jpg // Image file
snd:apple.wav // Sound file
vdo:film.avi // Video file
att:file.bin // Attachment file
More than one line is supported as a list of available files.
StarDict will find the files in the Resource Storage.
The image will be shown, the sound file will have a play button.
You can "save as" the attachment file and so on.
'W'
wav file.
The data begins with a network byte-ordered guint32 to identify the wav
file's size, immediately followed by the file's content.
'P'
Picture file.
The data begins with a network byte-ordered guint32 to identify the picture
file's size, immediately followed by the file's content.
'X'
this type identifier is reserved for experimental extensions.
"""
def __init__(self, dict_prefix, container):
"""
opens regular or dziped .dict file
"""
self._container = container
dict_filename = '%s.dict' % dict_prefix
dict_filename_dz = '%s.dz' % dict_filename
try:
self._file = open(dict_filename, 'rb')
except IOError:
try:
self._file = gzip.open(dict_filename_dz, 'rb')
except IOError:
raise Exception('.dict file does not exists')
def __getitem__(self, word):
"""
returns data from .dict for word
"""
# getting word data coordinats
cords = self._container.idx[word]
# seeking in file for data
self._file.seek(cords[0])
# reading data
bytes = self._file.read(cords[1])
return bytes
class _StarDictSyn():
def __init__(self, dict_prefix, container):
syn_filename = '%s.syn' % dict_prefix
try:
self._file = open(syn_filename)
except IOError:
# syn file is optional, passing silently
pass
class Dictionary(dict):
"""
Dictionary-like class for lazy manipulating stardict dictionaries
All items of this dictionary are writable and dict is expandable itself,
but changes are not stored anywhere and available in runtime only.
We assume in this documentation that "x" or "y" is instances of the
StarDictDict class and "x.{ifo,idx{,.gz},dict{,.dz),syn}" or
"y.{ifo,idx{,.gz},dict{,.dz),syn}" is files of the corresponding stardict
dictionaries.
Following documentation is from the "dict" class an is subkect to rewrite
in further impleneted methods:
"""
def __init__(self, filename_prefix):
"""
filename_prefix: path to dictionary files without files extensions
initializes new StarDictDict instance from stardict dictionary files
provided by filename_prefix
"""
# reading somedict.ifo
self.ifo = _StarDictIfo(dict_prefix=filename_prefix, container=self)
# reading somedict.idx or somedict.idx.gz
self.idx = _StarDictIdx(dict_prefix=filename_prefix, container=self)
# reading somedict.dict or somedict.dict.dz
self.dict = _StarDictDict(dict_prefix=filename_prefix, container=self)
# reading somedict.syn (optional)
self.syn = _StarDictSyn(dict_prefix=filename_prefix, container=self)
# initializing cache
self._dict_cache = {}
def __cmp__(self, y):
"""
raises NotImplemented exception
"""
raise NotImplementedError()
def __contains__(self, k):
"""
returns True if x.idx has a word k, else False
"""
return k in self.idx
def __delitem__(self, k):
"""
frees cache from word k translation
"""
del self._dict_cache[k]
def __eq__(self, y):
"""
returns True if hashlib(x.idx) is equal to hashlib(y.idx), else False
"""
return self.idx.__eq__(y.idx)
def __ge__(self, y):
"""
raises NotImplemented exception
"""
raise NotImplementedError()
def __getitem__(self, k):
"""
returns translation for word k from cache or not and then caches
"""
if k in self._dict_cache:
return self._dict_cache[k]
else:
value = self.dict[k]
self._dict_cache[k] = value
return value
def __gt__(self, y):
"""
raises NotImplemented exception
"""
raise NotImplementedError()
def __iter__(self):
"""
raises NotImplemented exception
"""
raise NotImplementedError()
def __le__(self):
"""
raises NotImplemented exception
"""
raise NotImplementedError()
def __len__(self):
"""
returns number of words provided by wordcount parameter of the x.ifo
"""
return self.ifo.wordcount
def __lt__(self):
"""
raises NotImplemented exception
"""
raise NotImplementedError()
def __ne__(self, y):
"""
returns True if hashlib(x.idx) is not equal to hashlib(y.idx), else False
"""
return not self.__eq__(y)
def __repr__(self):
"""
returns classname and bookname parameter of the x.ifo
"""
return u'%s %s' % (self.__class__, self.ifo.bookname)
def __setitem__(self, k, v):
"""
raises NotImplemented exception
"""
raise NotImplementedError()
def clear(self):
"""
clear dict cache
"""
self._dict_cache = dict()
def get(self, k, d=''):
"""
returns translation of the word k from self.dict or d if k not in x.idx
d defaults to empty string
"""
return k in self and self[k] or d
def has_key(self, k):
"""
returns True if self.idx has a word k, else False
"""
return k in self
def items(self):
"""
raises NotImplemented exception
"""
raise NotImplementedError()
def iteritems(self):
"""
raises NotImplemented exception
"""
raise NotImplementedError()
def iterkeys(self):
"""
raises NotImplemented exception
"""
raise NotImplementedError()
def itervalues(self):
"""
raises NotImplemented exception
"""
raise NotImplementedError()
def keys(self):
"""
raises NotImplemented exception
"""
raise NotImplementedError()
def pop(self, k, d):
"""
raises NotImplemented exception
"""
raise NotImplementedError()
def popitem(self):
"""
raises NotImplemented exception
"""
raise NotImplementedError()
def setdefault(self, k, d):
"""
raises NotImplemented exception
"""
raise NotImplementedError()
def update(self, E, **F):
"""
raises NotImplemented exception
"""
raise NotImplementedError()
def values(self):
"""
raises NotImplemented exception
"""
raise NotImplementedError()
def fromkeys(self, S, v=None):
"""
raises NotImplemented exception
"""
raise NotImplementedError()
| Python |
# English Helper for Chinese
# v0.08 - 11th April 2010
# Harry Eakins - harry.eakins at googlemail dot com
#
# This plugin adds an English model and auto-generates English and Chinese definitions for the inputted word.
import sys, os, re
from ankiqt import mw
ankidir = mw.config.configPath
plugdir = os.path.join(ankidir, "plugins")
plugdir = os.path.join(plugdir, "englishhelper")
sys.path.insert(0, plugdir)
from anki.hooks import addHook
from anki.db import *
from pystardict import Dictionary
import english_model
from PyQt4 import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
##### Dictionary functions ######
ecDict = None
def findMandarinDef(word):
if word == '':
return ''
global ecDict
if ecDict is None:
ecDict = Dictionary(os.path.join(os.path.dirname(os.path.realpath( __file__ )), 'englishhelper', u'stardict-xdict-ec-gb-2.4.2', u'xdict-ec-gb'))
try:
definition = ecDict[word]
ecregex = re.compile("(.*?)\\x00...([\s\S]*)")
return ecregex.search(unicode(definition, 'utf-8')).group(2).replace(u'\n', u'<br />')
except KeyError:
return ''
eeDict = None
def findEnglishDef(word):
if word == '':
return ''
global eeDict
if eeDict is None:
eeDict = Dictionary(os.path.join(os.path.dirname(os.path.realpath( __file__ )), 'englishhelper', u'stardict-mwc-2.4.2', u'mwc'))
definitionList = []
try:
# Grab the dictionary entry
dictPage = eeDict[word]
# Create regular expression which will match definitions
eeregex = re.compile("<dtrn>\s*([\s\S]*?)\s*</dtrn>")
# Retrieve all matches of the regular expression
definitions = eeregex.findall(dictPage)
# Create definition list and initialize to empty
definitionList = u''
i = 1
# Build definition list
for line in definitions:
definitionList += u'(' + unicode(str(i), 'utf-8') + u') ' + unicode(line, 'utf-8') + u'<br />'
i += 1
except KeyError:
return ''
return definitionList
from randStringGen import randStringGen
from audioGetter import getAudio
from anki.deck import Deck
audioSetting = True
def fetchAudioToggle():
global audioSetting
global menu1
audioSetting = not audioSetting
if audioSetting == True:
menu1.setText("Don't Fetch English Pronunciation Audio")
else:
menu1.setText("Fetch English Pronunciation Audio")
def findEnglishPro(word):
if word == '':
return ''
global ecDict
if ecDict is None:
ecDict = Dictionary(os.path.join(os.path.dirname(os.path.realpath( __file__ )), 'englishhelper', 'stardict-xdict-ec-gb-2.4.2', 'xdict-ec-gb'))
try:
fieldvalue = ''
# Get pronunciation in IPA
try:
definition = ecDict[word]
regex = re.compile("(.*?)\\x00...([\s\S]*)")
IPA = regex.search(unicode(definition, 'utf-8')).group(1)
unicodeFontList = "'DejaVu Sans, Arial Unicode MS, Charis SIL'"
fieldvalue += u"<font face=" + unicodeFontList + u">" + IPA + u'</font>'
except:
pass
if audioSetting == True:
# Get pronunciation in audio
try:
audio = getAudio(word)
audioFilename = randStringGen() + ".wav"
audioFile = open(os.path.join(mw.deck.mediaDir(create=True), audioFilename), "w")
audioFile.write(audio.read());
audioFile.close()
fieldvalue += u"[sound:" + audioFilename + u"]"
except:
pass
# Return pronunciation
return fieldvalue
except KeyError:
return ''
##### Handler functions #######
def onFocusLost(fact, field):
if field.name != 'English Word':
return
searchword = field.value.lower().strip()
try:
if fact['Chinese Definition'] == "": # Generate if empty
fact['Chinese Definition'] = findMandarinDef(searchword)
except KeyError:
pass
try:
if fact['English Definition'] == "":
fact['English Definition'] = findEnglishDef(searchword)
except KeyError:
pass
try:
if fact['English Pronunciation'] == "":
fact['English Pronunciation'] = findEnglishPro(searchword)
except KeyError:
pass
addHook('fact.focusLost', onFocusLost)
# Setup menu entries
menu1 = QAction(mw)
menu1.setText("Don't Fetch English Pronunciation Audio")
mw.connect(menu1, SIGNAL("triggered()"),fetchAudioToggle)
mw.mainWin.menuTools.addSeparator()
mw.mainWin.menuTools.addAction(menu1)
mw.registerPlugin("English Helper for Chinese", 0.08)
| Python |
# -*- coding: utf-8 -*-
#
# FormAlchemy documentation build configuration file, created by
# sphinx-quickstart on Thu Sep 4 22:53:00 2008.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't pickleable (module imports are okay, they're removed automatically).
#
# All configuration values have a default value; values that are commented out
# serve to show the default value.
import sys, os
# If your extensions are in another directory, add it here. If the directory
# is relative to the documentation root, use os.path.abspath to make it
# absolute, like shown here.
#sys.path.append(os.path.abspath('some/directory'))
# General configuration
# ---------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.txt'
# The master toctree document.
master_doc = 'index'
# General substitutions.
project = 'FormAlchemy'
copyright = '2008, Alexandre Conrad'
# The default replacements for |version| and |release|, also used in various
# other places throughout the built documents.
#
# The short X.Y version.
version = '1.3.6'
# The full version, including alpha/beta/rc tags.
release = version
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# List of directories, relative to source directories, that shouldn't be searched
# for source files.
#exclude_dirs = []
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# Options for HTML output
# -----------------------
# The style sheet to use for HTML and HTML Help pages. A file of that name
# must exist either in Sphinx' static/ path, or in one of the custom paths
# given in html_static_path.
html_style = 'default.css'
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (within the static path) to place at the top of
# the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_use_modindex = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, the reST sources are included in the HTML build as _sources/<name>.
#html_copy_source = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'FormAlchemydoc'
# Options for LaTeX output
# ------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, document class [howto/manual]).
latex_documents = [
('index', 'FormAlchemy.tex', 'FormAlchemy Documentation',
'Alexandre Conrad', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True
# Also add __init__'s doc to `autoclass` calls
autoclass_content = 'both'
| Python |
#!python
"""Bootstrap setuptools installation
If you want to use setuptools in your package's setup.py, just include this
file in the same directory with it, and add this to the top of your setup.py::
from ez_setup import use_setuptools
use_setuptools()
If you want to require a specific version of setuptools, set a download
mirror, or use an alternate download directory, you can do so by supplying
the appropriate options to ``use_setuptools()``.
This file can also be run as a script to install or upgrade setuptools.
"""
import sys
DEFAULT_VERSION = "0.6c9"
DEFAULT_URL = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3]
md5_data = {
'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca',
'setuptools-0.6b1-py2.4.egg': 'b79a8a403e4502fbb85ee3f1941735cb',
'setuptools-0.6b2-py2.3.egg': '5657759d8a6d8fc44070a9d07272d99b',
'setuptools-0.6b2-py2.4.egg': '4996a8d169d2be661fa32a6e52e4f82a',
'setuptools-0.6b3-py2.3.egg': 'bb31c0fc7399a63579975cad9f5a0618',
'setuptools-0.6b3-py2.4.egg': '38a8c6b3d6ecd22247f179f7da669fac',
'setuptools-0.6b4-py2.3.egg': '62045a24ed4e1ebc77fe039aa4e6f7e5',
'setuptools-0.6b4-py2.4.egg': '4cb2a185d228dacffb2d17f103b3b1c4',
'setuptools-0.6c1-py2.3.egg': 'b3f2b5539d65cb7f74ad79127f1a908c',
'setuptools-0.6c1-py2.4.egg': 'b45adeda0667d2d2ffe14009364f2a4b',
'setuptools-0.6c2-py2.3.egg': 'f0064bf6aa2b7d0f3ba0b43f20817c27',
'setuptools-0.6c2-py2.4.egg': '616192eec35f47e8ea16cd6a122b7277',
'setuptools-0.6c3-py2.3.egg': 'f181fa125dfe85a259c9cd6f1d7b78fa',
'setuptools-0.6c3-py2.4.egg': 'e0ed74682c998bfb73bf803a50e7b71e',
'setuptools-0.6c3-py2.5.egg': 'abef16fdd61955514841c7c6bd98965e',
'setuptools-0.6c4-py2.3.egg': 'b0b9131acab32022bfac7f44c5d7971f',
'setuptools-0.6c4-py2.4.egg': '2a1f9656d4fbf3c97bf946c0a124e6e2',
'setuptools-0.6c4-py2.5.egg': '8f5a052e32cdb9c72bcf4b5526f28afc',
'setuptools-0.6c5-py2.3.egg': 'ee9fd80965da04f2f3e6b3576e9d8167',
'setuptools-0.6c5-py2.4.egg': 'afe2adf1c01701ee841761f5bcd8aa64',
'setuptools-0.6c5-py2.5.egg': 'a8d3f61494ccaa8714dfed37bccd3d5d',
'setuptools-0.6c6-py2.3.egg': '35686b78116a668847237b69d549ec20',
'setuptools-0.6c6-py2.4.egg': '3c56af57be3225019260a644430065ab',
'setuptools-0.6c6-py2.5.egg': 'b2f8a7520709a5b34f80946de5f02f53',
'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2',
'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e',
'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372',
'setuptools-0.6c8-py2.3.egg': '50759d29b349db8cfd807ba8303f1902',
'setuptools-0.6c8-py2.4.egg': 'cba38d74f7d483c06e9daa6070cce6de',
'setuptools-0.6c8-py2.5.egg': '1721747ee329dc150590a58b3e1ac95b',
'setuptools-0.6c9-py2.3.egg': 'a83c4020414807b496e4cfbe08507c03',
'setuptools-0.6c9-py2.4.egg': '260a2be2e5388d66bdaee06abec6342a',
'setuptools-0.6c9-py2.5.egg': 'fe67c3e5a17b12c0e7c541b7ea43a8e6',
'setuptools-0.6c9-py2.6.egg': 'ca37b1ff16fa2ede6e19383e7b59245a',
}
import sys, os
try: from hashlib import md5
except ImportError: from md5 import md5
def _validate_md5(egg_name, data):
if egg_name in md5_data:
digest = md5(data).hexdigest()
if digest != md5_data[egg_name]:
print >>sys.stderr, (
"md5 validation of %s failed! (Possible download problem?)"
% egg_name
)
sys.exit(2)
return data
def use_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
download_delay=15
):
"""Automatically find/download setuptools and make it available on sys.path
`version` should be a valid setuptools version number that is available
as an egg for download under the `download_base` URL (which should end with
a '/'). `to_dir` is the directory where setuptools will be downloaded, if
it is not already available. If `download_delay` is specified, it should
be the number of seconds that will be paused before initiating a download,
should one be required. If an older version of setuptools is installed,
this routine will print a message to ``sys.stderr`` and raise SystemExit in
an attempt to abort the calling script.
"""
was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules
def do_download():
egg = download_setuptools(version, download_base, to_dir, download_delay)
sys.path.insert(0, egg)
import setuptools; setuptools.bootstrap_install_from = egg
try:
import pkg_resources
except ImportError:
return do_download()
try:
pkg_resources.require("setuptools>="+version); return
except pkg_resources.VersionConflict, e:
if was_imported:
print >>sys.stderr, (
"The required version of setuptools (>=%s) is not available, and\n"
"can't be installed while this script is running. Please install\n"
" a more recent version first, using 'easy_install -U setuptools'."
"\n\n(Currently using %r)"
) % (version, e.args[0])
sys.exit(2)
else:
del pkg_resources, sys.modules['pkg_resources'] # reload ok
return do_download()
except pkg_resources.DistributionNotFound:
return do_download()
def download_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
delay = 15
):
"""Download setuptools from a specified location and return its filename
`version` should be a valid setuptools version number that is available
as an egg for download under the `download_base` URL (which should end
with a '/'). `to_dir` is the directory where the egg will be downloaded.
`delay` is the number of seconds to pause before an actual download attempt.
"""
import urllib2, shutil
egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3])
url = download_base + egg_name
saveto = os.path.join(to_dir, egg_name)
src = dst = None
if not os.path.exists(saveto): # Avoid repeated downloads
try:
from distutils import log
if delay:
log.warn("""
---------------------------------------------------------------------------
This script requires setuptools version %s to run (even to display
help). I will attempt to download it for you (from
%s), but
you may need to enable firewall access for this script first.
I will start the download in %d seconds.
(Note: if this machine does not have network access, please obtain the file
%s
and place it in this directory before rerunning this script.)
---------------------------------------------------------------------------""",
version, download_base, delay, url
); from time import sleep; sleep(delay)
log.warn("Downloading %s", url)
src = urllib2.urlopen(url)
# Read/write all in one block, so we don't create a corrupt file
# if the download is interrupted.
data = _validate_md5(egg_name, src.read())
dst = open(saveto,"wb"); dst.write(data)
finally:
if src: src.close()
if dst: dst.close()
return os.path.realpath(saveto)
def main(argv, version=DEFAULT_VERSION):
"""Install or upgrade setuptools and EasyInstall"""
try:
import setuptools
except ImportError:
egg = None
try:
egg = download_setuptools(version, delay=0)
sys.path.insert(0,egg)
from setuptools.command.easy_install import main
return main(list(argv)+[egg]) # we're done here
finally:
if egg and os.path.exists(egg):
os.unlink(egg)
else:
if setuptools.__version__ == '0.0.1':
print >>sys.stderr, (
"You have an obsolete version of setuptools installed. Please\n"
"remove it from your system entirely before rerunning this script."
)
sys.exit(2)
req = "setuptools>="+version
import pkg_resources
try:
pkg_resources.require(req)
except pkg_resources.VersionConflict:
try:
from setuptools.command.easy_install import main
except ImportError:
from easy_install import main
main(list(argv)+[download_setuptools(delay=0)])
sys.exit(0) # try to force an exit
else:
if argv:
from setuptools.command.easy_install import main
main(argv)
else:
print "Setuptools version",version,"or greater has been installed."
print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)'
def update_md5(filenames):
"""Update our built-in md5 registry"""
import re
for name in filenames:
base = os.path.basename(name)
f = open(name,'rb')
md5_data[base] = md5(f.read()).hexdigest()
f.close()
data = [" %r: %r,\n" % it for it in md5_data.items()]
data.sort()
repl = "".join(data)
import inspect
srcfile = inspect.getsourcefile(sys.modules[__name__])
f = open(srcfile, 'rb'); src = f.read(); f.close()
match = re.search("\nmd5_data = {\n([^}]+)}", src)
if not match:
print >>sys.stderr, "Internal error!"
sys.exit(2)
src = src[:match.start(1)] + repl + src[match.end(1):]
f = open(srcfile,'w')
f.write(src)
f.close()
if __name__=='__main__':
if len(sys.argv)>2 and sys.argv[1]=='--md5update':
update_md5(sys.argv[2:])
else:
main(sys.argv[1:])
| Python |
"""Routes configuration
The more specific and detailed routes should be defined first so they
may take precedent over the more generic routes. For more information
refer to the routes manual at http://routes.groovie.org/docs/
"""
from routes import Mapper
def make_map(config):
"""Create, configure and return the routes Mapper"""
map = Mapper(directory=config['pylons.paths']['controllers'],
always_scan=config['debug'])
map.minimization = False
# The ErrorController route (handles 404/500 error pages); it should
# likely stay at the top, ensuring it can always be resolved
map.connect('/error/{action}', controller='error')
map.connect('/error/{action}/{id}', controller='error')
# CUSTOM ROUTES HERE
# Map the /admin url to FA's AdminController
# Map static files
map.connect('fa_static', '/admin/_static/{path_info:.*}', controller='admin', action='static')
# Index page
map.connect('admin', '/admin', controller='admin', action='models')
map.connect('formatted_admin', '/admin.json', controller='admin', action='models', format='json')
# Models
map.resource('model', 'models', path_prefix='/admin/{model_name}', controller='admin')
# serve couchdb's Pets as resource
# Index page
map.connect('couchdb', '/couchdb', controller='couchdb', action='models')
# Model resources
map.resource('node', 'nodes', path_prefix='/couchdb/{model_name}', controller='couchdb')
# serve Owner Model as resource
map.resource('owner', 'owners')
map.connect('/{controller}/{action}')
map.connect('/{controller}/{action}/{id}')
return map
| Python |
"""Pylons middleware initialization"""
from beaker.middleware import SessionMiddleware
from paste.cascade import Cascade
from paste.registry import RegistryManager
from paste.urlparser import StaticURLParser
from paste.deploy.converters import asbool
from pylons.middleware import ErrorHandler, StatusCodeRedirect
from pylons.wsgiapp import PylonsApp
from routes.middleware import RoutesMiddleware
from pylonsapp.config.environment import load_environment
def make_app(global_conf, full_stack=True, static_files=True, **app_conf):
"""Create a Pylons WSGI application and return it
``global_conf``
The inherited configuration for this application. Normally from
the [DEFAULT] section of the Paste ini file.
``full_stack``
Whether this application provides a full WSGI stack (by default,
meaning it handles its own exceptions and errors). Disable
full_stack when this application is "managed" by another WSGI
middleware.
``static_files``
Whether this application serves its own static files; disable
when another web server is responsible for serving them.
``app_conf``
The application's local configuration. Normally specified in
the [app:<name>] section of the Paste ini file (where <name>
defaults to main).
"""
# Configure the Pylons environment
config = load_environment(global_conf, app_conf)
# The Pylons WSGI app
app = PylonsApp(config=config)
# Routing/Session/Cache Middleware
app = RoutesMiddleware(app, config['routes.map'])
app = SessionMiddleware(app, config)
# CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)
if asbool(full_stack):
# Handle Python exceptions
app = ErrorHandler(app, global_conf, **config['pylons.errorware'])
# Display error documents for 401, 403, 404 status codes (and
# 500 when debug is disabled)
if asbool(config['debug']):
app = StatusCodeRedirect(app)
else:
app = StatusCodeRedirect(app, [400, 401, 403, 404, 500])
# Establish the Registry for this application
app = RegistryManager(app)
if asbool(static_files):
# Serve static files
static_app = StaticURLParser(config['pylons.paths']['static_files'])
app = Cascade([static_app, app])
app.config = config
return app
| Python |
"""Pylons environment configuration"""
import os
from mako.lookup import TemplateLookup
from pylons.configuration import PylonsConfig
from pylons.error import handle_mako_error
from sqlalchemy import engine_from_config
import pylonsapp.lib.app_globals as app_globals
import pylonsapp.lib.helpers
from pylonsapp.config.routing import make_map
from pylonsapp.model import init_model
def load_environment(global_conf, app_conf):
"""Configure the Pylons environment via the ``pylons.config``
object
"""
config = PylonsConfig()
# Pylons paths
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
paths = dict(root=root,
controllers=os.path.join(root, 'controllers'),
static_files=os.path.join(root, 'public'),
templates=[os.path.join(root, 'templates')])
# Initialize config with the basic options
config.init_app(global_conf, app_conf, package='pylonsapp', paths=paths)
config['routes.map'] = make_map(config)
config['pylons.app_globals'] = app_globals.Globals(config)
config['pylons.h'] = pylonsapp.lib.helpers
# Setup cache object as early as possible
import pylons
pylons.cache._push_object(config['pylons.app_globals'].cache)
# Create the Mako TemplateLookup, with the default auto-escaping
config['pylons.app_globals'].mako_lookup = TemplateLookup(
directories=paths['templates'],
error_handler=handle_mako_error,
module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
input_encoding='utf-8', default_filters=['escape'],
imports=['from webhelpers.html import escape'])
# Setup the SQLAlchemy database engine
engine = engine_from_config(config, 'sqlalchemy.')
init_model(engine)
# CONFIGURATION OPTIONS HERE (note: all config options will override
# any Pylons config options)
return config
| Python |
"""Pylons application test package
This package assumes the Pylons environment is already loaded, such as
when this script is imported from the `nosetests --with-pylons=test.ini`
command.
This module initializes the application via ``websetup`` (`paster
setup-app`) and provides the base testing objects.
"""
from unittest import TestCase
from paste.deploy import loadapp
from paste.script.appinstall import SetupCommand
from pylons import url
from routes.util import URLGenerator
from webtest import TestApp
import pylons.test
__all__ = ['environ', 'url', 'TestController']
# Invoke websetup with the current config file
SetupCommand('setup-app').run([pylons.test.pylonsapp.config['__file__']])
environ = {}
class TestController(TestCase):
def __init__(self, *args, **kwargs):
wsgiapp = pylons.test.pylonsapp
config = wsgiapp.config
self.app = TestApp(wsgiapp)
url._push_object(URLGenerator(config['routes.map'], environ))
TestCase.__init__(self, *args, **kwargs)
| Python |
import logging
from pylons import request, response, session, url, tmpl_context as c
from pylons.controllers.util import abort, redirect
from pylonsapp.lib.base import BaseController, render
from pylonsapp.model import meta
from pylonsapp import model
from pylonsapp.forms.fsblob import Files
log = logging.getLogger(__name__)
class FsblobController(BaseController):
def index(self, id=None):
if id:
record = meta.Session.query(model.Files).filter_by(id=id).first()
else:
record = model.Files()
assert record is not None, repr(id)
c.fs = Files.bind(record, data=request.POST or None)
if request.POST and c.fs.validate():
c.fs.sync()
if id:
meta.Session.update(record)
else:
meta.Session.add(record)
meta.Session.commit()
redirect(url.current(id=record.id))
return render('/form.mako')
| Python |
import cgi
from paste.urlparser import PkgResourcesParser
from pylons.middleware import error_document_template
from webhelpers.html.builder import literal
from pylonsapp.lib.base import BaseController
class ErrorController(BaseController):
"""Generates error documents as and when they are required.
The ErrorDocuments middleware forwards to ErrorController when error
related status codes are returned from the application.
This behaviour can be altered by changing the parameters to the
ErrorDocuments middleware in your config/middleware.py file.
"""
def document(self):
"""Render the error document"""
request = self._py_object.request
resp = request.environ.get('pylons.original_response')
content = literal(resp.body) or cgi.escape(request.GET.get('message', ''))
page = error_document_template % \
dict(prefix=request.environ.get('SCRIPT_NAME', ''),
code=cgi.escape(request.GET.get('code', str(resp.status_int))),
message=content)
return page
def img(self, id):
"""Serve Pylons' stock images"""
return self._serve_file('/'.join(['media/img', id]))
def style(self, id):
"""Serve Pylons' stock stylesheets"""
return self._serve_file('/'.join(['media/style', id]))
def _serve_file(self, path):
"""Call Paste's FileApp (a WSGI application) to serve the file
at the specified path
"""
request = self._py_object.request
request.environ['PATH_INFO'] = '/%s' % path
return PkgResourcesParser('pylons', 'pylons')(request.environ, self.start_response)
| Python |
import logging
from pylons import request, response, session, url, tmpl_context as c
from pylons.controllers.util import abort, redirect
from pylonsapp.lib.base import BaseController, render
from pylonsapp.model import meta
from pylonsapp import model
from pylonsapp.forms import FieldSet
log = logging.getLogger(__name__)
Foo = FieldSet(model.Foo)
Foo.configure(options=[Foo.bar.label('This is the bar field')])
class BasicController(BaseController):
def index(self, id=None):
if id:
record = meta.Session.query(model.Foo).filter_by(id=id).first()
else:
record = model.Foo()
assert record is not None, repr(id)
c.fs = Foo.bind(record, data=request.POST or None)
if request.POST and c.fs.validate():
c.fs.sync()
if id:
meta.Session.update(record)
else:
meta.Session.add(record)
meta.Session.commit()
redirect(url.current(id=record.id))
return render('/form.mako')
| Python |
import logging
from pylons import request, response, session, url, tmpl_context as c
from pylons.controllers.util import abort, redirect
from pylonsapp.lib.base import BaseController, render
from pylonsapp import model
from pylonsapp.model import meta
from formalchemy.ext.pylons.controller import RESTController
log = logging.getLogger(__name__)
class OwnersController(BaseController):
def Session(self):
return meta.Session
def get_model(self):
return model.Owner
OwnersController = RESTController(OwnersController, 'owner', 'owners')
| Python |
import logging
from formalchemy.ext.pylons.controller import ModelsController
from webhelpers.paginate import Page
from pylonsapp.lib.base import BaseController, render
from pylonsapp import model
from pylonsapp import forms
from pylonsapp.model import meta
log = logging.getLogger(__name__)
class AdminControllerBase(BaseController):
model = model # where your SQLAlchemy mappers are
forms = forms # module containing FormAlchemy fieldsets definitions
def Session(self): # Session factory
return meta.Session
## customize the query for a model listing
# def get_page(self):
# if self.model_name == 'Foo':
# return Page(meta.Session.query(model.Foo).order_by(model.Foo.bar)
# return super(AdminControllerBase, self).get_page()
AdminController = ModelsController(AdminControllerBase,
prefix_name='admin',
member_name='model',
collection_name='models',
)
| Python |
__doc__ = """This is an example on ow to setup a CRUD UI with couchdb as
backend"""
import os
import logging
import pylonsapp
from couchdbkit import *
from webhelpers.paginate import Page
from pylonsapp.lib.base import BaseController, render
from couchdbkit.loaders import FileSystemDocsLoader
from formalchemy.ext import couchdb
from formalchemy.ext.pylons.controller import ModelsController
log = logging.getLogger(__name__)
class Person(couchdb.Document):
"""A Person node"""
name = StringProperty(required=True)
def __unicode__(self):
return self.name or u''
class Pet(couchdb.Document):
"""A Pet node"""
name = StringProperty(required=True)
type = StringProperty(required=True)
birthdate = DateProperty(auto_now=True)
weight_in_pounds = IntegerProperty(default=0)
spayed_or_neutered = BooleanProperty()
owner = SchemaListProperty(Person)
def __unicode__(self):
return self.name
# You don't need a try/except. This is just to allow to run FA's tests without
# couchdb installed. Btw this have to be in another place in your app. eg: you
# don't need to sync views each time the controller is loaded.
try:
server = Server()
if server: pass
except:
server = None
else:
db = server.get_or_create_db('formalchemy_test')
design_docs = os.path.join(os.path.dirname(pylonsapp.__file__), '_design')
loader = FileSystemDocsLoader(design_docs)
loader.sync(db, verbose=True)
contain(db, Pet, Person)
class CouchdbController(BaseController):
# override default classes to use couchdb fieldsets
FieldSet = couchdb.FieldSet
Grid = couchdb.Grid
model = [Person, Pet]
def Session(self):
"""return a formalchemy.ext.couchdb.Session"""
return couchdb.Session(db)
CouchdbController = ModelsController(CouchdbController, prefix_name='couchdb', member_name='node', collection_name='nodes')
| Python |
"""Setup the pylonsapp application"""
import logging
import pylons.test
from pylonsapp.config.environment import load_environment
from pylonsapp.model.meta import Session, metadata
log = logging.getLogger(__name__)
def setup_app(command, conf, vars):
"""Place any commands to setup pylonsapp here"""
# Don't reload the app if it was loaded under the testing environment
if not pylons.test.pylonsapp:
load_environment(conf.global_conf, conf.local_conf)
# Create the tables if they aren't there already
metadata.create_all(bind=Session.bind)
from pylonsapp import model
o = model.Owner()
o.name = 'gawel'
Session.add(o)
for i in range(50):
o = model.Owner()
o.name = 'owner%i' % i
Session.add(o)
Session.commit()
| Python |
# -*- coding: utf-8 -*-
from pylons import config
from pylonsapp import model
from pylonsapp.forms import FieldSet
from formalchemy.ext.fsblob import FileFieldRenderer
# get the storage path from configuration
FileFieldRenderer.storage_path = config['app_conf']['storage_path']
Files = FieldSet(model.Files)
Files.configure(options=[Files.path.with_renderer(FileFieldRenderer)])
| Python |
from pylons import config
from pylonsapp import model
from pylonsapp.lib.base import render
from formalchemy import config as fa_config
from formalchemy import templates
from formalchemy import validators
from formalchemy import fields
from formalchemy import forms
from formalchemy import tables
from formalchemy.ext.fsblob import FileFieldRenderer
from formalchemy.ext.fsblob import ImageFieldRenderer
#if 'storage_path' in config['app_conf']:
# # set the storage_path if we can find an options in app_conf
# FileFieldRenderer.storage_path = config['app_conf']['storage_path']
# ImageFieldRenderer.storage_path = config['app_conf']['storage_path']
fa_config.encoding = 'utf-8'
class TemplateEngine(templates.TemplateEngine):
def render(self, name, **kwargs):
return render('/forms/%s.mako' % name, extra_vars=kwargs)
fa_config.engine = TemplateEngine()
class FieldSet(forms.FieldSet):
pass
class Grid(tables.Grid):
pass
## Initialize fieldsets
#Foo = FieldSet(model.Foo)
#Reflected = FieldSet(Reflected)
## Initialize grids
#FooGrid = Grid(model.Foo)
#ReflectedGrid = Grid(Reflected)
| Python |
"""The application's Globals object"""
from beaker.cache import CacheManager
from beaker.util import parse_cache_config_options
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self, config):
"""One instance of Globals is created during application
initialization and is available during requests via the
'app_globals' variable
"""
self.cache = CacheManager(**parse_cache_config_options(config))
| Python |
"""Helper functions
Consists of functions to typically be used within templates, but also
available to Controllers. This module is available to templates as 'h'.
"""
# Import helpers as desired, or define your own, ie:
#from webhelpers.html.tags import checkbox, password
| Python |
"""The base Controller API
Provides the BaseController class for subclassing.
"""
from pylons.controllers import WSGIController
from pylons.templating import render_mako as render
from pylonsapp.model.meta import Session
class BaseController(WSGIController):
def __call__(self, environ, start_response):
"""Invoke the Controller"""
# WSGIController.__call__ dispatches to the Controller method
# the request is routed to. This routing information is
# available in environ['pylons.routes_dict']
try:
return WSGIController.__call__(self, environ, start_response)
finally:
Session.remove()
| Python |
"""SQLAlchemy Metadata and Session object"""
from sqlalchemy import MetaData
from sqlalchemy.orm import scoped_session, sessionmaker
__all__ = ['Session', 'metadata']
# SQLAlchemy session manager. Updated by model.init_model()
Session = scoped_session(sessionmaker())
# Global metadata. If you have multiple databases with overlapping table
# names, you'll need a metadata for each database
metadata = MetaData()
| Python |
"""The application's model objects"""
import sqlalchemy as sa
from sqlalchemy import orm
from pylonsapp.model.meta import Session, metadata
def init_model(engine):
"""Call me before using any of the tables or classes in the model"""
Session.configure(bind=engine)
foo_table = sa.Table("Foo", meta.metadata,
sa.Column("id", sa.types.Integer, primary_key=True),
sa.Column("bar", sa.types.String(255), nullable=False),
)
class Foo(object):
pass
orm.mapper(Foo, foo_table)
files_table = sa.Table("Files", meta.metadata,
sa.Column("id", sa.types.Integer, primary_key=True),
sa.Column("path", sa.types.String(255), nullable=False),
)
class Files(object):
pass
orm.mapper(Files, files_table)
animals_table = sa.Table("Animals", meta.metadata,
sa.Column("id", sa.types.Integer, primary_key=True),
sa.Column("name", sa.types.String(255), nullable=False),
sa.Column("owner_id", sa.ForeignKey('Owners.id'), nullable=False),
)
class Animal(object):
def __unicode__(self):
return self.name
orm.mapper(Animal, animals_table)
owners_table = sa.Table("Owners", meta.metadata,
sa.Column("id", sa.types.Integer, primary_key=True),
sa.Column("name", sa.types.String(255), nullable=False),
)
class Owner(object):
def __unicode__(self):
return self.name
orm.mapper(Owner, owners_table, properties=dict(
animals=orm.relation(Animal,
backref=orm.backref('owner', uselist=False))
))
| Python |
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='pylonsapp',
version='0.1',
description='',
author='',
author_email='',
url='',
install_requires=[
"Pylons>=0.9.7",
"SQLAlchemy>=0.5",
],
setup_requires=["PasteScript>=1.6.3"],
packages=find_packages(exclude=['ez_setup']),
include_package_data=True,
test_suite='nose.collector',
package_data={'pylonsapp': ['i18n/*/LC_MESSAGES/*.mo']},
#message_extractors={'pylonsapp': [
# ('**.py', 'python', None),
# ('templates/**.mako', 'mako', {'input_encoding': 'utf-8'}),
# ('public/**', 'ignore', None)]},
zip_safe=False,
paster_plugins=['PasteScript', 'Pylons'],
entry_points="""
[paste.app_factory]
main = pylonsapp.config.middleware:make_app
[paste.app_install]
main = pylons.util:PylonsInstaller
""",
)
| Python |
#!bin/python
import webob
import formalchemy
import sqlalchemy as sa
from sqlalchemy.orm import relation, backref
from sqlalchemy.ext.declarative import declarative_base
from repoze.profile.profiler import AccumulatingProfileMiddleware
def make_middleware(app):
return AccumulatingProfileMiddleware(
app,
log_filename='/tmp/profile.log',
discard_first_request=True,
flush_at_shutdown=True,
path='/__profile__')
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.Unicode(12))
fullname = sa.Column(sa.Unicode(40))
password = sa.Column(sa.Unicode(20))
def simple_app(environ, start_response):
resp = webob.Response()
fs = formalchemy.FieldSet(User)
body = fs.bind(User()).render()
body += fs.bind(User()).render()
fs.rebind(User())
body += fs.render()
resp.body = body
return resp(environ, start_response)
if __name__ == '__main__':
import sys
import os
import signal
from paste.httpserver import serve
print 'Now do:'
print 'ab -n 100 http://127.0.0.1:8080/'
print 'wget -O - http://127.0.0.1:8080/__profile__'
serve(make_middleware(simple_app))
| Python |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import xml.sax.saxutils
from os.path import join
import sys
import os
try:
from msgfmt import Msgfmt
except:
sys.path.insert(0, join(os.getcwd(), 'formalchemy'))
from msgfmt import Msgfmt
def compile_po(path):
for language in os.listdir(path):
lc_path = join(path, language, 'LC_MESSAGES')
if os.path.isdir(lc_path):
for domain_file in os.listdir(lc_path):
if domain_file.endswith('.po'):
file_path = join(lc_path, domain_file)
mo_file = join(lc_path, '%s.mo' % domain_file[:-3])
mo_content = Msgfmt(file_path, name=file_path).get()
mo = open(mo_file, 'wb')
mo.write(mo_content)
mo.close()
try:
compile_po(join(os.getcwd(), 'formalchemy', 'i18n_resources'))
except Exception, e:
print 'Error while building .mo files'
print '%r - %s' % (e, e)
def read(filename):
text = open(filename).read()
text = unicode(text, 'utf-8').encode('ascii', 'xmlcharrefreplace')
return xml.sax.saxutils.escape(text)
long_description = '.. contents::\n\n' +\
'Description\n' +\
'===========\n\n' +\
read('README.txt') +\
'\n\n' +\
'Changes\n' +\
'=======\n\n' +\
read('CHANGELOG.txt')
setup(name='FormAlchemy',
license='MIT License',
version='1.3.6',
description='FormAlchemy greatly speeds development with SQLAlchemy mapped classes (models) in a HTML forms environment.',
long_description=long_description,
author='Alexandre Conrad, Jonathan Ellis, Gaël Pasgrimaud',
author_email='formalchemy@googlegroups.com',
url='http://formalchemy.googlecode.com',
download_url='http://code.google.com/p/formalchemy/downloads/list',
install_requires=['SQLAlchemy', 'Tempita', 'WebHelpers'],
packages=find_packages(),
package_data={'formalchemy': ['*.tmpl', 'i18n_resources/*/LC_MESSAGES/formalchemy.mo',
'ext/pylons/*.mako', 'ext/pylons/resources/*.css', 'ext/pylons/resources/*.png',
'tests/data/mako/*.mako', 'tests/data/genshi/*.html',
'paster_templates/pylons_fa/+package+/*/*_tmpl',
]},
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Software Development :: User Interfaces',
'Topic :: Text Processing :: Markup :: HTML',
'Topic :: Utilities',
],
message_extractors = {'formalchemy': [
('**.py', 'python', None),
('**.mako', 'mako', None),
('**.tmpl', 'python', None)]},
zip_safe=False,
entry_points = """
[paste.paster_create_template]
pylons_fa = formalchemy.ext.pylons.pastertemplate:PylonsTemplate
""",
)
| Python |
##############################################################################
#
# Copyright (c) 2006 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Bootstrap a buildout-based project
Simply run this script in a directory containing a buildout.cfg.
The script accepts buildout command-line options, so you can
use the -c option to specify an alternate configuration file.
"""
import os, shutil, sys, tempfile, textwrap, urllib, urllib2, subprocess
from optparse import OptionParser
if sys.platform == 'win32':
def quote(c):
if ' ' in c:
return '"%s"' % c # work around spawn lamosity on windows
else:
return c
else:
quote = str
# See zc.buildout.easy_install._has_broken_dash_S for motivation and comments.
stdout, stderr = subprocess.Popen(
[sys.executable, '-Sc',
'try:\n'
' import ConfigParser\n'
'except ImportError:\n'
' print 1\n'
'else:\n'
' print 0\n'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
has_broken_dash_S = bool(int(stdout.strip()))
# In order to be more robust in the face of system Pythons, we want to
# run without site-packages loaded. This is somewhat tricky, in
# particular because Python 2.6's distutils imports site, so starting
# with the -S flag is not sufficient. However, we'll start with that:
if not has_broken_dash_S and 'site' in sys.modules:
# We will restart with python -S.
args = sys.argv[:]
args[0:0] = [sys.executable, '-S']
args = map(quote, args)
os.execv(sys.executable, args)
# Now we are running with -S. We'll get the clean sys.path, import site
# because distutils will do it later, and then reset the path and clean
# out any namespace packages from site-packages that might have been
# loaded by .pth files.
clean_path = sys.path[:]
import site
sys.path[:] = clean_path
for k, v in sys.modules.items():
if k in ('setuptools', 'pkg_resources') or (
hasattr(v, '__path__') and
len(v.__path__)==1 and
not os.path.exists(os.path.join(v.__path__[0],'__init__.py'))):
# This is a namespace package. Remove it.
sys.modules.pop(k)
is_jython = sys.platform.startswith('java')
setuptools_source = 'http://peak.telecommunity.com/dist/ez_setup.py'
distribute_source = 'http://python-distribute.org/distribute_setup.py'
# parsing arguments
def normalize_to_url(option, opt_str, value, parser):
if value:
if '://' not in value: # It doesn't smell like a URL.
value = 'file://%s' % (
urllib.pathname2url(
os.path.abspath(os.path.expanduser(value))),)
if opt_str == '--download-base' and not value.endswith('/'):
# Download base needs a trailing slash to make the world happy.
value += '/'
else:
value = None
name = opt_str[2:].replace('-', '_')
setattr(parser.values, name, value)
usage = '''\
[DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options]
Bootstraps a buildout-based project.
Simply run this script in a directory containing a buildout.cfg, using the
Python that you want bin/buildout to use.
Note that by using --setup-source and --download-base to point to
local resources, you can keep this script from going over the network.
'''
parser = OptionParser(usage=usage)
parser.add_option("-v", "--version", dest="version",
help="use a specific zc.buildout version")
parser.add_option("-d", "--distribute",
action="store_true", dest="use_distribute", default=False,
help="Use Distribute rather than Setuptools.")
parser.add_option("--setup-source", action="callback", dest="setup_source",
callback=normalize_to_url, nargs=1, type="string",
help=("Specify a URL or file location for the setup file. "
"If you use Setuptools, this will default to " +
setuptools_source + "; if you use Distribute, this "
"will default to " + distribute_source +"."))
parser.add_option("--download-base", action="callback", dest="download_base",
callback=normalize_to_url, nargs=1, type="string",
help=("Specify a URL or directory for downloading "
"zc.buildout and either Setuptools or Distribute. "
"Defaults to PyPI."))
parser.add_option("--eggs",
help=("Specify a directory for storing eggs. Defaults to "
"a temporary directory that is deleted when the "
"bootstrap script completes."))
parser.add_option("-t", "--accept-buildout-test-releases",
dest='accept_buildout_test_releases',
action="store_true", default=False,
help=("Normally, if you do not specify a --version, the "
"bootstrap script and buildout gets the newest "
"*final* versions of zc.buildout and its recipes and "
"extensions for you. If you use this flag, "
"bootstrap and buildout will get the newest releases "
"even if they are alphas or betas."))
parser.add_option("-c", None, action="store", dest="config_file",
help=("Specify the path to the buildout configuration "
"file to be used."))
options, args = parser.parse_args()
# if -c was provided, we push it back into args for buildout's main function
if options.config_file is not None:
args += ['-c', options.config_file]
if options.eggs:
eggs_dir = os.path.abspath(os.path.expanduser(options.eggs))
else:
eggs_dir = tempfile.mkdtemp()
if options.setup_source is None:
if options.use_distribute:
options.setup_source = distribute_source
else:
options.setup_source = setuptools_source
if options.accept_buildout_test_releases:
args.append('buildout:accept-buildout-test-releases=true')
args.append('bootstrap')
try:
import pkg_resources
import setuptools # A flag. Sometimes pkg_resources is installed alone.
if not hasattr(pkg_resources, '_distribute'):
raise ImportError
except ImportError:
ez_code = urllib2.urlopen(
options.setup_source).read().replace('\r\n', '\n')
ez = {}
exec ez_code in ez
setup_args = dict(to_dir=eggs_dir, download_delay=0)
if options.download_base:
setup_args['download_base'] = options.download_base
if options.use_distribute:
setup_args['no_fake'] = True
ez['use_setuptools'](**setup_args)
if 'pkg_resources' in sys.modules:
reload(sys.modules['pkg_resources'])
import pkg_resources
# This does not (always?) update the default working set. We will
# do it.
for path in sys.path:
if path not in pkg_resources.working_set.entries:
pkg_resources.working_set.add_entry(path)
cmd = [quote(sys.executable),
'-c',
quote('from setuptools.command.easy_install import main; main()'),
'-mqNxd',
quote(eggs_dir)]
if not has_broken_dash_S:
cmd.insert(1, '-S')
find_links = options.download_base
if not find_links:
find_links = os.environ.get('bootstrap-testing-find-links')
if find_links:
cmd.extend(['-f', quote(find_links)])
if options.use_distribute:
setup_requirement = 'distribute'
else:
setup_requirement = 'setuptools'
ws = pkg_resources.working_set
setup_requirement_path = ws.find(
pkg_resources.Requirement.parse(setup_requirement)).location
env = dict(
os.environ,
PYTHONPATH=setup_requirement_path)
requirement = 'zc.buildout'
version = options.version
if version is None and not options.accept_buildout_test_releases:
# Figure out the most recent final version of zc.buildout.
import setuptools.package_index
_final_parts = '*final-', '*final'
def _final_version(parsed_version):
for part in parsed_version:
if (part[:1] == '*') and (part not in _final_parts):
return False
return True
index = setuptools.package_index.PackageIndex(
search_path=[setup_requirement_path])
if find_links:
index.add_find_links((find_links,))
req = pkg_resources.Requirement.parse(requirement)
if index.obtain(req) is not None:
best = []
bestv = None
for dist in index[req.project_name]:
distv = dist.parsed_version
if _final_version(distv):
if bestv is None or distv > bestv:
best = [dist]
bestv = distv
elif distv == bestv:
best.append(dist)
if best:
best.sort()
version = best[-1].version
if version:
requirement = '=='.join((requirement, version))
cmd.append(requirement)
if is_jython:
import subprocess
exitcode = subprocess.Popen(cmd, env=env).wait()
else: # Windows prefers this, apparently; otherwise we would prefer subprocess
exitcode = os.spawnle(*([os.P_WAIT, sys.executable] + cmd + [env]))
if exitcode != 0:
sys.stdout.flush()
sys.stderr.flush()
print ("An error occurred when trying to install zc.buildout. "
"Look above this message for any errors that "
"were output by easy_install.")
sys.exit(exitcode)
ws.add_entry(eggs_dir)
ws.require(requirement)
import zc.buildout.buildout
zc.buildout.buildout.main(args)
if not options.eggs: # clean up temporary egg directory
shutil.rmtree(eggs_dir)
| Python |
# Copyright (C) 2007 Alexandre Conrad, alexandre (dot) conrad (at) gmail (dot) com
#
# This module is part of FormAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import warnings
import logging
logger = logging.getLogger('formalchemy.' + __name__)
import base, fields
from validators import ValidationError
from formalchemy import config
from formalchemy import exceptions
from tempita import Template as TempitaTemplate # must import after base
__all__ = ['AbstractFieldSet', 'FieldSet', 'form_data']
def form_data(fieldset, params):
"""
deprecated. moved the "pull stuff out of a request object" stuff
into relevant_data(). until this is removed it is a no-op.
"""
return params
class AbstractFieldSet(base.EditableRenderer):
"""
`FieldSets` are responsible for generating HTML fields from a given
`model`.
You can derive your own subclasses from `FieldSet` or `AbstractFieldSet`
to provide a customized `render` and/or `configure`.
`AbstractBaseSet` encorporates validation/errors logic and provides a default
`configure` method. It does *not* provide `render`.
You can write `render` by manually sticking strings together if that's what you want,
but we recommend using a templating package for clarity and maintainability.
!FormAlchemy includes the Tempita templating package as formalchemy.tempita;
see http://pythonpaste.org/tempita/ for documentation.
`formalchemy.forms.template_text_tempita` is the default template used by `FieldSet.`
!FormAlchemy also includes a Mako version, `formalchemy.forms.template_text_mako`,
and will use that instead if Mako is available. The rendered HTML is identical
but (we suspect) Mako is faster.
"""
def __init__(self, *args, **kwargs):
base.EditableRenderer.__init__(self, *args, **kwargs)
self.validator = None
self._errors = []
def configure(self, pk=False, exclude=[], include=[], options=[], global_validator=None):
"""
`global_validator` should be a function that performs validations that need
to know about the entire form. The other parameters are passed directly
to `ModelRenderer.configure`.
- `pk=False`:
set to True to include primary key columns
- `exclude=[]`:
an iterable of attributes to exclude. Other attributes will
be rendered normally
- `include=[]`:
an iterable of attributes to include. Other attributes will
not be rendered
- `options=[]`:
an iterable of modified attributes. The set of attributes to
be rendered is unaffected
- `global_validator=None`:
`global_validator` should be a function that performs
validations that need to know about the entire form.
Only one of {`include`, `exclude`} may be specified.
Note that there is no option to include foreign keys. This is
deliberate. Use `include` if you really need to manually edit FKs.
If `include` is specified, fields will be rendered in the order given
in `include`. Otherwise, fields will be rendered in order of declaration,
with table fields before mapped properties. (However, mapped property order
is sometimes ambiguous, e.g. when backref is involved. In these cases,
FormAlchemy will take its best guess, but you may have to force the
"right" order with `include`.)
"""
base.EditableRenderer.configure(self, pk, exclude, include, options)
self.validator = global_validator
def validate(self):
"""
Validate attributes and `global_validator`.
If validation fails, the validator should raise `ValidationError`.
"""
if self.data is None:
raise Exception('Cannot validate without binding data')
success = True
for field in self.render_fields.itervalues():
success = field._validate() and success
# run this _after_ the field validators, since each field validator
# resets its error list. we want to allow the global validator to add
# errors to individual fields.
if self.validator:
self._errors = []
try:
self.validator(self)
except ValidationError, e:
self._errors = e.args
success = False
return success
@property
def errors(self):
"""
A dictionary of validation failures. Always empty before `validate()` is run.
Dictionary keys are attributes; values are lists of messages given to `ValidationError`.
Global errors (not specific to a single attribute) are under the key `None`.
"""
errors = {}
if self._errors:
errors[None] = self._errors
errors.update(dict([(field, field.errors)
for field in self.render_fields.itervalues() if field.errors]))
return errors
def __repr__(self):
_fields = self._fields
conf = ''
if self._render_fields:
conf = ' (configured)'
_fields = self._render_fields
return '<%s%s with %r>' % (self.__class__.__name__, conf,
_fields.keys())
class FieldSet(AbstractFieldSet):
"""
A `FieldSet` is bound to a SQLAlchemy mapped instance (or class, for
creating new instances) and can render a form for editing that instance,
perform validation, and sync the form data back to the bound instance.
"""
engine = _render = _render_readonly = None
def __init__(self, *args, **kwargs):
AbstractFieldSet.__init__(self, *args, **kwargs)
self.focus = True
self.readonly = False
def configure(self, pk=False, exclude=[], include=[], options=[], global_validator=None, focus=True, readonly=False):
"""
Besides the options in :meth:`AbstractFieldSet.configure`,
`FieldSet.configure` takes the `focus` parameter, which should be the
attribute (e.g., `fs.orders`) whose rendered input element gets focus. Default value is
True, meaning, focus the first element. False means do not focus at
all.
This `configure` adds two parameters:
- `focus=True`:
the attribute (e.g., `fs.orders`) whose rendered input element
gets focus. Default value is True, meaning, focus the first
element. False means do not focus at all.
- `readonly=False`:
if true, the fieldset will be rendered as a table (tbody)
instead of a group of input elements. Opening and closing
table tags are not included.
"""
AbstractFieldSet.configure(self, pk, exclude, include, options, global_validator)
self.focus = focus
self.readonly = readonly
def validate(self):
if self.readonly:
raise Exception('Cannot validate a read-only FieldSet')
return AbstractFieldSet.validate(self)
def sync(self):
if self.readonly:
raise Exception('Cannot sync a read-only FieldSet')
AbstractFieldSet.sync(self)
def render(self, **kwargs):
if fields._pk(self.model) != self._bound_pk and self.data is not None:
msg = ("Primary key of model has changed since binding, "
"probably due to sync()ing a new instance (from %r to %r). "
"You can solve this by either binding to a model "
"with the original primary key again, or by binding data to None.")
raise exceptions.PkError(msg % (self._bound_pk, fields._pk(self.model)))
engine = self.engine or config.engine
if self._render or self._render_readonly:
warnings.warn(DeprecationWarning('_render and _render_readonly are deprecated and will be removed in 1.5. Use a TemplateEngine instead'))
if self.readonly:
if self._render_readonly is not None:
engine._update_args(kwargs)
return self._render_readonly(fieldset=self, **kwargs)
return engine('fieldset_readonly', fieldset=self, **kwargs)
if self._render is not None:
engine._update_args(kwargs)
return self._render(fieldset=self, **kwargs)
return engine('fieldset', fieldset=self, **kwargs)
| Python |
# -*- coding: utf-8 -*-
import os
import sys
from formalchemy.i18n import get_translator
from formalchemy import helpers
from tempita import Template as TempitaTemplate
try:
from mako.lookup import TemplateLookup
from mako.template import Template as MakoTemplate
from mako.exceptions import TopLevelLookupException
HAS_MAKO = True
except ImportError:
HAS_MAKO = False
try:
from genshi.template import TemplateLoader as GenshiTemplateLoader
HAS_GENSHI = True
except ImportError:
HAS_GENSHI = False
MAKO_TEMPLATES = os.path.join(
os.path.dirname(__file__),
'paster_templates','pylons_fa','+package+','templates', 'forms')
class TemplateEngine(object):
"""Base class for templates engines
"""
directories = []
extension = None
_templates = ['fieldset', 'fieldset_readonly',
'grid', 'grid_readonly']
def __init__(self, **kw):
self.templates = {}
if 'extension' in kw:
self.extension = kw.pop('extension')
if 'directories' in kw:
self.directories = list(kw.pop('directories'))
for name in self._templates:
self.templates[name] = self.get_template(name, **kw)
def get_template(self, name, **kw):
"""return the template object for `name`. Must be override by engines"""
return None
def get_filename(self, name):
"""return the filename for template `name`"""
for dirname in self.directories + [os.path.dirname(__file__)]:
filename = os.path.join(dirname, '%s.%s' % (name, self.extension))
if os.path.isfile(filename):
return filename
def render(self, template_name, **kwargs):
"""render the template. Must be override by engines"""
return ''
def _update_args(cls, kw):
kw['F_'] = get_translator(kw.get('lang', None)).gettext
kw['html'] = helpers
return kw
_update_args = classmethod(_update_args)
def __call__(self, template_name, **kw):
"""update kw to extend the namespace with some FA's utils then call `render`"""
self._update_args(kw)
return self.render(template_name, **kw)
class TempitaEngine(TemplateEngine):
"""Template engine for tempita. File extension is `.tmpl`.
"""
extension = 'tmpl'
def get_template(self, name, **kw):
filename = self.get_filename(name)
if filename:
return TempitaTemplate.from_filename(filename, **kw)
def render(self, template_name, **kwargs):
template = self.templates.get(template_name, None)
return template.substitute(**kwargs)
class MakoEngine(TemplateEngine):
"""Template engine for mako. File extension is `.mako`.
"""
extension = 'mako'
_lookup = None
def get_template(self, name, **kw):
if self._lookup is None:
self._lookup = TemplateLookup(directories=self.directories, **kw)
try:
return self._lookup.get_template('%s.%s' % (name, self.extension))
except TopLevelLookupException:
filename = os.path.join(MAKO_TEMPLATES, '%s.mako_tmpl' % name)
if os.path.isfile(filename):
template = TempitaTemplate.from_filename(filename)
return MakoTemplate(template.substitute(template_engine='mako'), **kw)
def render(self, template_name, **kwargs):
template = self.templates.get(template_name, None)
return template.render_unicode(**kwargs)
class GenshiEngine(TemplateEngine):
"""Template engine for genshi. File extension is `.html`.
"""
extension = 'html'
def get_template(self, name, **kw):
filename = self.get_filename(name)
if filename:
loader = GenshiTemplateLoader(os.path.dirname(filename), **kw)
return loader.load(os.path.basename(filename))
def render(self, template_name, **kwargs):
template = self.templates.get(template_name, None)
return template.generate(**kwargs).render('html', doctype=None)
if HAS_MAKO:
default_engine = MakoEngine(input_encoding='utf-8', output_encoding='utf-8')
engines = dict(mako=default_engine, tempita=TempitaEngine())
else:
default_engine = TempitaEngine()
engines = dict(tempita=TempitaEngine())
| Python |
# Copyright (C) 2007 Alexandre Conrad, alexandre (dot) conrad (at) gmail (dot) com
#
# This module is part of FormAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import os
import cgi
import logging
logger = logging.getLogger('formalchemy.' + __name__)
from copy import copy, deepcopy
import datetime
import warnings
from sqlalchemy.orm import class_mapper, Query
from sqlalchemy.orm.attributes import ScalarAttributeImpl, ScalarObjectAttributeImpl, CollectionAttributeImpl, InstrumentedAttribute
from sqlalchemy.orm.properties import CompositeProperty, ColumnProperty
from sqlalchemy.exceptions import InvalidRequestError # 0.4 support
from formalchemy import helpers as h
from formalchemy import fatypes, validators
from formalchemy import config
from formalchemy.i18n import get_translator
from formalchemy.i18n import _
__all__ = ['Field', 'FieldRenderer',
'TextFieldRenderer', 'TextAreaFieldRenderer',
'PasswordFieldRenderer', 'HiddenFieldRenderer',
'DateFieldRenderer', 'TimeFieldRenderer',
'DateTimeFieldRenderer',
'CheckBoxFieldRenderer', 'CheckBoxSet',
'deserialize_once']
########################## RENDERER STUFF ############################
def iterable(item):
try:
iter(item)
except:
return False
return True
def _stringify(k, null_value=u''):
if k is None:
return null_value
if isinstance(k, datetime.timedelta):
return '%s.%s' % (k.days, k.seconds)
elif isinstance(k, str):
return unicode(k, config.encoding)
elif isinstance(k, unicode):
return k
elif hasattr(k, '__unicode__'):
return unicode(k)
else:
return unicode(str(k), config.encoding)
def _htmlify(k, null_value=u''):
if hasattr(k, '__html__'):
try:
return h.literal(k.__html__())
except TypeError:
# not callable. skipping
pass
return _stringify(k, null_value)
NoDefault = object()
def deserialize_once(func):
"""Simple deserialization caching decorator.
To be used on a Renderer object's `deserialize` function, to cache it's
result while it's being called once for ``validate()`` and another time
when doing ``sync()``.
"""
def cache(self, *args, **kwargs):
if hasattr(self, '_deserialization_result'):
return self._deserialization_result
self._deserialization_result = func(self, *args, **kwargs)
return self._deserialization_result
return cache
class FieldRenderer(object):
"""
This should be the super class of all Renderer classes.
Renderers generate the html corresponding to a single Field,
and are also responsible for deserializing form data into
Python objects.
Subclasses should override `render` and `deserialize`.
See their docstrings for details.
"""
def __init__(self, field):
self.field = field
assert isinstance(self.field, AbstractField)
@property
def name(self):
"""Name of rendered input element.
The `name` of a field will always look like:
[fieldset_prefix-]ModelName-[pk]-fieldname
The fieldset_prefix is defined when instantiating the
`FieldSet` object, by passing the `prefix=` keyword argument.
The `ModelName` is taken by introspection from the model
passed in at that same moment.
The `pk` is the primary key of the object being edited.
If you are creating a new object, then the `pk` is an
empty string.
The `fieldname` is, well, the field name.
.. note::
This method as the direct consequence that you can not `create`
two objects of the same class, using the same FieldSet, on the
same page. You can however, create more than one object
of a certain class, provided that you create multiple FieldSet
instances and pass the `prefix=` keyword argument.
Otherwise, FormAlchemy deals very well with editing multiple
existing objects of same/different types on the same page,
without any name clash. Just be careful with multiple object
creation.
When creating your own Renderer objects, use `self.name` to
get the field's `name` HTML attribute, both when rendering
and deserializing.
"""
clsname = self.field.model.__class__.__name__
pk = self.field.parent._bound_pk
assert pk != ''
if isinstance(pk, basestring) or not iterable(pk):
pk_string = _stringify(pk)
else:
# remember to use a delimiter that can be used in the DOM (specifically, no commas).
# we don't have to worry about escaping the delimiter, since we never try to
# deserialize the generated name. All we care about is generating unique
# names for a given model's domain.
pk_string = u'_'.join([_stringify(k) for k in pk])
components = [clsname, pk_string, self.field.name]
if self.field.parent.prefix:
components.insert(0, self.field.parent.prefix)
return u"-".join(components)
@property
def value(self):
"""
Submitted value, or field value converted to string.
Return value is always either None or a string.
"""
if not self.field.is_readonly() and self.params is not None:
# submitted value. do not deserialize here since that requires valid data, which we might not have
v = self._serialized_value()
else:
v = None
# empty field will be '' -- use default value there, too
return v or self._model_value_as_string()
@property
def _value(self):
warnings.warn('FieldRenderer._value is deprecated. Use '\
'FieldRenderer.value instead')
return self.value
@property
def raw_value(self):
"""return fields field.raw_value (mean real objects, not ForeignKeys)
"""
return self.field.raw_value
def _model_value_as_string(self):
if self.field.model_value is None:
return None
if self.field.is_collection:
return [self.stringify_value(v) for v in self.field.model_value]
else:
return self.stringify_value(self.field.model_value)
def get_translator(self, **kwargs):
"""return a GNUTranslations object in the most convenient way
"""
if 'F_' in kwargs:
return kwargs.pop('F_')
if 'lang' in kwargs:
lang = kwargs.pop('lang')
else:
lang = 'en'
return get_translator(lang=lang).gettext
@property
def errors(self):
"""Return the errors on the FieldSet if any. Useful to know
if you're redisplaying a form, or showing up a fresh one.
"""
return self.field.parent.errors
def render(self, **kwargs):
"""
Render the field. Use `self.name` to get a unique name for the
input element and id. `self.value` may also be useful if
you are not rendering multiple input elements.
When rendering, you can verify `self.errors` to know
if you are rendering a new form, or re-displaying a form with
errors. Knowing that, you could select the data either from
the model, or the web form submission.
"""
raise NotImplementedError()
def render_readonly(self, **kwargs):
"""render a string representation of the field value"""
value = self.raw_value
if value is None:
return ''
if isinstance(value, list):
return h.literal(', ').join([self.stringify_value(item, as_html=True) for item in value])
if isinstance(value, unicode):
return value
return self.stringify_value(value, as_html=True)
@property
def params(self):
"""This gives access to the POSTed data, as received from
the web user. You should call `.getone`, or `.getall` to
retrieve a single value or multiple values for a given
key.
For example, when coding a renderer, you'd use:
.. sourcecode:: py
vals = self.params.getall(self.name)
to catch all the values for the renderer's form entry.
"""
return self.field.parent.data
@property
def _params(self):
warnings.warn('FieldRenderer._params is deprecated. Use '\
'FieldRenderer.params instead')
return self.params
def _serialized_value(self):
"""
Returns the appropriate value to deserialize for field's
datatype, from the user-submitted data. Only called
internally, so, if you are overriding `deserialize`,
you can use or ignore `_serialized_value` as you please.
This is broken out into a separate method so multi-input
renderers can stitch their values back into a single one
to have that can be handled by the default deserialize.
Do not attempt to deserialize here; return value should be a
string (corresponding to the output of `str` for your data
type), or for a collection type, a a list of strings,
or None if no value was submitted for this renderer.
The default _serialized_value returns the submitted value(s)
in the input element corresponding to self.name.
"""
if self.field.is_collection:
return self.params.getall(self.name)
return self.params.getone(self.name)
def deserialize(self):
"""Turns the user-submitted data into a Python value.
The raw data received from the web can be accessed via
`self.params`. This dict-like object usually accepts the
`getone()` and `getall()` method calls.
For SQLAlchemy
collections, return a list of primary keys, and !FormAlchemy
will take care of turning that into a list of objects.
For manually added collections, return a list of values.
You will need to override this in a child Renderer object
if you want to mangle the data from your web form, before
it reaches your database model. For example, if your render()
method displays a select box filled with items you got from a
CSV file or another source, you will need to decide what to do
with those values when it's time to save them to the database
-- or is this field going to determine the hashing algorithm
for your password ?.
This function should return the value that is going to be
assigned to the model *and* used in the place of the model
value if there was an error with the form.
.. note::
Note that this function will be called *twice*, once when
the fieldset is `.validate()`'d -- with it's value only tested,
and a second time when the fieldset is `.sync()`'d -- and it's
value assigned to the model. Also note that deserialize() can
also raise a ValidationError() exception if it finds some
errors converting it's values.
If calling this function twice poses a problem to your logic, for
example, if you have heavy database queries, or temporary objects
created in this function, consider using the ``deserialize_once``
decorator, provided using:
.. sourcecode:: py
from formalchemy.fields import deserialize_once
@deserialize_once
def deserialize(self):
... my stuff ...
return calculated_only_once
Finally, you should only have to override this if you are using custom
(e.g., Composite) types.
"""
if self.field.is_collection:
return [self._deserialize(subdata) for subdata in self._serialized_value()]
return self._deserialize(self._serialized_value())
def _deserialize(self, data):
if isinstance(self.field.type, fatypes.Boolean):
if data is not None:
if data.lower() in ['1', 't', 'true', 'yes']: return True
if data.lower() in ['0', 'f', 'false', 'no']: return False
if data is None or data == self.field._null_option[1]:
return None
if isinstance(self.field.type, fatypes.Interval):
return datetime.timedelta(validators.float_(data, self))
if isinstance(self.field.type, fatypes.Integer):
return validators.integer(data, self)
if isinstance(self.field.type, fatypes.Float):
return validators.float_(data, self)
if isinstance(self.field.type, fatypes.Numeric):
if self.field.type.asdecimal:
return validators.decimal_(data, self)
else:
return validators.float_(data, self)
def _date(data):
if data == 'YYYY-MM-DD' or data == '-MM-DD' or not data.strip():
return None
try:
return datetime.date(*[int(st) for st in data.split('-')])
except:
raise validators.ValidationError('Invalid date')
def _time(data):
if data == 'HH:MM:SS' or not data.strip():
return None
try:
return datetime.time(*[int(st) for st in data.split(':')])
except:
raise validators.ValidationError('Invalid time')
if isinstance(self.field.type, fatypes.Date):
return _date(data)
if isinstance(self.field.type, fatypes.Time):
return _time(data)
if isinstance(self.field.type, fatypes.DateTime):
data_date, data_time = data.split(' ')
dt, tm = _date(data_date), _time(data_time)
if dt is None and tm is None:
return None
elif dt is None or tm is None:
raise validators.ValidationError('Incomplete datetime')
return datetime.datetime(dt.year, dt.month, dt.day, tm.hour, tm.minute, tm.second)
return data
def stringify_value(self, v, as_html=False):
if as_html:
return _htmlify(v, null_value=self.field._null_option[1])
return _stringify(v, null_value=self.field._null_option[1])
def __repr__(self):
return '<%s for %r>' % (self.__class__.__name__, self.field)
class EscapingReadonlyRenderer(FieldRenderer):
"""
In readonly mode, html-escapes the output of the default renderer
for this field type. (Escaping is not performed by default because
it is sometimes useful to have the renderer include raw html in its
output. The FormAlchemy admin app extension for Pylons uses this,
for instance.)
"""
def __init__(self, field):
FieldRenderer.__init__(self, field)
self._renderer = field._get_renderer()(field)
def render(self, **kwargs):
return self._renderer.render(**kwargs)
def render_readonly(self, **kwargs):
return h.HTML(self._renderer.render_readonly(**kwargs))
class TextFieldRenderer(FieldRenderer):
"""render a field as a text field"""
@property
def length(self):
return self.field.type.length
def render(self, **kwargs):
return h.text_field(self.name, value=self.value, maxlength=self.length, **kwargs)
class IntegerFieldRenderer(FieldRenderer):
"""render an integer as a text field"""
def render(self, **kwargs):
return h.text_field(self.name, value=self.value, **kwargs)
class FloatFieldRenderer(FieldRenderer):
"""render a float as a text field"""
def render(self, **kwargs):
return h.text_field(self.name, value=self.value, **kwargs)
class IntervalFieldRenderer(FloatFieldRenderer):
"""render an interval as a text field"""
def _deserialize(self, data):
value = FloatFieldRenderer._deserialize(self, data)
if isinstance(value, (float, int)):
return datetime.timedelta(value)
return value
class PasswordFieldRenderer(TextFieldRenderer):
"""Render a password field"""
def render(self, **kwargs):
return h.password_field(self.name, value=self.value, maxlength=self.length, **kwargs)
def render_readonly(self):
return '*'*6
class TextAreaFieldRenderer(FieldRenderer):
"""render a field as a textarea"""
def render(self, **kwargs):
if isinstance(kwargs.get('size'), tuple):
kwargs['size'] = 'x'.join([str(i) for i in kwargs['size']])
return h.text_area(self.name, content=self.value, **kwargs)
class HiddenFieldRenderer(FieldRenderer):
"""render a field as an hidden field"""
def render(self, **kwargs):
return h.hidden_field(self.name, value=self.value, **kwargs)
def render_readonly(self):
return ''
class CheckBoxFieldRenderer(FieldRenderer):
"""render a boolean value as checkbox field"""
def render(self, **kwargs):
return h.check_box(self.name, True, checked=_simple_eval(self.value or ''), **kwargs)
def _serialized_value(self):
if self.name not in self.params:
return None
return FieldRenderer._serialized_value(self)
def deserialize(self):
if self._serialized_value() is None:
return False
return FieldRenderer.deserialize(self)
class FileFieldRenderer(FieldRenderer):
"""render a file input field"""
remove_label = _('Remove')
def __init__(self, *args, **kwargs):
FieldRenderer.__init__(self, *args, **kwargs)
self._data = None # caches FieldStorage data
self._filename = None
def render(self, **kwargs):
if self.field.model_value:
checkbox_name = '%s--remove' % self.name
return h.literal('%s %s %s') % (
h.file_field(self.name, **kwargs),
h.check_box(checkbox_name),
h.label(self.remove_label, for_=checkbox_name))
else:
return h.file_field(self.name, **kwargs)
def get_size(self):
value = self.raw_value
if value is None:
return 0
return len(value)
def readable_size(self):
length = self.get_size()
if length == 0:
return '0 KB'
if length <= 1024:
return '1 KB'
if length > 1048576:
return '%0.02f MB' % (length / 1048576.0)
return '%0.02f KB' % (length / 1024.0)
def render_readonly(self, **kwargs):
"""
render only the binary size in a human readable format but you can
override it to whatever you want
"""
return self.readable_size()
def deserialize(self):
data = FieldRenderer.deserialize(self)
if isinstance(data, cgi.FieldStorage):
if data.filename:
# FieldStorage can only be read once so we need to cache the
# value since FA call deserialize during validation and
# synchronisation
if self._data is None:
self._filename = data.filename
self._data = data.file.read()
data = self._data
else:
data = None
checkbox_name = '%s--remove' % self.name
if not data and not self.params.has_key(checkbox_name):
data = getattr(self.field.model, self.field.name)
return data is not None and data or ''
# for when and/or is not safe b/c first might eval to false
def _ternary(condition, first, second):
if condition:
return first()
return second()
class DateFieldRenderer(FieldRenderer):
"""Render a date field"""
@property
def format(self):
return config.date_format
@property
def edit_format(self):
return config.date_edit_format
def render_readonly(self, **kwargs):
value = self.raw_value
return value and value.strftime(self.format) or ''
def _render(self, **kwargs):
data = self.params
F_ = self.get_translator(**kwargs)
month_options = [(F_('Month'), 'MM')] + [(unicode(F_('month_%02i' % i), 'utf-8'), str(i)) for i in xrange(1, 13)]
day_options = [(F_('Day'), 'DD')] + [(i, str(i)) for i in xrange(1, 32)]
mm_name = self.name + '__month'
dd_name = self.name + '__day'
yyyy_name = self.name + '__year'
mm = _ternary((data is not None and mm_name in data), lambda: data[mm_name][-1], lambda: str(self.field.model_value and self.field.model_value.month))
dd = _ternary((data is not None and dd_name in data), lambda: data[dd_name][-1], lambda: str(self.field.model_value and self.field.model_value.day))
# could be blank so don't use and/or construct
if data is not None and yyyy_name in data:
yyyy = data[yyyy_name]
else:
yyyy = str(self.field.model_value and self.field.model_value.year or 'YYYY')
selects = dict(
m=h.select(mm_name, [mm], month_options, **kwargs),
d=h.select(dd_name, [dd], day_options, **kwargs),
y=h.text_field(yyyy_name, value=yyyy, maxlength=4, size=4, **kwargs))
value = [selects.get(l) for l in self.edit_format.split('-')]
return h.literal('\n').join(value)
def render(self, **kwargs):
return h.content_tag('span', self._render(**kwargs), id=self.name)
def _serialized_value(self):
return '-'.join([self.params.getone(self.name + '__' + subfield) for subfield in ['year', 'month', 'day']])
class TimeFieldRenderer(FieldRenderer):
"""Render a time field"""
format = '%H:%M:%S'
def is_time_type(self):
return isinstance(self.field.model_value, (datetime.datetime, datetime.date, datetime.time))
def render_readonly(self, **kwargs):
value = self.raw_value
return isinstance(value, datetime.time) and value.strftime(self.format) or ''
def _render(self, **kwargs):
data = self.params
hour_options = ['HH'] + [str(i) for i in xrange(24)]
minute_options = ['MM' ] + [str(i) for i in xrange(60)]
second_options = ['SS'] + [str(i) for i in xrange(60)]
hh_name = self.name + '__hour'
mm_name = self.name + '__minute'
ss_name = self.name + '__second'
is_time_type = isinstance(self.field.model_value, (datetime.datetime, datetime.date, datetime.time))
hh = _ternary((data is not None and hh_name in data),
lambda: data[hh_name][-1],
lambda: str(is_time_type and self.field.model_value.hour))
mm = _ternary((data is not None and mm_name in data),
lambda: data[mm_name][-1],
lambda: str(is_time_type and self.field.model_value.minute))
ss = _ternary((data is not None and ss_name in data),
lambda: data[ss_name][-1],
lambda: str(is_time_type and self.field.model_value.second))
return h.literal(':').join([
h.select(hh_name, [hh], hour_options, **kwargs),
h.select(mm_name, [mm], minute_options, **kwargs),
h.select(ss_name, [ss], second_options, **kwargs)])
def render(self, **kwargs):
return h.content_tag('span', self._render(**kwargs), id=self.name)
def _serialized_value(self):
return ':'.join([self.params.getone(self.name + '__' + subfield) for subfield in ['hour', 'minute', 'second']])
class DateTimeFieldRenderer(DateFieldRenderer, TimeFieldRenderer):
"""Render a date time field"""
format = '%Y-%m-%d %H:%M:%S'
def render(self, **kwargs):
return h.content_tag('span', DateFieldRenderer._render(self, **kwargs) + h.literal(' ') + TimeFieldRenderer._render(self, **kwargs), id=self.name)
def _serialized_value(self):
return DateFieldRenderer._serialized_value(self) + ' ' + TimeFieldRenderer._serialized_value(self)
def _extract_options(options):
if isinstance(options, dict):
options = options.items()
for choice in options:
# Choice is a list/tuple...
if isinstance(choice, (list, tuple)):
if len(choice) != 2:
raise Exception('Options should consist of two items, a name and a value; found %d items in %r' % (len(choice, choice)))
yield choice
# ... or just a string.
else:
if not isinstance(choice, basestring):
raise Exception('List, tuple, or string value expected as option (got %r)' % choice)
yield (choice, choice)
class RadioSet(FieldRenderer):
"""render a field as radio"""
widget = staticmethod(h.radio_button)
format = '%(field)s%(label)s'
def _serialized_value(self):
if self.name not in self.params:
return None
return FieldRenderer._serialized_value(self)
def _is_checked(self, choice_value, value=NoDefault):
if value is NoDefault:
value = self.value
return value == _stringify(choice_value)
def render(self, options, **kwargs):
value = self.value
self.radios = []
if callable(options):
options = options(self.field.parent)
for i, (choice_name, choice_value) in enumerate(_extract_options(options)):
choice_id = '%s_%i' % (self.name, i)
radio = self.widget(self.name, choice_value, id=choice_id,
checked=self._is_checked(choice_value, value),
**kwargs)
label = h.label(choice_name, for_=choice_id)
self.radios.append(h.literal(self.format % dict(field=radio,
label=label)))
return h.tag("br").join(self.radios)
class CheckBoxSet(RadioSet):
widget = staticmethod(h.check_box)
def _serialized_value(self):
if self.name not in self.params:
return []
return FieldRenderer._serialized_value(self)
def _is_checked(self, choice_value, value=NoDefault):
if value is NoDefault:
value = self.value
return _stringify(choice_value) in value
class SelectFieldRenderer(FieldRenderer):
"""render a field as select"""
def _serialized_value(self):
if self.name not in self.params:
if self.field.is_collection:
return []
return None
return FieldRenderer._serialized_value(self)
def render(self, options, **kwargs):
if callable(options):
L = _normalized_options(options(self.field.parent))
if not self.field.is_required() and not self.field.is_collection:
L.insert(0, self.field._null_option)
else:
L = list(options)
if len(L) > 0:
if len(L[0]) == 2:
L = [(k, self.stringify_value(v)) for k, v in L]
else:
L = [_stringify(k) for k in L]
return h.select(self.name, self.value, L, **kwargs)
def render_readonly(self, options=None, **kwargs):
"""render a string representation of the field value.
Try to retrieve a value from `options`
"""
if not options or self.field.is_scalar_relation:
return FieldRenderer.render_readonly(self)
value = self.raw_value
if value is None:
return ''
if callable(options):
L = _normalized_options(options(self.field.parent))
else:
L = list(options)
if len(L) > 0:
if len(L[0]) == 2:
L = [(v, k) for k, v in L]
else:
L = [(k, _stringify(k)) for k in L]
D = dict(L)
if isinstance(value, list):
return u', '.join([_stringify(D.get(item, item)) for item in value])
return _stringify(D.get(value, value))
################## FIELDS STUFF ####################
def _pk_one_column(instance, column):
try:
attr = getattr(instance, column.key)
except AttributeError:
# FIXME: this is not clean but the only way i've found to retrieve the
# real attribute name of the primary key.
# This is needed when you use something like:
# id = Column('UGLY_NAMED_ID', primary_key=True)
# It's a *really* needed feature
cls = instance.__class__
for k in instance._sa_class_manager.keys():
props = getattr(cls, k).property
if hasattr(props, 'columns'):
if props.columns[0] is column:
attr = getattr(instance, k)
break
return attr
def _pk(instance):
# Return the value of this instance's primary key, suitable for passing to Query.get().
# Will be a tuple if PK is multicolumn.
try:
columns = class_mapper(type(instance)).primary_key
except InvalidRequestError:
# try to get pk from model attribute
if hasattr(instance, '_pk'):
return getattr(instance, '_pk', None) or None
return None
if len(columns) == 1:
return _pk_one_column(instance, columns[0])
return tuple([_pk_one_column(instance, column) for column in columns])
# see http://code.activestate.com/recipes/364469/ for explanation.
# 2.6 provides ast.literal_eval, but requiring 2.6 is a bit of a stretch for now.
import compiler
class _SafeEval(object):
def visit(self, node,**kw):
cls = node.__class__
meth = getattr(self,'visit'+cls.__name__,self.default)
return meth(node, **kw)
def default(self, node, **kw):
for child in node.getChildNodes():
return self.visit(child, **kw)
visitExpression = default
def visitName(self, node, **kw):
if node.name in ['True', 'False', 'None']:
return eval(node.name)
def visitConst(self, node, **kw):
return node.value
def visitTuple(self,node, **kw):
return tuple(self.visit(i) for i in node.nodes)
def visitList(self,node, **kw):
return [self.visit(i) for i in node.nodes]
def _simple_eval(source):
"""like 2.6's ast.literal_eval, but only does constants, lists, and tuples, for serialized pk eval"""
if source == '':
return None
walker = _SafeEval()
ast = compiler.parse(source, 'eval')
return walker.visit(ast)
def _query_options(L):
"""
Return a list of tuples of `(item description, item pk)`
for each item in the iterable L, where `item description`
is the result of str(item) and `item pk` is the item's primary key.
"""
return [(_stringify(item), _pk(item)) for item in L]
def _normalized_options(options):
"""
If `options` is an SA query or an iterable of SA instances, it will be
turned into a list of `(item description, item value)` pairs. Otherwise, a
copy of the original options will be returned with no further validation.
"""
if isinstance(options, Query):
options = options.all()
if callable(options):
return options
i = iter(options)
try:
first = i.next()
except StopIteration:
return []
try:
class_mapper(type(first))
except:
return list(options)
return _query_options(options)
def _foreign_keys(property):
# 0.4/0.5 compatibility fn
try:
return property.foreign_keys
except AttributeError:
return [r for l, r in property.synchronize_pairs]
def _model_equal(a, b):
if not isinstance(a, type):
a = type(a)
if not isinstance(b, type):
b = type(b)
return a is b
class AbstractField(object):
"""
Contains the information necessary to render (and modify the rendering of)
a form field
Methods taking an `options` parameter will accept several ways of
specifying those options:
- an iterable of SQLAlchemy objects; `str()` of each object will be the description, and the primary key the value
- a SQLAlchemy query; the query will be executed with `all()` and the objects returned evaluated as above
- an iterable of (description, value) pairs
- a dictionary of {description: value} pairs
Options can be "chained" indefinitely because each modification returns a new
:mod:`Field <formalchemy.fields>` instance, so you can write::
>>> from formalchemy.tests import FieldSet, User
>>> fs = FieldSet(User)
>>> fs.append(Field('foo').dropdown(options=[('one', 1), ('two', 2)]).radio())
or::
>>> fs.configure(options=[fs.name.label('Username').readonly()])
"""
_null_option = (u'None', u'')
def __init__(self, parent):
# the FieldSet (or any ModelRenderer) owning this instance
self.parent = parent
if 0:
import forms
isinstance(self.parent, forms.FieldSet)
# Renderer for this Field. this will
# be autoguessed, unless the user forces it with .dropdown,
# .checkbox, etc.
self._renderer = None
# other render options, such as size, multiple, etc.
self.render_opts = {}
# validator functions added with .validate()
self.validators = []
# errors found by _validate() (which runs implicit and
# explicit validators)
self.errors = []
self._readonly = False
# label to use for the rendered field. autoguessed if not specified by .label()
self.label_text = None
# optional attributes to pass to renderers
self.html_options = {}
# True iff this Field is a primary key
self.is_pk = False
# True iff this Field is a raw foreign key
self.is_raw_foreign_key = False
# Field metadata, for customization
self.metadata = {}
return False
def __deepcopy__(self, memo):
wrapper = copy(self)
wrapper.render_opts = dict(self.render_opts)
wrapper.validators = list(self.validators)
wrapper.errors = list(self.errors)
try:
wrapper._renderer = copy(self._renderer)
except TypeError: # 2.4 support
# it's a lambda, safe to just use same referende
pass
if hasattr(wrapper._renderer, 'field'):
wrapper._renderer.field = wrapper
return wrapper
@property
def requires_label(self):
return not isinstance(self.renderer, HiddenFieldRenderer)
def query(self, *args, **kwargs):
"""Perform a query in the parent's session"""
if not self.parent.session:
raise Exception("No session found. Either bind a session explicitly, or specify relation options manually so FormAlchemy doesn't try to autoload them.")
return self.parent.session.query(*args, **kwargs)
def _validate(self):
if self.is_readonly():
return True
self.errors = []
try:
# Call renderer.deserialize(), because the deserializer can
# also raise a ValidationError
value = self._deserialize()
except validators.ValidationError, e:
self.errors.append(e.message)
return False
L = list(self.validators)
if self.is_required() and validators.required not in L:
L.append(validators.required)
for validator in L:
if (not (hasattr(validator, 'accepts_none') and validator.accepts_none)) and value is None:
continue
try:
validator(value, self)
except validators.ValidationError, e:
self.errors.append(e.message)
except TypeError:
warnings.warn(DeprecationWarning('Please provide a field argument to your %r validator. Your validator will break in FA 1.5' % validator))
try:
validator(value)
except validators.ValidationError, e:
self.errors.append(e.message)
return not self.errors
def is_required(self):
"""True iff this Field must be given a non-empty value"""
return validators.required in self.validators
def is_readonly(self):
"""True iff this Field is in readonly mode"""
return self._readonly
@property
def model(self):
return self.parent.model
def _modified(self, **kwattrs):
# return a copy of self, with the given attributes modified
copied = deepcopy(self)
for attr, value in kwattrs.iteritems():
setattr(copied, attr, value)
return copied
def set(self, **kwattrs):
"""
Update field attributes in place. Allowed attributes are: validate,
renderer, required, readonly, nul_as, label, multiple, options, size,
instructions, metadata::
>>> field = Field('myfield')
>>> field.set(label='My field', renderer=SelectFieldRenderer,
... options=[('Value', 1)])
AttributeField(myfield)
>>> field.label_text
'My field'
>>> field.renderer
<SelectFieldRenderer for AttributeField(myfield)>
"""
attrs = kwattrs.keys()
mapping = dict(renderer='_renderer',
readonly='_readonly',
null_as='_null_option',
label='label_text')
for attr in attrs:
value = kwattrs.pop(attr)
if attr == 'validate':
self.validators.append(value)
elif attr == 'metadata':
self.metadata.update(value)
elif attr == 'instructions':
self.metadata['instructions'] = value
elif attr == 'required':
if value:
if validators.required not in self.validators:
self.validators.append(validators.required)
else:
if validators.required in self.validators:
self.validators.remove(validators.required)
elif attr in mapping:
attr = mapping.get(attr)
setattr(self, attr, value)
elif attr in ('multiple', 'options', 'size'):
if attr == 'options' and value is not None:
value = _normalized_options(value)
self.render_opts[attr] = value
else:
raise ValueError('Invalid argument %s' % attr)
return self
def with_null_as(self, option):
"""Render null as the given option tuple of text, value."""
return self._modified(_null_option=option)
def with_renderer(self, renderer):
"""
Return a copy of this Field, with a different renderer.
Used for one-off renderer changes; if you want to change the
renderer for all instances of a Field type, modify
FieldSet.default_renderers instead.
"""
return self._modified(_renderer=renderer)
def bind(self, parent):
"""Return a copy of this Field, bound to a different parent"""
return self._modified(parent=parent)
def with_metadata(self, **attrs):
"""Attach some metadata attributes to the Field, to be used by
conditions in templates.
Example usage:
>>> test = Field('test')
>>> field = test.with_metadata(instructions='use this widget this way')
...
And further in your templates you can verify:
>>> 'instructions' in field.metadata
True
and display the content in a <span> or something.
"""
new_attr = self.metadata.copy()
new_attr.update(attrs)
return self._modified(metadata=new_attr)
def validate(self, validator):
"""
Add the `validator` function to the list of validation
routines to run when the `FieldSet`'s `validate` method is
run. Validator functions take one parameter: the value to
validate. This value will have already been turned into the
appropriate data type for the given `Field` (string, int, float,
etc.). It should raise `ValidationError` if validation
fails with a message explaining the cause of failure.
"""
field = deepcopy(self)
field.validators.append(validator)
return field
def required(self):
"""
Convenience method for `validate(validators.required)`. By
default, NOT NULL columns are required. You can only add
required-ness, not remove it.
"""
return self.validate(validators.required)
def with_html(self, **html_options):
"""
Give some HTML options to renderer.
Trailing underscore (_) characters will be stripped. For example,
you might want to add a `class` attribute to your checkbox. You
would need to specify `.options(class_='someclass')`.
For WebHelpers-aware people: those parameters will be passed to
the `text_area()`, `password()`, `text()`, etc.. webhelpers.
NOTE: Those options can override generated attributes and can mess
the `sync` calls, or `label`-tag associations (if you change
`name`, or `id` for example). Use with caution.
"""
new_opts = copy(self.html_options)
for k, v in html_options.iteritems():
new_opts[k.rstrip('_')] = v
return self._modified(html_options=new_opts)
def label(self, text):
"""
Change the label associated with this field. By default, the field name
is used, modified for readability (e.g., 'user_name' -> 'User name').
"""
return self._modified(label_text=text)
def readonly(self, value=True):
"""Render the field readonly."""
return self._modified(_readonly=True)
def hidden(self):
"""Render the field hidden. (Value only, no label.)"""
return self._modified(_renderer=HiddenFieldRenderer, render_opts={})
def password(self):
"""Render the field as a password input, hiding its value."""
field = deepcopy(self)
field._renderer = lambda f: f.parent.default_renderers['password']
field.render_opts = {}
return field
def textarea(self, size=None):
"""
Render the field as a textarea. Size must be a string
(`"25x10"`) or tuple (`25, 10`).
"""
field = deepcopy(self)
field._renderer = lambda f: f.parent.default_renderers['textarea']
if size:
field.render_opts = {'size': size}
return field
def radio(self, options=None):
"""Render the field as a set of radio buttons."""
field = deepcopy(self)
field._renderer = lambda f: f.parent.default_renderers['radio']
if options is None:
options = self.render_opts.get('options')
else:
options = _normalized_options(options)
field.render_opts = {'options': options}
return field
def checkbox(self, options=None):
"""Render the field as a set of checkboxes."""
field = deepcopy(self)
field._renderer = lambda f: f.parent.default_renderers['checkbox']
if options is None:
options = self.render_opts.get('options')
else:
options = _normalized_options(options)
field.render_opts = {'options': options}
return field
def dropdown(self, options=None, multiple=False, size=5):
"""
Render the field as an HTML select field.
(With the `multiple` option this is not really a 'dropdown'.)
"""
field = deepcopy(self)
field._renderer = lambda f: f.parent.default_renderers['dropdown']
if options is None:
options = self.render_opts.get('options')
else:
options = _normalized_options(options)
field.render_opts = {'multiple': multiple, 'options': options}
if multiple:
field.render_opts['size'] = size
return field
def reset(self):
"""
Return the field with all configuration changes reverted.
"""
return deepcopy(self.parent._fields[self.name])
def _get_renderer(self):
for t in self.parent.default_renderers:
if not isinstance(t, basestring) and type(self.type) is t:
return self.parent.default_renderers[t]
for t in self.parent.default_renderers:
if not isinstance(t, basestring) and isinstance(self.type, t):
return self.parent.default_renderers[t]
raise TypeError(
'No renderer found for field %s. '
'Type %s as no default renderer' % (self.name, self.type))
@property
def renderer(self):
if self._renderer is None:
self._renderer = self._get_renderer()
try:
self._renderer = self._renderer(self)
except TypeError:
pass
if not isinstance(self._renderer, FieldRenderer):
# must be a Renderer class. instantiate.
self._renderer = self._renderer(self)
return self._renderer
def _get_render_opts(self):
"""
Calculate the final options dict to be sent to renderers.
"""
# Use options from internally set render_opts
opts = dict(self.render_opts)
# Override with user-specified options (with .with_html())
opts.update(self.html_options)
return opts
def render(self):
"""
Render this Field as HTML.
"""
if self.is_readonly():
return self.render_readonly()
opts = self._get_render_opts()
if (isinstance(self.type, fatypes.Boolean)
and not opts.get('options')
and self.renderer.__class__ in [self.parent.default_renderers['dropdown'], self.parent.default_renderers['radio']]):
opts['options'] = [('Yes', True), ('No', False)]
return self.renderer.render(**opts)
def render_readonly(self):
"""
Render this Field as HTML for read only mode.
"""
return self.renderer.render_readonly(**self._get_render_opts())
def _pkify(self, value):
"""return the PK for value, if applicable"""
return value
@property
def value(self):
"""
The value of this Field: use the corresponding value in the bound `data`,
if any; otherwise, use the value in the bound `model`. For SQLAlchemy models,
if there is still no value, use the default defined on the corresponding `Column`.
For SQLAlchemy collections,
a list of the primary key values of the items in the collection is returned.
Invalid form data will cause an error to be raised. Controllers should thus validate first.
Renderers should thus never access .value; use .model_value instead.
"""
# TODO add ._validated flag to save users from themselves?
if not self.is_readonly() and self.parent.data is not None:
v = self._deserialize()
if v is not None:
return self._pkify(v)
return self.model_value
@property
def model_value(self):
"""
raw value from model, transformed if necessary for use as a form input value.
"""
raise NotImplementedError()
def raw_value(self):
"""
raw value from model. different from `.model_value` in SQLAlchemy fields, because for reference types,
`.model_value` will return the foreign key ID. This will return the actual object
referenced instead.
"""
raise NotImplementedError()
def _deserialize(self):
return self.renderer.deserialize()
class Field(AbstractField):
"""
A manually-added form field
"""
def __init__(self, name=None, type=fatypes.String, value=None, **kwattrs):
"""
Create a new Field object.
- `name`:
field name
- `type=types.String`:
data type, from formalchemy.types (Integer, Float, String,
LargeBinary, Boolean, Date, DateTime, Time) or a custom type
- `value=None`:
default value. If value is a callable, it will be passed the current
bound model instance when the value is read. This allows creating a
Field whose value depends on the model once, then binding different
instances to it later.
* `name`: field name
* `type`: data type, from formalchemy.types (Boolean, Integer, String, etc.),
or a custom type for which you have added a renderer.
* `value`: default value. If value is a callable, it will be passed
the current bound model instance when the value is read. This allows
creating a Field whose value depends on the model once, then
binding different instances to it later.
"""
AbstractField.__init__(self, None) # parent will be set by ModelRenderer.add
self.type = type()
self.name = self.key = name
self._value = value
self.is_relation = False
self.is_scalar_relation = False
self.set(**kwattrs)
def set(self, **kwattrs):
if 'value' in kwattrs:
self._value = kwattrs.pop('value')
return AbstractField.set(self, **kwattrs)
@property
def model_value(self):
return self.raw_value
@property
def is_collection(self):
if isinstance(self.type, (fatypes.List, fatypes.Set)):
return True
return self.render_opts.get('multiple', False) or isinstance(self.renderer, self.parent.default_renderers['checkbox'])
@property
def raw_value(self):
try:
# this is NOT the same as getattr -- getattr will return the class's
# value for the attribute name, which for a manually added Field will
# be the Field object. So force looking in the instance __dict__ only.
return self.model.__dict__[self.name]
except (KeyError, AttributeError):
pass
if callable(self._value):
return self._value(self.model)
return self._value
def sync(self):
"""Set the attribute's value in `model` to the value given in `data`"""
if not self.is_readonly():
self._value = self._deserialize()
def __repr__(self):
return 'AttributeField(%s)' % self.name
def __eq__(self, other):
# we override eq so that when we configure with options=[...], we can match the renders in options
# with the ones that were generated at FieldSet creation time
try:
return self.name == other.name and _model_equal(self.model, other.model)
except (AttributeError, ValueError):
return False
def __hash__(self):
return hash(self.name)
class AttributeField(AbstractField):
"""
Field corresponding to an SQLAlchemy attribute.
"""
def __init__(self, instrumented_attribute, parent):
"""
>>> from formalchemy.tests import FieldSet, Order
>>> fs = FieldSet(Order)
>>> print fs.user.key
user
>>> print fs.user.name
user_id
"""
AbstractField.__init__(self, parent)
# we rip out just the parts we care about from InstrumentedAttribute.
# impl is the AttributeImpl. So far all we care about there is ".key,"
# which is the name of the attribute in the mapped class.
self._impl = instrumented_attribute.impl
# property is the PropertyLoader which handles all the interesting stuff.
# mapper, columns, and foreign keys are all located there.
self._property = instrumented_attribute.property
# True iff this is a multi-valued (one-to-many or many-to-many) SA relation
self.is_collection = isinstance(self._impl, CollectionAttributeImpl)
# True iff this is the 'one' end of a one-to-many relation
self.is_scalar_relation = isinstance(self._impl, ScalarObjectAttributeImpl)
# True iff this field represents a mapped SA relation
self.is_relation = self.is_scalar_relation or self.is_collection
self.is_composite = isinstance(self._property, CompositeProperty)
_columns = self._columns
self.is_pk = bool([c for c in self._columns if c.primary_key])
self.is_raw_foreign_key = bool(isinstance(self._property, ColumnProperty) and _foreign_keys(self._property.columns[0]))
self.is_composite_foreign_key = len(_columns) > 1 and not [c for c in _columns if not _foreign_keys(c)]
if self.is_composite:
# this is a little confusing -- we need to return an _instance_ of
# the correct type, which for composite values will be the value
# itself. SA should probably have called .type something
# different, or just not instantiated them...
self.type = self._property.composite_class.__new__(self._property.composite_class)
elif len(_columns) > 1:
self.type = None # may have to be more accurate here
else:
self.type = _columns[0].type
self.key = self._impl.key
self._column_name = '_'.join([c.name for c in _columns])
# The name of the form input. usually the same as the key, except for
# single-valued SA relation properties. For example, for order.user,
# name will be 'user_id' (assuming that is indeed the name of the foreign
# key to users), but for user.orders, name will be 'orders'.
if self.is_collection or self.is_composite or not hasattr(self.model, self._column_name):
self.name = self.key
else:
self.name = self._column_name
# smarter default "required" value
if not self.is_collection and not self.is_readonly() and [c for c in _columns if not c.nullable]:
self.validators.append(validators.required)
def is_readonly(self):
from sqlalchemy.sql.expression import _Label
return AbstractField.is_readonly(self) or isinstance(self._columns[0], _Label)
@property
def _columns(self):
if self.is_scalar_relation:
# If the attribute is a foreign key, return the Column that this
# attribute is mapped from -- e.g., .user -> .user_id.
return _foreign_keys(self._property)
elif isinstance(self._impl, ScalarAttributeImpl) or self._impl.__class__.__name__ in ('ProxyImpl', '_ProxyImpl'): # 0.4 compatibility: ProxyImpl is a one-off class for each synonym, can't import it
# normal property, mapped to a single column from the main table
return self._property.columns
else:
# collection -- use the mapped class's PK
assert self.is_collection, self._impl.__class__
return self._property.mapper.primary_key
def relation_type(self):
"""
The type of object in the collection (e.g., `User`).
Calling this is only valid when `is_relation` is True.
"""
return self._property.mapper.class_
def _pkify(self, value):
"""return the PK for value, if applicable"""
if value is None:
return None
if self.is_collection:
return [_pk(item) for item in value]
if self.is_relation:
return _pk(value)
return value
@property
def model_value(self):
return self._pkify(self.raw_value)
@property
def raw_value(self):
if self.is_scalar_relation:
v = getattr(self.model, self.key)
else:
try:
v = getattr(self.model, self.name)
except AttributeError:
v = getattr(self.model, self.key)
if v is not None:
return v
_columns = self._columns
if len(_columns) == 1 and _columns[0].default:
try:
from sqlalchemy.sql.expression import Function
except ImportError:
from sqlalchemy.sql.expression import _Function as Function
arg = _columns[0].default.arg
if callable(arg) or isinstance(arg, Function):
# callables often depend on the current time, e.g. datetime.now or the equivalent SQL function.
# these are meant to be the value *at insertion time*, so it's not strictly correct to
# generate a value at form-edit time.
pass
else:
return arg
return None
def sync(self):
"""Set the attribute's value in `model` to the value given in `data`"""
if not self.is_readonly():
setattr(self.model, self.name, self._deserialize())
def __eq__(self, other):
# we override eq so that when we configure with options=[...], we can match the renders in options
# with the ones that were generated at FieldSet creation time
try:
return self._impl is other._impl and _model_equal(self.model, other.model)
except (AttributeError, ValueError):
return False
def __hash__(self):
return hash(self._impl)
def __repr__(self):
return 'AttributeField(%s)' % self.key
def render(self):
if self.is_readonly():
return self.render_readonly()
if self.is_relation and self.render_opts.get('options') is None:
if self.is_required() or self.is_collection:
self.render_opts['options'] = []
else:
self.render_opts['options'] = [self._null_option]
# todo 2.0 this does not handle primaryjoin (/secondaryjoin) alternate join conditions
fk_cls = self.relation_type()
order_by = self._property.order_by or list(class_mapper(fk_cls).primary_key)
if order_by and not isinstance(order_by, list):
order_by = [order_by]
q = self.query(fk_cls).order_by(*order_by)
self.render_opts['options'] += _query_options(q)
logger.debug('options for %s are %s' % (self.name, self.render_opts['options']))
if self.is_collection and isinstance(self.renderer, self.parent.default_renderers['dropdown']):
self.render_opts['multiple'] = True
if 'size' not in self.render_opts:
self.render_opts['size'] = 5
return AbstractField.render(self)
def _get_renderer(self):
if self.is_relation:
return self.parent.default_renderers['dropdown']
return AbstractField._get_renderer(self)
def _deserialize(self):
# for multicolumn keys, we turn the string into python via _simple_eval; otherwise,
# the key is just the raw deserialized value (which is already an int, etc., as necessary)
if len(self._columns) > 1:
python_pk = _simple_eval
else:
python_pk = lambda st: st
if self.is_collection:
return [self.query(self.relation_type()).get(python_pk(pk)) for pk in self.renderer.deserialize()]
if self.is_composite_foreign_key:
return self.query(self.relation_type()).get(python_pk(self.renderer.deserialize()))
return self.renderer.deserialize()
| Python |
# -*- coding: utf-8 -*-
#used to simulate the library module used in doctests
| Python |
# -*- coding: utf-8 -*-
import os
import glob
import logging
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
from BeautifulSoup import BeautifulSoup # required for html prettification
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
logging.getLogger('sqlalchemy').setLevel(logging.ERROR)
from formalchemy.fields import Field, SelectFieldRenderer, FieldRenderer, TextFieldRenderer, EscapingReadonlyRenderer
import formalchemy.fatypes as types
def ls(*args):
dirname = os.path.dirname(__file__)
args = list(args)
args.append('*')
files = glob.glob(os.path.join(dirname, *args))
files.sort()
for f in files:
if os.path.isdir(f):
print 'D %s' % os.path.basename(f)
else:
print '- %s' % os.path.basename(f)
def cat(*args):
filename = os.path.join(os.path.dirname(__file__), *args)
print open(filename).read()
engine = create_engine('sqlite://')
Session = scoped_session(sessionmaker(autoflush=False, bind=engine))
Base = declarative_base(engine, mapper=Session.mapper)
class One(Base):
__tablename__ = 'ones'
id = Column(Integer, primary_key=True)
class Two(Base):
__tablename__ = 'twos'
id = Column(Integer, primary_key=True)
foo = Column(Integer, default='133', nullable=True)
class TwoInterval(Base):
__tablename__ = 'two_interval'
id = Column(Integer, primary_key=True)
foo = Column(Interval, nullable=False)
class TwoFloat(Base):
__tablename__ = 'two_floats'
id = Column(Integer, primary_key=True)
foo = Column(Float, nullable=False)
from decimal import Decimal
class TwoNumeric(Base):
__tablename__ = 'two_numerics'
id = Column(Integer, primary_key=True)
foo = Column(Numeric, nullable=True)
class Three(Base):
__tablename__ = 'threes'
id = Column(Integer, primary_key=True)
foo = Column(Text, nullable=True)
bar = Column(Text, nullable=True)
class CheckBox(Base):
__tablename__ = 'checkboxes'
id = Column(Integer, primary_key=True)
field = Column(Boolean, nullable=False)
class PrimaryKeys(Base):
__tablename__ = 'primary_keys'
id = Column(Integer, primary_key=True)
id2 = Column(String(10), primary_key=True)
field = Column(String(10), nullable=False)
class Binaries(Base):
__tablename__ = 'binaries'
id = Column(Integer, primary_key=True)
file = Column(LargeBinary, nullable=True)
class ConflictNames(Base):
__tablename__ = 'conflict_names'
id = Column(Integer, primary_key=True)
model = Column(String, nullable=True)
data = Column(String, nullable=True)
session = Column(String, nullable=True)
vertices = Table('vertices', Base.metadata,
Column('id', Integer, primary_key=True),
Column('x1', Integer),
Column('y1', Integer),
Column('x2', Integer),
Column('y2', Integer),
)
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __composite_values__(self):
return [self.x, self.y]
def __eq__(self, other):
return other.x == self.x and other.y == self.y
def __ne__(self, other):
return not self.__eq__(other)
class Vertex(object):
pass
Session.mapper(Vertex, vertices, properties={
'start':composite(Point, vertices.c.x1, vertices.c.y1),
'end':composite(Point, vertices.c.x2, vertices.c.y2)
})
class PointFieldRenderer(FieldRenderer):
def render(self, **kwargs):
from formalchemy import helpers as h
data = self.field.parent.data
x_name = self.name + '-x'
y_name = self.name + '-y'
x_value = (data is not None and x_name in data) and data[x_name] or str(self.field.value and self.field.value.x or '')
y_value = (data is not None and y_name in data) and data[y_name] or str(self.field.value and self.field.value.y or '')
return h.text_field(x_name, value=x_value) + h.text_field(y_name, value=y_value)
def deserialize(self):
data = self.field.parent.data.getone(self.name + '-x'), self.field.parent.data.getone(self.name + '-y')
return Point(*[int(i) for i in data])
# todo? test a CustomBoolean, using a TypeDecorator --
# http://www.sqlalchemy.org/docs/04/types.html#types_custom
# probably need to add _renderer attr and check
# isinstance(getattr(myclass, '_renderer', type(myclass)), Boolean)
# since the custom class shouldn't really inherit from Boolean
properties = Table('properties', Base.metadata,
Column('id', Integer, primary_key=True),
Column('a', Integer))
class Property(Base):
__table__ = properties
foo = column_property(properties.c.a.label('foo'))
# bar = column_property(properties.c.a) # TODO
class Recursive(Base):
__tablename__ = 'recursives'
id = Column(Integer, primary_key=True)
foo = Column(Text, nullable=True)
parent_id = Column(Integer, ForeignKey("recursives.id"))
parent = relation('Recursive', primaryjoin=parent_id==id, uselist=False, remote_side=parent_id)
class Synonym(Base):
__tablename__ = 'synonyms'
id = Column(Integer, primary_key=True)
_foo = Column(Text, nullable=True)
def _set_foo(self, foo):
self._foo = "SOMEFOO " + foo
def _get_foo(self):
return self._foo
foo = synonym('_foo', descriptor=property(_get_foo, _set_foo))
class OTOChild(Base):
__tablename__ = 'one_to_one_child'
id = Column(Integer, primary_key=True)
baz = Column(Text, nullable=False)
def __unicode__(self):
return self.baz
def __repr__(self):
return '<OTOChild %s>' % self.baz
class OTOParent(Base):
__tablename__ = 'one_to_one_parent'
id = Column(Integer, primary_key=True)
oto_child_id = Column(Integer, ForeignKey('one_to_one_child.id'), nullable=False)
child = relation(OTOChild, uselist=False)
class Order(Base):
__tablename__ = 'orders'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
quantity = Column(Integer, nullable=False)
def __unicode__(self):
return 'Quantity: %s' % self.quantity
def __repr__(self):
return '<Order for user %s: %s>' % (self.user_id, self.quantity)
class OptionalOrder(Base): # the user is optional, not the order
__tablename__ = 'optional_orders'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.id'))
quantity = Column(Integer)
user = relation('User')
def __unicode__(self):
return 'Quantity: %s' % self.quantity
def __repr__(self):
return '<OptionalOrder for user %s: %s>' % (self.user_id, self.quantity)
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
email = Column(Unicode(40), unique=True, nullable=False)
password = Column(Unicode(20), nullable=False)
name = Column(Unicode(30))
orders = relation(Order, backref='user', order_by='Order.quantity')
orders_dl = dynamic_loader(Order)
def __unicode__(self):
return self.name
def __repr__(self):
return '<User %s>' % self.name
def __html__(self):
return '<a href="mailto:%s">%s</a>' % (self.email, self.name)
class NaturalOrder(Base):
__tablename__ = 'natural_orders'
id = Column(Integer, primary_key=True)
user_email = Column(String, ForeignKey('natural_users.email'), nullable=False)
quantity = Column(Integer, nullable=False)
def __repr__(self):
return 'Quantity: %s' % self.quantity
class NaturalUser(Base):
__tablename__ = 'natural_users'
email = Column(Unicode(40), primary_key=True)
password = Column(Unicode(20), nullable=False)
name = Column(Unicode(30))
orders = relation(NaturalOrder, backref='user')
def __repr__(self):
return self.name
class Function(Base):
__tablename__ = 'functions'
foo = Column(TIMESTAMP, primary_key=True, default=func.current_timestamp())
# test property order for non-declarative mapper
addresses = Table('email_addresses', Base.metadata,
Column('address_id', Integer, Sequence('address_id_seq', optional=True), primary_key = True),
Column('address', String(40)),
)
users2 = Table('users2', Base.metadata,
Column('user_id', Integer, Sequence('user_id_seq', optional=True), primary_key = True),
Column('address_id', Integer, ForeignKey(addresses.c.address_id)),
Column('name', String(40), nullable=False)
)
class Address(object): pass
class User2(object): pass
mapper(Address, addresses)
mapper(User2, users2, properties={'address': relation(Address)})
class Manual(object):
a = Field()
b = Field(type=types.Integer).dropdown([('one', 1), ('two', 2)], multiple=True)
d = Field().textarea((80, 10))
class OrderUser(Base):
__tablename__ = 'order_users'
user_id = Column(Integer, ForeignKey('users.id'), primary_key=True)
order_id = Column(Integer, ForeignKey('orders.id'), primary_key=True)
user = relation(User)
order = relation(Order)
def __repr__(self):
return 'OrderUser(%s, %s)' % (self.user_id, self.order_id)
class OrderUserTag(Base):
__table__ = Table('order_user_tags', Base.metadata,
Column('id', Integer, primary_key=True),
Column('user_id', Integer, nullable=False),
Column('order_id', Integer, nullable=False),
Column('tag', String, nullable=False),
ForeignKeyConstraint(['user_id', 'order_id'], ['order_users.user_id', 'order_users.order_id']))
order_user = relation(OrderUser)
class Order__User(Base):
__table__ = join(Order.__table__, User.__table__).alias('__orders__users')
class Aliases(Base):
__tablename__ = 'table_with_aliases'
id = Column(Integer, primary_key=True)
text = Column('row_text', Text)
Base.metadata.create_all()
session = Session()
primary1 = PrimaryKeys(id=1, id2='22', field='value1')
primary2 = PrimaryKeys(id=1, id2='33', field='value2')
parent = OTOParent()
parent.child = OTOChild(baz='baz')
bill = User(email='bill@example.com',
password='1234',
name='Bill')
john = User(email='john@example.com',
password='5678',
name='John')
order1 = Order(user=bill, quantity=10)
order2 = Order(user=john, quantity=5)
order3 = Order(user=john, quantity=6)
nbill = NaturalUser(email='nbill@example.com',
password='1234',
name='Natural Bill')
njohn = NaturalUser(email='njohn@example.com',
password='5678',
name='Natural John')
norder1 = NaturalOrder(user=nbill, quantity=10)
norder2 = NaturalOrder(user=njohn, quantity=5)
orderuser1 = OrderUser(user_id=1, order_id=1)
orderuser2 = OrderUser(user_id=1, order_id=2)
conflict_names = ConflictNames(data='data', model='model', session='session')
session.commit()
from formalchemy import config
from formalchemy.forms import FieldSet as DefaultFieldSet
from formalchemy.tables import Grid as DefaultGrid
from formalchemy.fields import Field
from formalchemy import templates
from formalchemy.validators import ValidationError
if templates.HAS_MAKO:
if not isinstance(config.engine, templates.MakoEngine):
raise ValueError('MakoEngine is not the default engine: %s' % config.engine)
else:
raise ImportError('mako is required for testing')
def pretty_html(html):
if isinstance(html, unicode):
html = html.encode('utf-8')
soup = BeautifulSoup(str(html))
return soup.prettify().strip()
class FieldSet(DefaultFieldSet):
def render(self, lang=None):
if self.readonly:
html = pretty_html(DefaultFieldSet.render(self))
for name, engine in templates.engines.items():
if isinstance(engine, config.engine.__class__):
continue
html_engine = pretty_html(engine('fieldset_readonly', fieldset=self))
assert html == html_engine, (name, html, html_engine)
return html
html = pretty_html(DefaultFieldSet.render(self))
for name, engine in templates.engines.items():
if isinstance(engine, config.engine.__class__):
continue
html_engine = pretty_html(engine('fieldset', fieldset=self))
assert html == html_engine, (name, html, html_engine)
return html
class Grid(DefaultGrid):
def render(self, lang=None):
if self.readonly:
html = pretty_html(DefaultGrid.render(self))
for name, engine in templates.engines.items():
if isinstance(engine, config.engine.__class__):
continue
html_engine = pretty_html(engine('grid_readonly', collection=self))
assert html == html_engine, (name, html, html_engine)
return html
html = pretty_html(DefaultGrid.render(self))
for name, engine in templates.engines.items():
if isinstance(engine, config.engine.__class__):
continue
html_engine = pretty_html(engine('grid', collection=self))
assert html == html_engine, (name, html, html_engine)
return html
original_renderers = FieldSet.default_renderers.copy()
def configure_and_render(fs, **options):
fs.configure(**options)
return fs.render()
if not hasattr(__builtins__, 'sorted'):
# 2.3 support
def sorted(L, key=lambda a: a):
L = list(L)
L.sort(lambda a, b: cmp(key(a), key(b)))
return L
class ImgRenderer(TextFieldRenderer):
def render(self, *args, **kwargs):
return '<img src="%s">' % self.value
import fake_module
fake_module.__dict__.update({
'fs': FieldSet(User),
})
import sys
sys.modules['library'] = fake_module
| Python |
# -*- coding: utf-8 -*-
import sys
from formalchemy import templates
__doc__ = """
There is two configuration settings available in a global config object.
- encoding: the global encoding used by FormAlchemy to deal with unicode. Default: utf-8
- engine: A valide :class:`~formalchemy.templates.TemplateEngine`
- date_format: Used to format date fields. Default to %Y-%d-%m
- date_edit_format: Used to retrieve field order. Default to m-d-y
Here is a simple example::
>>> from formalchemy import config
>>> config.encoding = 'iso-8859-1'
>>> config.encoding
'iso-8859-1'
>>> from formalchemy import templates
>>> config.engine = templates.TempitaEngine
There is also a convenience method to set the configuration from a config file::
>>> config.from_config({'formalchemy.encoding':'utf-8',
... 'formalchemy.engine':'mako',
... 'formalchemy.engine.options.input_encoding':'utf-8',
... 'formalchemy.engine.options.output_encoding':'utf-8',
... })
>>> config.from_config({'formalchemy.encoding':'utf-8'})
>>> config.encoding
'utf-8'
>>> isinstance(config.engine, templates.MakoEngine)
True
"""
class Config(object):
__doc__ = __doc__
__name__ = 'formalchemy.config'
__file__ = __file__
__data = dict(
encoding='utf-8',
date_format='%Y-%m-%d',
date_edit_format='m-d-y',
engine = templates.default_engine,
)
def __getattr__(self, attr):
if attr in self.__data:
return self.__data[attr]
else:
raise AttributeError('Configuration has no attribute %s' % attr)
def __setattr__(self, attr, value):
meth = getattr(self, '__set_%s' % attr, None)
if callable(meth):
meth(value)
else:
self.__data[attr] = value
def __set_engine(self, value):
if isinstance(value, templates.TemplateEngine):
self.__data['engine'] = value
else:
raise ValueError('%s is not a template engine')
def _get_config(self, config, prefix):
values = {}
config_keys = config.keys()
for k in config_keys:
if k.startswith(prefix):
v = config.pop(k)
k = k[len(prefix):]
values[k] = v
return values
def from_config(self, config, prefix='formalchemy.'):
from formalchemy import templates
engine_config = self._get_config(config, '%s.engine.options.' % prefix)
for k, v in self._get_config(config, prefix).items():
if k == 'engine':
engine = templates.__dict__.get('%sEngine' % v.title(), None)
if engine is not None:
v = engine(**engine_config)
else:
raise ValueError('%sEngine does not exist' % v.title())
self.__setattr__(k, v)
def __repr__(self):
return "<module 'formalchemy.config' from '%s' with values %s>" % (self.__file__, self.__data)
sys.modules['formalchemy.config'] = Config()
| Python |
# -*- coding: utf-8 -*-
import os
import stat
import string
import random
import formalchemy.helpers as h
from formalchemy.fields import FileFieldRenderer as Base
from formalchemy.validators import regex
from formalchemy.i18n import _
try:
from pylons import config
except ImportError:
config = {}
__all__ = ['file_extension', 'image_extension',
'FileFieldRenderer', 'ImageFieldRenderer']
def file_extension(extensions=[], errormsg=None):
"""Validate a file extension.
"""
if errormsg is None:
errormsg = _('Invalid file extension. Must be %s'%', '.join(extensions))
return regex(r'^.+\.(%s)$' % '|'.join(extensions), errormsg=errormsg)
def image_extension(extensions=['jpeg', 'jpg', 'gif', 'png']):
"""Validate an image extension. default valid extensions are jpeg, jpg,
gif, png.
"""
errormsg = _('Invalid image file. Must be %s'%', '.join(extensions))
return file_extension(extensions, errormsg=errormsg)
def normalized_basename(path):
"""
>>> print normalized_basename(u'c:\\Prog files\My fil\xe9.jpg')
My_fil.jpg
>>> print normalized_basename('c:\\Prog files\My fil\xc3\xa9.jpg')
My_fil.jpg
"""
if isinstance(path, str):
path = path.decode('utf-8', 'ignore').encode('ascii', 'ignore')
if isinstance(path, unicode):
path = path.encode('ascii', 'ignore')
filename = path.split('/')[-1]
filename = filename.split('\\')[-1]
return filename.replace(' ', '_')
class FileFieldRenderer(Base):
"""render a file input field stored on file system
"""
@property
def storage_path(self):
if 'app_conf' in config:
config['app_conf'].get('storage_path', '')
def __init__(self, *args, **kwargs):
if not self.storage_path or not os.path.isdir(self.storage_path):
raise ValueError(
'storage_path must be set to a valid path. Got %r' % self.storage_path)
Base.__init__(self, *args, **kwargs)
self._path = None
def relative_path(self, filename):
"""return the file path relative to root
"""
rdir = lambda: ''.join(random.sample(string.ascii_lowercase, 3))
path = '/'.join([rdir(), rdir(), rdir(), filename])
return path
def get_url(self, relative_path):
"""return the file url. by default return the relative path stored in
the DB
"""
return '/' + relative_path
def get_size(self):
relative_path = self.field.value
if relative_path:
filepath = os.path.join(self.storage_path,
relative_path.replace('/', os.sep))
if os.path.isfile(filepath):
return os.stat(filepath)[stat.ST_SIZE]
return 0
def render(self, **kwargs):
"""render a file field and the file preview
"""
html = Base.render(self, **kwargs)
value = self.field.value
if value:
html += self.render_readonly()
# add the old value for objects not yet stored
old_value = '%s--old' % self.name
html += h.hidden_field(old_value, value=value)
return html
def render_readonly(self, **kwargs):
"""render the filename and the binary size in a human readable with a
link to the file itself.
"""
value = self.field.value
if value:
content = '%s (%s)' % (normalized_basename(value),
self.readable_size())
return h.content_tag('a', content,
href=self.get_url(value), **kwargs)
return ''
def deserialize(self):
if self._path:
return self._path
data = Base.deserialize(self)
if self._data is not None and self._filename:
filename = normalized_basename(self._filename)
self._path = self.relative_path(filename)
filepath = os.path.join(self.storage_path,
self._path.replace('/', os.sep))
dirname = os.path.dirname(filepath)
if not os.path.isdir(dirname):
os.makedirs(dirname)
fd = open(filepath, 'wb')
fd.write(data)
fd.close()
return self._path
# get value from old_value if needed
old_value = '%s--old' % self.name
checkbox_name = '%s--remove' % self.name
if not data and not self.params.has_key(checkbox_name) \
and self.params.has_key(old_value):
return self.params[old_value]
return data is not None and data or ''
class ImageFieldRenderer(FileFieldRenderer):
def render_readonly(self, **kwargs):
"""render the image tag with a link to the image itself.
"""
value = self.field.value
if value:
url = self.get_url(value)
content = '%s (%s)' % (normalized_basename(value),
self.readable_size())
tag = h.tag('img', src=url, alt=content)
return h.content_tag('a', tag, href=url, **kwargs)
return ''
| Python |
# -*- coding: utf-8 -*-
__doc__ = """This module provides an experimental subclass of
:class:`~formalchemy.forms.FieldSet` to support RDFAlchemy_.
.. _RDFAlchemy: http://www.openvest.com/trac/wiki/RDFAlchemy
Usage
=====
>>> from rdfalchemy.samples.company import Company
>>> c = Company(stockDescription='description', symbol='FA',
... cik='cik', companyName='fa corp',
... stock=['value1'])
>>> fs = FieldSet(Company)
>>> fs.configure(options=[fs.stock.set(options=['value1', 'value2'])])
>>> fs = fs.bind(c)
>>> fs.stock.value
['value1']
>>> print fs.render().strip() # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
<div>
<label class="field_opt" for="Company--stockDescription">Stockdescription</label>
<input id="Company--stockDescription" name="Company--stockDescription" type="text" value="description" />
</div>
...
<div>
<label class="field_opt" for="Company--stock">Stock</label>
<select id="Company--stock" name="Company--stock">
<option selected="selected" value="value1">value1</option>
<option value="value2">value2</option>
</select>
</div>
>>> fs = Grid(Company, [c])
>>> fs.configure(options=[fs.stock.set(options=['value1', 'value2'])], readonly=True)
>>> print fs.render().strip() #doctest: +NORMALIZE_WHITESPACE
<thead>
<tr>
<th>Stockdescription</th>
<th>Companyname</th>
<th>Cik</th>
<th>Symbol</th>
<th>Stock</th>
</tr>
</thead>
<tbody>
<tr class="even">
<td>description</td>
<td>fa corp</td>
<td>cik</td>
<td>FA</td>
<td>value1</td>
</tr>
</tbody>
"""
from formalchemy.forms import FieldSet as BaseFieldSet
from formalchemy.tables import Grid as BaseGrid
from formalchemy.fields import Field as BaseField
from formalchemy.base import SimpleMultiDict
from formalchemy import fields
from formalchemy import validators
from formalchemy import fatypes
from sqlalchemy.util import OrderedDict
from rdfalchemy import descriptors
from datetime import datetime
__all__ = ['Field', 'FieldSet']
class Session(object):
"""A SA like Session to implement rdf"""
def add(self, record):
"""add a record"""
record.save()
def update(self, record):
"""update a record"""
record.save()
def delete(self, record):
"""delete a record"""
def query(self, model, *args, **kwargs):
raise NotImplementedError()
def commit(self):
"""do nothing since there is no transaction in couchdb"""
remove = commit
class Field(BaseField):
""""""
@property
def value(self):
if not self.is_readonly() and self.parent.data is not None:
v = self._deserialize()
if v is not None:
return v
return getattr(self.model, self.name)
@property
def model_value(self):
return getattr(self.model, self.name)
raw_value = model_value
def sync(self):
"""Set the attribute's value in `model` to the value given in `data`"""
if not self.is_readonly():
setattr(self.model, self.name, self._deserialize())
class FieldSet(BaseFieldSet):
_mapping = {
descriptors.rdfSingle: fatypes.String,
descriptors.rdfMultiple: fatypes.List,
descriptors.rdfList: fatypes.List,
}
def __init__(self, model, session=None, data=None, prefix=None):
self._fields = OrderedDict()
self._render_fields = OrderedDict()
self.model = self.session = None
BaseFieldSet.rebind(self, model, data=data)
self.prefix = prefix
self.model = model
self.readonly = False
self.focus = True
self._errors = []
focus = True
for k, v in model.__dict__.iteritems():
if not k.startswith('_'):
descriptor = type(v)
t = self._mapping.get(descriptor)
if t:
self.append(Field(name=k, type=t))
def bind(self, model=None, session=None, data=None):
"""Bind to an instance"""
if not (model or session or data):
raise Exception('must specify at least one of {model, session, data}')
if not model:
if not self.model:
raise Exception('model must be specified when none is already set')
else:
model = self.model()
# copy.copy causes a stacktrace on python 2.5.2/OSX + pylons. unable to reproduce w/ simpler sample.
mr = object.__new__(self.__class__)
mr.__dict__ = dict(self.__dict__)
# two steps so bind's error checking can work
mr.rebind(model, session, data)
mr._fields = OrderedDict([(key, renderer.bind(mr)) for key, renderer in self._fields.iteritems()])
if self._render_fields:
mr._render_fields = OrderedDict([(field.key, field) for field in
[field.bind(mr) for field in self._render_fields.itervalues()]])
return mr
def rebind(self, model, session=None, data=None):
if model:
if isinstance(model, type):
try:
model = model()
except:
raise Exception('%s appears to be a class, not an instance, but FormAlchemy cannot instantiate it. (Make sure all constructor parameters are optional!)' % model)
self.model = model
self._bound_pk = None
if data is None:
self.data = None
elif hasattr(data, 'getall') and hasattr(data, 'getone'):
self.data = data
else:
try:
self.data = SimpleMultiDict(data)
except:
raise Exception('unsupported data object %s. currently only dicts and Paste multidicts are supported' % self.data)
class Grid(BaseGrid, FieldSet):
def __init__(self, cls, instances=[], session=None, data=None, prefix=None):
FieldSet.__init__(self, cls, session, data, prefix)
self.rows = instances
self.readonly = False
self._errors = {}
def _get_errors(self):
return self._errors
def _set_errors(self, value):
self._errors = value
errors = property(_get_errors, _set_errors)
def rebind(self, instances=None, session=None, data=None):
FieldSet.rebind(data=data)
if instances is not None:
self.rows = instances
def _set_active(self, instance, session=None):
FieldSet.rebind(self, instance, session or self.session, self.data)
def test_sync():
from rdfalchemy.samples.company import Company
c = Company(stockDescription='description', symbol='FA',
cik='cik', companyName='fa corp',
stock=['value1'])
fs = FieldSet(Company)
fs.configure(include=[fs.companyName, fs.stock.set(options=['value1', 'value2'])])
fs = fs.bind(c, data={'Company--companyName':'new name', 'Company--stock':'value2'})
assert fs.stock.raw_value == ['value1']
fs.validate()
fs.sync()
assert fs.stock.raw_value == ['value2']
| Python |
# -*- coding: utf-8 -*-
try:
from tempita import paste_script_template_renderer
from paste.script.templates import Template, var
except ImportError:
class PylonsTemplate(object):
pass
else:
class PylonsTemplate(Template):
_template_dir = ('formalchemy', 'paster_templates/pylons_fa')
summary = 'Pylons application template with formalchemy support'
required_templates = ['pylons']
template_renderer = staticmethod(paste_script_template_renderer)
vars = [
var('admin_controller', 'Add formalchemy\'s admin controller',
default=False),
]
| Python |
# standard pylons controller imports
import os
import logging
log = logging.getLogger(__name__)
from pylons import request, response, session, config
from pylons import tmpl_context as c
from pylons import url
from pylons.controllers.util import redirect
import pylons.controllers.util as h
from webhelpers.paginate import Page
from sqlalchemy.orm import class_mapper, object_session
from formalchemy import *
from formalchemy.i18n import _, get_translator
from formalchemy.fields import _pk
from formalchemy.templates import MakoEngine
import simplejson as json
__all__ = ['FormAlchemyAdminController']
# misc labels
_('Add')
_('Edit')
_('New')
_('Save')
_('Delete')
_('Cancel')
_('Models')
_('Existing objects')
_('New object')
_('Related types')
_('Existing objects')
_('Create form')
# templates
template_dir = os.path.dirname(__file__)
static_dir = os.path.join(template_dir, 'resources')
def flash(msg):
"""Add 'msg' to the users flashest list in the users session"""
flashes = session.setdefault('_admin_flashes', [])
flashes.append(msg)
session.save()
def get_forms(model_module, forms):
"""scan model and forms"""
if forms is not None:
model_fieldsets = dict((form.model.__class__.__name__, form)
for form in forms.__dict__.itervalues()
if isinstance(form, FieldSet))
model_grids = dict((form.model.__class__.__name__, form)
for form in forms.__dict__.itervalues()
if isinstance(form, Grid))
else:
model_fieldsets = dict()
model_grids = dict()
# generate missing forms, grids
for key, obj in model_module.__dict__.iteritems():
try:
class_mapper(obj)
except:
continue
if not isinstance(obj, type):
continue
if key not in model_fieldsets:
model_fieldsets[key] = FieldSet(obj)
if key not in model_grids:
model_grids[key] = Grid(obj)
# add Edit + Delete link to grids
for modelname, grid in model_grids.iteritems():
def edit_link():
model_url = url('models', modelname=modelname)
return lambda item: '<a href="%(url)s/%(id)s" title="%(label)s" class="icon edit">%(label)s</a>' % dict(
url=model_url, id=_pk(item),
label=get_translator().gettext('edit'))
def delete_link():
model_url = url('models', modelname=modelname)
return lambda item: '''<form action="%(url)s/%(id)s" method="POST">
<input type="submit" class="icon delete" title="%(label)s" value="" />
<input type="hidden" name="_method" value="DELETE" />
</form>
''' % dict(
url=model_url, id=_pk(item),
label=get_translator().gettext('delete'))
grid.append(Field('edit', types.String, edit_link()))
grid.append(Field('delete', types.String, delete_link()))
grid.readonly = True
return {'_model_fieldsets':model_fieldsets, '_model_grids':model_grids}
class AdminController(object):
"""Base class to generate administration interface in Pylons"""
_custom_css = _custom_js = ''
def render_json(self, fs=None, **kwargs):
response.content_type = 'text/javascript'
if fs:
fields = dict([(field.key, field.model_value) for field in fs.render_fields.values()])
data = dict(fields=fields)
pk = _pk(fs.model)
if pk:
data['url'] = url('view_model', modelname=fs.model.__class__.__name__, id=pk)
else:
data = {}
data.update(kwargs)
return json.dumps(data)
def index(self, format='html'):
"""List model types"""
modelnames = sorted(self._model_grids.keys())
if format == 'json':
return self.render_json(**dict([(m, url('models', modelname=m)) for m in modelnames]))
return self._engine('admin_index', c=c, modelname=None,
modelnames=modelnames,
custom_css = self._custom_css,
custom_js = self._custom_js)
def list(self, modelname, format='html'):
"""List instances of a model type"""
S = self.Session()
grid = self._model_grids[modelname]
query = S.query(grid.model.__class__)
page = Page(query, page=int(request.GET.get('page', '1')), **self._paginate)
if format == 'json':
values = []
for item in page:
pk = _pk(item)
values.append((pk, url('view_model', pk)))
return self.render_json(records=dict(values), page_count=page.page_count, page=page.page)
grid = grid.bind(instances=page, session=None)
clsnames = [f.relation_type().__name__ for f in grid._fields.itervalues() if f.is_relation]
return self._engine('admin_list', c=c,
grid=grid,
page=page,
clsnames=clsnames,
modelname=modelname,
custom_css = self._custom_css,
custom_js = self._custom_js)
def edit(self, modelname, id=None, format='html'):
"""Edit (or create, if `id` is None) an instance of the given model type"""
saved = 1
if id and id.endswith('.json'):
id = id[:-5]
format = 'json'
if request.method == 'POST' or format == 'json':
if id:
prefix = '%s-%s' % (modelname, id)
else:
prefix = '%s-' % modelname
if request.method == 'PUT':
items = json.load(request.body_file).items()
request.method = 'POST'
elif '_method' not in request.POST:
items = request.POST.items()
format = 'json'
else:
items = None
if items:
for k, v in items:
if not k.startswith(prefix):
if isinstance(v, list):
for val in v:
request.POST.add('%s-%s' % (prefix, k), val)
else:
request.POST.add('%s-%s' % (prefix, k), v)
fs = self._model_fieldsets[modelname]
S = self.Session()
if id:
instance = S.query(fs.model.__class__).get(id)
assert instance, id
title = 'Edit'
else:
instance = fs.model.__class__
title = 'New object'
if request.method == 'POST':
F_ = get_translator().gettext
c.fs = fs.bind(instance, data=request.POST, session=not id and S or None)
if c.fs.validate():
c.fs.sync()
S.flush()
if not id:
# needed if the object does not exist in db
if not object_session(c.fs.model):
S.add(c.fs.model)
message = _('Created %s %s')
else:
S.refresh(c.fs.model)
message = _('Modified %s %s')
S.commit()
saved = 0
if format == 'html':
message = F_(message) % (modelname.encode('utf-8', 'ignore'),
_pk(c.fs.model))
flash(message)
redirect(url('models', modelname=modelname))
else:
c.fs = fs.bind(instance, session=not id and S or None)
if format == 'html':
return self._engine('admin_edit', c=c,
action=title, id=id,
modelname=modelname,
custom_css = self._custom_css,
custom_js = self._custom_js)
else:
return self.render_json(fs=c.fs, status=saved, model=modelname)
def delete(self, modelname, id, format='html'):
"""Delete an instance of the given model type"""
F_ = get_translator().gettext
fs = self._model_fieldsets[modelname]
S = self.Session()
instance = S.query(fs.model.__class__).get(id)
key = _pk(instance)
S.delete(instance)
S.commit()
if format == 'html':
message = F_(_('Deleted %s %s')) % (modelname.encode('utf-8', 'ignore'),
key)
flash(message)
redirect(url('models', modelname=modelname))
else:
return self.render_json(status=0)
def static(self, id):
filename = os.path.basename(id)
if filename not in os.listdir(static_dir):
raise IOError('Invalid filename: %s' % filename)
filepath = os.path.join(static_dir, filename)
if filename.endswith('.css'):
response.headers['Content-type'] = "text/css"
elif filename.endswith('.js'):
response.headers['Content-type'] = "text/javascript"
elif filename.endswith('.png'):
response.headers['Content-type'] = "image/png"
else:
raise IOError('Invalid filename: %s' % filename)
fd = open(filepath, 'rb')
data = fd.read()
fd.close()
return data
class TemplateEngine(MakoEngine):
directories = [os.path.join(p, 'fa_admin') for p in config['pylons.paths']['templates']] + [template_dir]
_templates = ['base', 'admin_index', 'admin_list', 'admin_edit']
def FormAlchemyAdminController(cls, engine=None, paginate=dict(), **kwargs):
"""
Generate a controller that is a subclass of `AdminController`
and the Pylons BaseController `cls`
"""
kwargs = get_forms(cls.model, cls.forms)
log.info('creating admin controller with args %s' % kwargs)
kwargs['_paginate'] = paginate
if engine is not None:
kwargs['_engine'] = engine
else:
kwargs['_engine'] = TemplateEngine(input_encoding='utf-8', output_encoding='utf-8')
return type(cls.__name__, (cls, AdminController), kwargs)
| Python |
# -*- coding: utf-8 -*-
import pylons
import logging
log = logging.getLogger(__name__)
try:
version = pylons.__version__.split('.')
except AttributeError:
version = ['0', '6']
def format(environ, result):
if environ.get('HTTP_ACCEPT', '') == 'application/json':
result['format'] = 'json'
return True
elif 'format' not in result:
result['format'] = 'html'
return True
def admin_map(map, controller, url='%s'):
"""connect the admin controller `cls` under the given `url`"""
log.info('connecting %s to %s' % (url, controller))
map.connect('static_contents', '%s/static_contents/{id}' % url, controller=controller, action='static')
map.connect('admin', '%s' % url,
controller=controller, action='index')
map.connect('formatted_admin', '%s.{format}' % url,
controller=controller, action='index')
map.connect("models", "%s/{modelname}" % url,
controller=controller, action="edit", id=None, format='html',
conditions=dict(method=["POST"], function=format))
map.connect("models", "%s/{modelname}" % url,
controller=controller, action="list",
conditions=dict(method=["GET"], function=format))
map.connect("formatted_models", "%s/{modelname}.{format}" % url,
controller=controller, action="list",
conditions=dict(method=["GET"]))
map.connect("new_model", "%s/{modelname}/new" % url,
controller=controller, action="edit", id=None,
conditions=dict(method=["GET"]))
map.connect("formatted_new_model", "%s/{modelname}/new.{format}" % url,
controller=controller, action="edit", id=None,
conditions=dict(method=["GET"]))
map.connect("%s/{modelname}/{id}" % url,
controller=controller, action="edit",
conditions=dict(method=["PUT"], function=format))
map.connect("%s/{modelname}/{id}" % url,
controller=controller, action="delete",
conditions=dict(method=["DELETE"]))
map.connect("edit_model", "%s/{modelname}/{id}/edit" % url,
controller=controller, action="edit",
conditions=dict(method=["GET"]))
map.connect("formatted_edit_model", "%s/{modelname}/{id}.{format}/edit" % url,
controller=controller, action="edit",
conditions=dict(method=["GET"]))
map.connect("view_model", "%s/{modelname}/{id}" % url,
controller=controller, action="edit",
conditions=dict(method=["GET"], function=format))
map.connect("formatted_view_model", "%s/{modelname}/{id}.{format}" % url,
controller=controller, action="edit",
conditions=dict(method=["GET"]))
| Python |
# -*- coding: utf-8 -*-
| Python |
# -*- coding: utf-8 -*-
import os
from paste.urlparser import StaticURLParser
from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect
from pylons.templating import render_mako as render
from pylons import url
from webhelpers.paginate import Page
from sqlalchemy.orm import class_mapper, object_session
from formalchemy.fields import _pk
from formalchemy.fields import _stringify
from formalchemy import Grid, FieldSet
from formalchemy.i18n import get_translator
from formalchemy.fields import Field
from formalchemy import fatypes
try:
from formalchemy.ext.couchdb import Document
except ImportError:
Document = None
import simplejson as json
def model_url(*args, **kwargs):
"""wrap ``pylons.url`` and take care about ``model_name`` in
``pylons.routes_dict`` if any"""
if 'model_name' in request.environ['pylons.routes_dict'] and 'model_name' not in kwargs:
kwargs['model_name'] = request.environ['pylons.routes_dict']['model_name']
return url(*args, **kwargs)
class Session(object):
"""A abstract class to implement other backend than SA"""
def add(self, record):
"""add a record"""
def update(self, record):
"""update a record"""
def delete(self, record):
"""delete a record"""
def commit(self):
"""commit transaction"""
class _RESTController(object):
"""A RESTful Controller bound to a model"""
template = '/forms/restfieldset.mako'
engine = prefix_name = None
FieldSet = FieldSet
Grid = Grid
pager_args = dict(link_attr={'class': 'ui-pager-link ui-state-default ui-corner-all'},
curpage_attr={'class': 'ui-pager-curpage ui-state-highlight ui-corner-all'})
@property
def model_name(self):
"""return ``model_name`` from ``pylons.routes_dict``"""
return request.environ['pylons.routes_dict'].get('model_name', None)
def Session(self):
"""return a Session object. You **must** override this."""
return Session()
def get_model(self):
"""return SA mapper class. You **must** override this."""
raise NotImplementedError()
def sync(self, fs, id=None):
"""sync a record. If ``id`` is None add a new record else save current one.
Default is::
S = self.Session()
if id:
S.merge(fs.model)
else:
S.add(fs.model)
S.commit()
"""
S = self.Session()
if id:
try:
S.merge(fs.model)
except AttributeError:
# SA <= 0.5.6
S.update(fs.model)
else:
S.add(fs.model)
S.commit()
def breadcrumb(self, action=None, fs=None, id=None, **kwargs):
"""return items to build the breadcrumb"""
items = []
if self.prefix_name:
items.append((url(self.prefix_name), self.prefix_name))
if self.model_name:
items.append((model_url(self.collection_name), self.model_name))
elif not self.prefix_name and 'is_grid' not in kwargs:
items.append((model_url(self.collection_name), self.collection_name))
if id and hasattr(fs.model, '__unicode__'):
items.append((model_url(self.member_name, id=id), u'%s' % fs.model))
elif id:
items.append((model_url(self.member_name, id=id), id))
if action in ('edit', 'new'):
items.append((None, action))
return items
def render(self, format='html', **kwargs):
"""render the form as html or json"""
if format != 'html':
meth = getattr(self, 'render_%s_format' % format, None)
if meth is not None:
return meth(**kwargs)
else:
abort(404)
kwargs.update(model_name=self.model_name or self.member_name,
prefix_name=self.prefix_name,
collection_name=self.collection_name,
member_name=self.member_name,
breadcrumb=self.breadcrumb(**kwargs),
F_=get_translator().gettext)
if self.engine:
return self.engine.render(self.template, **kwargs)
else:
return render(self.template, extra_vars=kwargs)
def render_grid(self, format='html', **kwargs):
"""render the grid as html or json"""
return self.render(format=format, is_grid=True, **kwargs)
def render_json_format(self, fs=None, **kwargs):
response.content_type = 'text/javascript'
if fs:
try:
fields = fs.jsonify()
except AttributeError:
fields = dict([(field.renderer.name, field.model_value) for field in fs.render_fields.values()])
data = dict(fields=fields)
pk = _pk(fs.model)
if pk:
data['item_url'] = model_url(self.member_name, id=pk)
else:
data = {}
data.update(kwargs)
return json.dumps(data)
def render_xhr_format(self, fs=None, **kwargs):
response.content_type = 'text/html'
if fs is not None:
if 'field' in request.GET:
field_name = request.GET.get('field')
fields = fs.render_fields
if field_name in fields:
field = fields[field_name]
return field.render()
else:
abort(404)
return fs.render()
return ''
def get_page(self, **kwargs):
"""return a ``webhelpers.paginate.Page`` used to display ``Grid``.
Default is::
S = self.Session()
query = S.query(self.get_model())
kwargs = request.environ.get('pylons.routes_dict', {})
return Page(query, page=int(request.GET.get('page', '1')), **kwargs)
"""
S = self.Session()
options = dict(collection=S.query(self.get_model()), page=int(request.GET.get('page', '1')))
options.update(request.environ.get('pylons.routes_dict', {}))
options.update(kwargs)
collection = options.pop('collection')
return Page(collection, **options)
def get(self, id=None):
"""return correct record for ``id`` or a new instance.
Default is::
S = self.Session()
model = self.get_model()
if id:
model = S.query(model).get(id)
else:
model = model()
return model or abort(404)
"""
S = self.Session()
model = self.get_model()
if id:
model = S.query(model).get(id)
return model or abort(404)
def get_fieldset(self, id=None):
"""return a ``FieldSet`` object bound to the correct record for ``id``.
Default is::
fs = self.FieldSet(self.get(id))
fs.engine = fs.engine or self.engine
return fs
"""
fs = self.FieldSet(self.get(id))
fs.engine = fs.engine or self.engine
return fs
def get_add_fieldset(self):
"""return a ``FieldSet`` used for add form.
Default is::
fs = self.get_fieldset()
for field in fs.render_fields.itervalues():
if field.is_readonly():
del fs[field.name]
return fs
"""
fs = self.get_fieldset()
for field in fs.render_fields.itervalues():
if field.is_readonly():
del fs[field.name]
return fs
def get_grid(self):
"""return a Grid object
Default is::
grid = self.Grid(self.get_model())
grid.engine = self.engine
self.update_grid(grid)
return grid
"""
grid = self.Grid(self.get_model())
grid.engine = self.engine
self.update_grid(grid)
return grid
def update_grid(self, grid):
"""Add edit and delete buttons to ``Grid``"""
try:
grid.edit
except AttributeError:
def edit_link():
return lambda item: '''
<form action="%(url)s" method="GET" class="ui-grid-icon ui-widget-header ui-corner-all">
<input type="submit" class="ui-grid-icon ui-icon ui-icon-pencil" title="%(label)s" value="%(label)s" />
</form>
''' % dict(url=model_url('edit_%s' % self.member_name, id=_pk(item)),
label=get_translator().gettext('edit'))
def delete_link():
return lambda item: '''
<form action="%(url)s" method="POST" class="ui-grid-icon ui-state-error ui-corner-all">
<input type="submit" class="ui-icon ui-icon-circle-close" title="%(label)s" value="%(label)s" />
<input type="hidden" name="_method" value="DELETE" />
</form>
''' % dict(url=model_url(self.member_name, id=_pk(item)),
label=get_translator().gettext('delete'))
grid.append(Field('edit', fatypes.String, edit_link()))
grid.append(Field('delete', fatypes.String, delete_link()))
grid.readonly = True
def index(self, format='html', **kwargs):
"""REST api"""
page = self.get_page()
fs = self.get_grid()
fs = fs.bind(instances=page)
fs.readonly = True
if format == 'json':
values = []
for item in page:
pk = _pk(item)
fs._set_active(item)
value = dict(id=pk,
item_url=model_url(self.member_name, id=pk))
if 'jqgrid' in request.GET:
fields = [_stringify(field.render_readonly()) for field in fs.render_fields.values()]
value['cell'] = [pk] + fields
else:
value.update(dict([(field.key, field.model_value) for field in fs.render_fields.values()]))
values.append(value)
return self.render_json_format(rows=values,
records=len(values),
total=page.page_count,
page=page.page)
if 'pager' not in kwargs:
pager = page.pager(**self.pager_args)
else:
pager = kwargs.pop('pager')
return self.render_grid(format=format, fs=fs, id=None, pager=pager)
def create(self, format='html', **kwargs):
"""REST api"""
fs = self.get_add_fieldset()
if format == 'json' and request.method == 'PUT':
data = json.load(request.body_file)
else:
data = request.POST
try:
fs = fs.bind(data=data, session=self.Session())
except:
# non SA forms
fs = fs.bind(self.get_model(), data=data, session=self.Session())
if fs.validate():
fs.sync()
self.sync(fs)
if format == 'html':
if request.is_xhr:
response.content_type = 'text/plain'
return ''
redirect(model_url(self.collection_name))
else:
fs.rebind(fs.model, data=None)
return self.render(format=format, fs=fs)
return self.render(format=format, fs=fs, action='new', id=None)
def delete(self, id, format='html', **kwargs):
"""REST api"""
record = self.get(id)
if record:
S = self.Session()
S.delete(record)
S.commit()
if format == 'html':
if request.is_xhr:
response.content_type = 'text/plain'
return ''
redirect(model_url(self.collection_name))
return self.render(format=format, id=id)
def show(self, id=None, format='html', **kwargs):
"""REST api"""
fs = self.get_fieldset(id=id)
fs.readonly = True
return self.render(format=format, fs=fs, action='show', id=id)
def new(self, format='html', **kwargs):
"""REST api"""
fs = self.get_add_fieldset()
fs = fs.bind(session=self.Session())
return self.render(format=format, fs=fs, action='new', id=None)
def edit(self, id=None, format='html', **kwargs):
"""REST api"""
fs = self.get_fieldset(id)
return self.render(format=format, fs=fs, action='edit', id=id)
def update(self, id, format='html', **kwargs):
"""REST api"""
fs = self.get_fieldset(id)
if format == 'json' and request.method == 'PUT' and '_method' not in request.GET:
data = json.load(request.body_file)
else:
data = request.POST
fs = fs.bind(data=data)
if fs.validate():
fs.sync()
self.sync(fs, id)
if format == 'html':
if request.is_xhr:
response.content_type = 'text/plain'
return ''
redirect(model_url(self.member_name, id=id))
else:
return self.render(format=format, fs=fs, status=0)
if format == 'html':
return self.render(format=format, fs=fs, action='edit', id=id)
else:
return self.render(format=format, fs=fs, status=1)
def RESTController(cls, member_name, collection_name):
"""wrap a controller with :class:`~formalchemy.ext.pylons.controller._RESTController`"""
return type(cls.__name__, (cls, _RESTController),
dict(member_name=member_name, collection_name=collection_name))
class _ModelsController(_RESTController):
"""A RESTful Controller bound to more tha one model. The ``model`` and
``forms`` attribute can be a list of object or a module"""
engine = None
model = forms = None
_static_app = StaticURLParser(os.path.join(os.path.dirname(__file__), 'resources'))
def Session(self):
return meta.Session
def models(self, format='html', **kwargs):
"""Models index page"""
models = self.get_models()
return self.render(models=models, format=format)
def static(self):
"""Serve static files from the formalchemy package"""
return self._static_app(request.environ, self.start_response)
def get_models(self):
"""return a dict containing all model names as key and url as value"""
models = {}
if isinstance(self.model, list):
for model in self.model:
key = model.__name__
models[key] = model_url(self.collection_name, model_name=key)
else:
for key, obj in self.model.__dict__.iteritems():
if not key.startswith('_'):
if Document is not None:
try:
if issubclass(obj, Document):
models[key] = model_url(self.collection_name, model_name=key)
continue
except:
pass
try:
class_mapper(obj)
except:
continue
if not isinstance(obj, type):
continue
models[key] = model_url(self.collection_name, model_name=key)
return models
def get_model(self):
if isinstance(self.model, list):
for model in self.model:
if model.__name__ == self.model_name:
return model
elif hasattr(self.model, self.model_name):
return getattr(self.model, self.model_name)
abort(404)
def get_fieldset(self, id):
if self.forms and hasattr(self.forms, self.model_name):
fs = getattr(self.forms, self.model_name)
fs.engine = fs.engine or self.engine
return id and fs.bind(self.get(id)) or fs
return _RESTController.get_fieldset(self, id)
def get_add_fieldset(self):
if self.forms and hasattr(self.forms, '%sAdd' % self.model_name):
fs = getattr(self.forms, '%sAdd' % self.model_name)
fs.engine = fs.engine or self.engine
return fs
return self.get_fieldset(id=None)
def get_grid(self):
model_name = self.model_name
if self.forms and hasattr(self.forms, '%sGrid' % model_name):
g = getattr(self.forms, '%sGrid' % model_name)
g.engine = g.engine or self.engine
g.readonly = True
self.update_grid(g)
return g
return _RESTController.get_grid(self)
def ModelsController(cls, prefix_name, member_name, collection_name):
"""wrap a controller with :class:`~formalchemy.ext.pylons.controller._ModelsController`"""
return type(cls.__name__, (cls, _ModelsController),
dict(prefix_name=prefix_name, member_name=member_name, collection_name=collection_name))
| Python |
# -*- coding: utf-8 -*-
import os
from paste.urlparser import StaticURLParser
from webhelpers.paginate import Page
from sqlalchemy.orm import class_mapper, object_session
from formalchemy.fields import _pk
from formalchemy.fields import _stringify
from formalchemy import Grid, FieldSet
from formalchemy.i18n import get_translator
from formalchemy.fields import Field
from formalchemy import fatypes
from pyramid.view import view_config
from pyramid.renderers import render
from pyramid.renderers import get_renderer
from pyramid import httpexceptions as exc
try:
from formalchemy.ext.couchdb import Document
except ImportError:
Document = None
import simplejson as json
class Session(object):
"""A abstract class to implement other backend than SA"""
def add(self, record):
"""add a record"""
def update(self, record):
"""update a record"""
def delete(self, record):
"""delete a record"""
def commit(self):
"""commit transaction"""
class AdminView(object):
def __init__(self, request):
self.request = request
request.model_name = None
request.model_id = None
request.format = 'html'
self.__parent__ = self.__name__ = None
def __getitem__(self, item):
if item in ('json',):
self.request.format = item
return self
model = ModelListing(self.request, item)
model.__parent__ = self
return model
class ModelListing(object):
def __init__(self, request, name):
self.request = request
request.model_name = name
self.__name__ = name
self.__parent__ = None
def __getitem__(self, item):
if item in ('json',):
self.request.format = item
return self
if item in ('new',):
raise KeyError()
model = ModelItem(self.request, item)
model.__parent__ = self
return model
class ModelItem(object):
def __init__(self, request, name):
request.model_id = name
self.__name__ = name
self.__parent__ = None
class ModelView(object):
"""A RESTful view bound to a model"""
engine = prefix_name = None
pager_args = dict(link_attr={'class': 'ui-pager-link ui-state-default ui-corner-all'},
curpage_attr={'class': 'ui-pager-curpage ui-state-highlight ui-corner-all'})
def __init__(self, context, request):
self.context = context
self.request = request
self.settings = request.registry.settings
self.model = self.settings['fa.models']
self.forms = self.settings.get('fa.forms', None)
self.FieldSet = self.settings.get('fa.fieldset', FieldSet)
self.Grid = self.settings.get('fa.grid', Grid)
@property
def model_name(self):
"""return ``model_name`` from ``pylons.routes_dict``"""
try:
return self.request.model_name
except AttributeError:
return None
def route_url(self, *args):
return self.request.route_url('fa_admin', traverse='/'.join([str(a) for a in args]))
def Session(self):
"""return a Session object. You **must** override this."""
return self.settings['fa.session_factory']()
def models(self, **kwargs):
"""Models index page"""
request = self.request
models = {}
if isinstance(self.model, list):
for model in self.model:
key = model.__name__
models[key] = self.route_url(key, request.format)
else:
for key, obj in self.model.__dict__.iteritems():
if not key.startswith('_'):
if Document is not None:
try:
if issubclass(obj, Document):
models[key] = self.route_url(key, request.format)
continue
except:
pass
try:
class_mapper(obj)
except:
continue
if not isinstance(obj, type):
continue
models[key] = self.route_url(key, request.format)
return self.render(models=models)
def get_model(self):
if isinstance(self.model, list):
for model in self.model:
if model.__name__ == self.model_name:
return model
elif hasattr(self.model, self.model_name):
return getattr(self.model, self.model_name)
raise exc.HTTPNotFound(description='model %s not found' % self.model_name)
def get_fieldset(self, id):
if self.forms and hasattr(self.forms, self.model_name):
fs = getattr(self.forms, self.model_name)
fs.engine = fs.engine or self.engine
return id and fs.bind(self.get(id)) or fs
raise KeyError(self.model_name)
def get_add_fieldset(self):
if self.forms and hasattr(self.forms, '%sAdd' % self.model_name):
fs = getattr(self.forms, '%sAdd' % self.model_name)
fs.engine = fs.engine or self.engine
return fs
return self.get_fieldset(id=None)
def get_grid(self):
model_name = self.model_name
if self.forms and hasattr(self.forms, '%sGrid' % model_name):
g = getattr(self.forms, '%sGrid' % model_name)
g.engine = g.engine or self.engine
g.readonly = True
self.update_grid(g)
return g
raise KeyError(self.model_name)
def sync(self, fs, id=None):
"""sync a record. If ``id`` is None add a new record else save current one.
Default is::
S = self.Session()
if id:
S.merge(fs.model)
else:
S.add(fs.model)
S.commit()
"""
S = self.Session()
if id:
S.merge(fs.model)
else:
S.add(fs.model)
def breadcrumb(self, fs=None, **kwargs):
"""return items to build the breadcrumb"""
items = []
request = self.request
model_name = request.model_name
id = request.model_id
items.append((self.route_url(), 'root'))
if self.model_name:
items.append((self.route_url(model_name), model_name))
if id and hasattr(fs.model, '__unicode__'):
items.append((self.route_url(model_name, id), u'%s' % fs.model))
elif id:
items.append((self.route_url(model_name, id), id))
return items
def render(self, **kwargs):
"""render the form as html or json"""
request = self.request
if request.format != 'html':
meth = getattr(self, 'render_%s_format' % request.format, None)
if meth is not None:
return meth(**kwargs)
else:
return exc.HTTPNotfound()
kwargs.update(
main = get_renderer('formalchemy:ext/pyramid/forms/master.pt').implementation(),
model_name=self.model_name,
breadcrumb=self.breadcrumb(**kwargs),
F_=get_translator().gettext)
return kwargs
def render_grid(self, **kwargs):
"""render the grid as html or json"""
return self.render(is_grid=True, **kwargs)
def render_json_format(self, fs=None, **kwargs):
request = self.request
request.override_renderer = 'json'
if fs:
try:
fields = fs.jsonify()
except AttributeError:
fields = dict([(field.renderer.name, field.model_value) for field in fs.render_fields.values()])
data = dict(fields=fields)
pk = _pk(fs.model)
if pk:
data['item_url'] = request.route_url('fa_admin', traverse='%s/json/%s' % (self.model_name, pk))
else:
data = {}
data.update(kwargs)
return data
def render_xhr_format(self, fs=None, **kwargs):
response.content_type = 'text/html'
if fs is not None:
if 'field' in request.GET:
field_name = request.GET.get('field')
fields = fs.render_fields
if field_name in fields:
field = fields[field_name]
return field.render()
else:
return exc.HTTPNotfound()
return fs.render()
return ''
def get_page(self, **kwargs):
"""return a ``webhelpers.paginate.Page`` used to display ``Grid``.
Default is::
S = self.Session()
query = S.query(self.get_model())
kwargs = request.environ.get('pylons.routes_dict', {})
return Page(query, page=int(request.GET.get('page', '1')), **kwargs)
"""
S = self.Session()
def get_page_url(page, partial=None):
url = "%s?page=%s" % (self.request.path, page)
if partial:
url += "&partial=1"
return url
options = dict(collection=S.query(self.get_model()),
page=int(self.request.GET.get('page', '1')),
url=get_page_url)
options.update(kwargs)
collection = options.pop('collection')
return Page(collection, **options)
def get(self, id=None):
"""return correct record for ``id`` or a new instance.
Default is::
S = self.Session()
model = self.get_model()
if id:
model = S.query(model).get(id)
else:
model = model()
return model or abort(404)
"""
S = self.Session()
model = self.get_model()
if id:
model = S.query(model).get(id)
if model:
return model
raise exc.HTTPNotFound()
def get_fieldset(self, id=None):
"""return a ``FieldSet`` object bound to the correct record for ``id``.
Default is::
fs = self.FieldSet(self.get(id))
fs.engine = fs.engine or self.engine
return fs
"""
if self.forms and hasattr(self.forms, self.model_name):
fs = getattr(self.forms, self.model_name)
fs.engine = fs.engine or self.engine
return id and fs.bind(self.get(id)) or fs
fs = self.FieldSet(self.get(id))
fs.engine = fs.engine or self.engine
return fs
def get_add_fieldset(self):
"""return a ``FieldSet`` used for add form.
Default is::
fs = self.get_fieldset()
for field in fs.render_fields.itervalues():
if field.is_readonly():
del fs[field.name]
return fs
"""
fs = self.get_fieldset()
for field in fs.render_fields.itervalues():
if field.is_readonly():
del fs[field.name]
return fs
def get_grid(self):
"""return a Grid object
Default is::
grid = self.Grid(self.get_model())
grid.engine = self.engine
self.update_grid(grid)
return grid
"""
model_name = self.model_name
if self.forms and hasattr(self.forms, '%sGrid' % model_name):
g = getattr(self.forms, '%sGrid' % model_name)
g.engine = g.engine or self.engine
g.readonly = True
self.update_grid(g)
return g
grid = self.Grid(self.get_model())
grid.engine = self.engine
self.update_grid(grid)
return grid
def update_grid(self, grid):
"""Add edit and delete buttons to ``Grid``"""
try:
grid.edit
except AttributeError:
def edit_link():
return lambda item: '''
<form action="%(url)s" method="GET" class="ui-grid-icon ui-widget-header ui-corner-all">
<input type="submit" class="ui-grid-icon ui-icon ui-icon-pencil" title="%(label)s" value="%(label)s" />
</form>
''' % dict(url=self.route_url(self.model_name, _pk(item), 'edit'),
label=get_translator().gettext('edit'))
def delete_link():
return lambda item: '''
<form action="%(url)s" method="POST" class="ui-grid-icon ui-state-error ui-corner-all">
<input type="submit" class="ui-icon ui-icon-circle-close" title="%(label)s" value="%(label)s" />
</form>
''' % dict(url=self.route_url(self.model_name, _pk(item), 'delete'),
label=get_translator().gettext('delete'))
grid.append(Field('edit', fatypes.String, edit_link()))
grid.append(Field('delete', fatypes.String, delete_link()))
grid.readonly = True
def listing(self, **kwargs):
"""listing page"""
page = self.get_page()
fs = self.get_grid()
fs = fs.bind(instances=page)
fs.readonly = True
if self.request.format == 'json':
values = []
request = self.request
for item in page:
pk = _pk(item)
fs._set_active(item)
value = dict(id=pk,
item_url=self.route_url(request.model_name, pk))
if 'jqgrid' in request.GET:
fields = [_stringify(field.render_readonly()) for field in fs.render_fields.values()]
value['cell'] = [pk] + fields
else:
value.update(dict([(field.key, field.model_value) for field in fs.render_fields.values()]))
values.append(value)
return self.render_json_format(rows=values,
records=len(values),
total=page.page_count,
page=page.page)
if 'pager' not in kwargs:
pager = page.pager(**self.pager_args)
else:
pager = kwargs.pop('pager')
return self.render_grid(fs=fs, id=None, pager=pager)
def create(self):
"""REST api"""
request = self.request
S = self.Session()
fs = self.get_add_fieldset()
if request.format == 'json' and request.method == 'PUT':
data = json.load(request.body_file)
else:
data = request.POST
try:
fs = fs.bind(data=data, session=S)
except:
# non SA forms
fs = fs.bind(self.get_model(), data=data, session=S)
if fs.validate():
fs.sync()
self.sync(fs)
S.flush()
if request.format == 'html':
if request.is_xhr:
response.content_type = 'text/plain'
return ''
return exc.HTTPFound(
location=self.route_url(request.model_name))
else:
fs.rebind(fs.model, data=None)
return self.render(fs=fs)
return self.render(fs=fs, action='new', id=None)
def delete(self, **kwargs):
"""REST api"""
request = self.request
id = request.model_id
record = self.get(id)
if record:
S = self.Session()
S.delete(record)
if request.format == 'html':
if request.is_xhr:
response = Response()
response.content_type = 'text/plain'
return response
return exc.HTTPFound(location=self.route_url(request.model_name))
return self.render(id=id)
def show(self):
"""REST api"""
id = self.request.model_id
fs = self.get_fieldset(id=id)
fs.readonly = True
return self.render(fs=fs, action='show', id=id)
def new(self, **kwargs):
"""REST api"""
fs = self.get_add_fieldset()
fs = fs.bind(session=self.Session())
return self.render(fs=fs, action='new', id=None)
def edit(self, id=None, **kwargs):
"""REST api"""
id = self.request.model_id
fs = self.get_fieldset(id)
return self.render(fs=fs, action='edit', id=id)
def update(self, **kwargs):
"""REST api"""
request = self.request
S = self.Session()
id = request.model_id
fs = self.get_fieldset(id)
if not request.POST:
raise ValueError(request.POST)
fs = fs.bind(data=request.POST)
if fs.validate():
fs.sync()
self.sync(fs, id)
S.flush()
if request.format == 'html':
if request.is_xhr:
response.content_type = 'text/plain'
return ''
return exc.HTTPFound(
location=self.route_url(request.model_name, _pk(fs.model)))
else:
return self.render(fs=fs, status=0)
if request.format == 'html':
return self.render(fs=fs, action='edit', id=id)
else:
return self.render(fs=fs, status=1)
| Python |
registry = dict(version=0)
| Python |
# -*- coding: utf-8 -*-
| Python |
# -*- coding: utf-8 -*-
| Python |
# -*- coding: utf-8 -*-
__doc__ = """This module provides an experimental subclass of
:class:`~formalchemy.forms.FieldSet` to support zope.schema_'s schema. `Simple
validation`_ is supported. `Invariant`_ is not supported.
.. _zope.schema: http://pypi.python.org/pypi/zope.schema
.. _simple validation: http://pypi.python.org/pypi/zope.schema#simple-usage
.. _invariant: http://pypi.python.org/pypi/zope.schema#schema-validation
Available fields
================
Not all fields are supported. You can use TextLine, Text, Int, Bool, Float,
Date, Datetime, Time, and Choice.
Usage
=====
Here is a simple example. First we need a schema::
>>> class IPet(interface.Interface):
... name = schema.Text(title=u'Name', required=True)
... type = schema.TextLine(title=u'Type', required=True)
... age = schema.Int(min=1)
... owner = schema.TextLine(title=u'Owner')
... birthdate = schema.Date(title=u'Birth date')
... colour = schema.Choice(title=u'Colour',
... values=['Brown', 'Black'])
... friends = schema.List(title=u'Friends', value_type=schema.Choice(['cat', 'dog', 'bulldog']))
Initialize FieldSet with schema::
>>> fs = FieldSet(IPet)
Create a class to store values. If your class does not implement the form interface the FieldSet will generate an adapter for you:
>>> class Pet(FlexibleDict):pass
>>> p = Pet(name='dewey', type='cat', owner='gawel', friends=['cat', 'dog'])
>>> fs = fs.bind(p)
Fields are aware of schema attributes:
>>> fs.name.is_required()
True
We can use the form::
>>> print fs.render().strip() #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
<div>
<label class="field_req" for="Pet--name">Name</label>
<textarea id="Pet--name" name="Pet--name">dewey</textarea>
</div>
<script type="text/javascript">
//<![CDATA[
document.getElementById("Pet--name").focus();
//]]>
</script>
<div>
<label class="field_req" for="Pet--type">Type</label>
<input id="Pet--type" name="Pet--type" type="text" value="cat" />
</div>
<div>
<label class="field_req" for="Pet--age">age</label>
<input id="Pet--age" name="Pet--age" type="text" />
</div>
<div>
<label class="field_req" for="Pet--owner">Owner</label>
<input id="Pet--owner" name="Pet--owner" type="text" value="gawel" />
</div>
<div>
<label class="field_req" for="Pet--birthdate">Birth date</label>
<span id="Pet--birthdate"><select id="Pet--birthdate__month" name="Pet--birthdate__month">
<option value="MM">Month</option>
<option value="1">January</option>
<option value="2">February</option>
...
<option value="31">31</option>
</select>
<input id="Pet--birthdate__year" maxlength="4" name="Pet--birthdate__year" size="4" type="text" value="YYYY" /></span>
</div>
<div>
<label class="field_req" for="Pet--colour">Colour</label>
<select id="Pet--colour" name="Pet--colour">
<option value="Brown">Brown</option>
<option value="Black">Black</option>
</select>
</div>
<div>
<label class="field_req" for="Pet--friends">Friends</label>
<select id="Pet--friends" multiple="multiple" name="Pet--friends">
<option value="bulldog">bulldog</option>
<option selected="selected" value="dog">dog</option>
<option selected="selected" value="cat">cat</option>
</select>
</div>
Ok, let's assume that validation and syncing works:
>>> fs.configure(include=[fs.name])
>>> fs.rebind(p, data={'Pet--name':'minou'})
>>> fs.validate()
True
>>> fs.sync()
>>> fs.name.value
'minou'
>>> p.name
'minou'
>>> fs.configure(include=[fs.age])
>>> fs.rebind(p, data={'Pet--age':'-1'})
>>> fs.validate()
False
>>> fs.age.errors
[u'Value is too small']
>>> fs.configure(include=[fs.colour])
>>> fs.rebind(p, data={'Pet--colour':'Yellow'})
>>> fs.validate()
False
>>> fs.colour.errors
[u'Constraint not satisfied']
>>> fs.rebind(p, data={'Pet--colour':'Brown'})
>>> fs.validate()
True
>>> fs.sync()
>>> fs.colour.value
'Brown'
>>> p.colour
'Brown'
Looks nice ! Let's use the grid:
>>> grid = Grid(IPet)
>>> grid = grid.bind([p])
>>> print grid.render().strip() #doctest: +ELLIPSIS
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>age</th>
<th>Owner</th>
<th>Birth date</th>
<th>Colour</th>
<th>Friends</th>
</tr>
...
<tr class="even">
<td>
<textarea id="Pet--name" name="Pet--name">minou</textarea>
</td>
<td>
<input id="Pet--type" name="Pet--type" type="text" value="cat" />
</td>
<td>
<input id="Pet--age" name="Pet--age" type="text" />
</td>
<td>
<input id="Pet--owner" name="Pet--owner" type="text" value="gawel" />
</td>
<td>
<span id="Pet--birthdate"><select id="Pet--birthdate__month" name="Pet--birthdate__month">
<option value="MM">Month</option>
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<select id="Pet--birthdate__day" name="Pet--birthdate__day">
<option value="DD">Day</option>
<option value="1">1</option>
...
<option value="31">31</option>
</select>
<input id="Pet--birthdate__year" maxlength="4" name="Pet--birthdate__year" size="4" type="text" value="YYYY" /></span>
</td>
<td>
<select id="Pet--colour" name="Pet--colour">
<option selected="selected" value="Brown">Brown</option>
<option value="Black">Black</option>
</select>
</td>
<td>
<select id="Pet--friends" multiple="multiple" name="Pet--friends">
<option value="bulldog">bulldog</option>
<option selected="selected" value="dog">dog</option>
<option selected="selected" value="cat">cat</option>
</select>
</td>
</tr>
</tbody>
"""
from formalchemy.forms import FieldSet as BaseFieldSet
from formalchemy.tables import Grid as BaseGrid
from formalchemy.fields import Field as BaseField
from formalchemy.fields import _stringify
from formalchemy.base import SimpleMultiDict
from formalchemy import fields
from formalchemy import validators
from formalchemy import fatypes
from sqlalchemy.util import OrderedDict
from datetime import datetime
from uuid import UUID
from zope import schema
from zope.schema import interfaces
from zope import interface
class Pk(property):
"""FormAlchemy use a ``_pk`` attribute to identify objects. You can use
this property to bind another attribute as a primary key::
>>> class Content(object):
... _pk = Pk()
... __name__ = 'primary_key'
>>> content = Content()
>>> content._pk
'primary_key'
>>> content._pk = 'another_key'
>>> content.__name__
'another_key'
>>> class Content(object):
... _pk = Pk('uid')
... uid = 'primary_key'
>>> content = Content()
>>> content._pk
'primary_key'
>>> fields._pk(content)
'primary_key'
"""
def __init__(self, attr='__name__'):
self.attr = attr
def __get__(self, instance, cls):
return getattr(instance, self.attr, None) or None
def __set__(self, instance, value):
setattr(instance, self.attr, value)
class FlexibleModel(object):
"""A flexible object to easy adapt most python classes:
.. sourcecode:: python
>>> obj = FlexibleModel(owner='gawel')
>>> obj.owner == obj.get('owner') == obj['owner'] == 'gawel'
True
>>> obj._pk is None
True
If your object provide an uuid attribute then FormAlchemy will use it has primary key:
.. sourcecode:: python
>>> import uuid
>>> obj = FlexibleModel(uuid=uuid.uuid4())
>>> obj._pk is None
False
"""
interface.implements(interface.Interface)
_is_dict = False
def __init__(self, context=None, **kwargs):
if context is None:
self.context = dict(**kwargs)
else:
self.context = context
if getattr(self, 'uuid', None):
uuid = self.uuid
if isinstance(uuid, UUID):
self._pk = str(int(uuid))
else:
self._pk = _stringify(self.uuid)
else:
self._pk = None
def __getattr__(self, attr):
"""flexible __getattr__. also used for __getitem__ and get"""
if hasattr(self.context, attr):
return getattr(self.context, attr, None)
elif self._is_dict or isinstance(self.context, dict):
return self.context.get(attr)
raise AttributeError('%r as no attribute %s' % (self.context, attr))
__getitem__ = get = __getattr__
def __setattr__(self, attr, value):
"""flexible __getattr__"""
if attr.startswith('_') or attr == 'context':
object.__setattr__(self, attr, value)
elif not self._is_dict and hasattr(self.context, attr):
setattr(self.context, attr, value)
elif self._is_dict or isinstance(self.context, dict):
self.context[attr] = value
else:
raise AttributeError('%r as no attribute %s' % (self.context, attr))
def __repr__(self):
return '<%s adapter for %s>' % (self.__class__.__name__, repr(self.context))
class FlexibleDict(FlexibleModel, dict):
"""like FlexibleModel but inherit from dict:
.. sourcecode:: python
>>> obj = FlexibleDict(owner='gawel')
>>> obj.owner == obj.get('owner') == obj['owner'] == 'gawel'
True
>>> isinstance(obj, dict)
True
>>> 'owner' in obj
True
"""
interface.implements(interface.Interface)
_is_dict = True
def keys(self):
return self.context.keys()
def values(self):
return self.context.values()
def items(self):
return self.context.items()
def copy(self):
return self.context.copy()
def __iter__(self):
return iter(self.context)
def __contains__(self, value):
return value in self.context
_model_registry = {}
def gen_model(iface, klass=None, dict_like=False):
"""return a new FlexibleModel or FlexibleDict factory who provide iface:
.. sourcecode:: python
>>> class ITitle(interfaces.Interface):
... title = schema.TextLine(title=u'title')
>>> factory = gen_model(ITitle)
>>> adapted = factory()
>>> ITitle.providedBy(adapted)
True
>>> class Title(object):
... title = None
>>> obj = Title()
>>> adapted = factory(obj)
>>> adapted.context is obj
True
>>> adapted.title = 'my title'
>>> obj.title
'my title'
>>> obj = dict()
>>> adapted = factory(obj)
>>> adapted.context is obj
True
>>> adapted.title = 'my title'
>>> obj['title']
'my title'
"""
if klass:
if not hasattr(klass, '__name__'):
klass = klass.__class__
name = class_name = klass.__name__
else:
class_name = None
name = iface.__name__[1:]
adapter = _model_registry.get((iface.__name__, class_name), None)
if adapter is not None:
return adapter
new_klass = type(name, (dict_like and FlexibleDict or FlexibleModel,), {})
def adapter(context=None, **kwargs):
adapted = new_klass(context=context, **kwargs)
interface.directlyProvides(adapted, [iface])
return adapted
_model_registry[(iface.__name__, class_name)] = adapter
return adapter
class Field(BaseField):
"""Field aware of zope schema. See :class:`formalchemy.fields.AbstractField` for full api."""
def set(self, options=[], **kwargs):
if isinstance(options, schema.Choice):
sourcelist = options.source.by_value.values()
if sourcelist[0].title is None:
options = [term.value for term in sourcelist]
else:
options = [(term.title, term.value) for term in sourcelist]
return BaseField.set(self, options=options, **kwargs)
@property
def value(self):
if not self.is_readonly() and self.parent.data is not None:
v = self._deserialize()
if v is not None:
return v
return getattr(self.model, self.name)
@property
def raw_value(self):
try:
return getattr(self.model, self.name)
except (KeyError, AttributeError):
pass
if callable(self._value):
return self._value(self.model)
return self._value
def _validate(self):
if self.is_readonly():
return True
valide = BaseField._validate(self)
if not valide:
return False
value = self._deserialize()
if isinstance(self.type, fatypes.Unicode) and not isinstance(value, unicode):
value = _stringify(value)
field = self.parent.iface[self.name]
bound = field.bind(self.model)
try:
bound.validate(value)
except schema.ValidationError, e:
self.errors.append(e.doc())
except schema._bootstrapinterfaces.ConstraintNotSatisfied, e:
self.errors.append(e.doc())
return not self.errors
def sync(self):
"""Set the attribute's value in `model` to the value given in `data`"""
if not self.is_readonly():
setattr(self.model, self.name, self._deserialize())
class FieldSet(BaseFieldSet):
"""FieldSet aware of zope schema. See :class:`formalchemy.forms.FieldSet` for full api."""
_fields_mapping = {
schema.TextLine: fatypes.Unicode,
schema.Text: fatypes.Unicode,
schema.Int: fatypes.Integer,
schema.Bool: fatypes.Boolean,
schema.Float: fatypes.Float,
schema.Date: fatypes.Date,
schema.Datetime: fatypes.DateTime,
schema.Time: fatypes.Time,
schema.Choice: fatypes.Unicode,
schema.List: fatypes.List,
}
def __init__(self, model, session=None, data=None, prefix=None):
self._fields = OrderedDict()
self._render_fields = OrderedDict()
self.model = self.session = None
self.prefix = prefix
self.model = model
self.readonly = False
self.focus = True
self._errors = []
self._bound_pk = None
self.data = None
self.validator = None
self.iface = model
focus = True
for name, field in schema.getFieldsInOrder(model):
klass = field.__class__
try:
t = self._fields_mapping[klass]
except KeyError:
raise NotImplementedError('%s is not mapped to a type' % klass)
else:
self.append(Field(name=name, type=t))
self._fields[name].label_text = field.title or name
if field.description:
self._fields[name].set(instructions=field.description)
if field.required:
self._fields[name].validators.append(validators.required)
if klass is schema.Text:
self._fields[name].set(renderer=fields.TextAreaFieldRenderer)
if klass is schema.List:
value_type = self.model[name].value_type
if isinstance(value_type, schema.Choice):
self._fields[name].set(options=value_type, multiple=True)
else:
self._fields[name].set(multiple=True)
elif klass is schema.Choice:
self._fields[name].set(renderer=fields.SelectFieldRenderer,
options=self.model[name])
def bind(self, model, session=None, data=None):
if not (model is not None or session or data):
raise Exception('must specify at least one of {model, session, data}')
# copy.copy causes a stacktrace on python 2.5.2/OSX + pylons. unable to reproduce w/ simpler sample.
mr = object.__new__(self.__class__)
mr.__dict__ = dict(self.__dict__)
# two steps so bind's error checking can work
mr.rebind(model, session, data)
mr._fields = OrderedDict([(key, renderer.bind(mr)) for key, renderer in self._fields.iteritems()])
if self._render_fields:
mr._render_fields = OrderedDict([(field.key, field) for field in
[field.bind(mr) for field in self._render_fields.itervalues()]])
return mr
def gen_model(self, model=None, dict_like=False, **kwargs):
if model and self.iface.providedBy(model):
return model
factory = gen_model(self.iface, model, dict_like=dict_like)
model = factory(context=model, **kwargs)
return model
def rebind(self, model, session=None, data=None):
if model is not self.iface:
if model and not self.iface.providedBy(model):
if getattr(model, '__implemented__', None) is not None:
raise ValueError('%r does not provide %r' % (model, self.iface))
model = self.gen_model(model)
self.model = model
self._bound_pk = fields._pk(model)
if data is None:
self.data = None
elif hasattr(data, 'getall') and hasattr(data, 'getone'):
self.data = data
else:
try:
self.data = SimpleMultiDict(data)
except:
raise Exception('unsupported data object %s. currently only dicts and Paste multidicts are supported' % self.data)
class Grid(BaseGrid, FieldSet):
"""Grid aware of zope schema. See :class:`formalchemy.tables.Grid` for full api."""
def __init__(self, cls, instances=[], session=None, data=None, prefix=None):
FieldSet.__init__(self, cls, session, data, prefix)
self.rows = instances
self.readonly = False
self._errors = {}
def _get_errors(self):
return self._errors
def _set_errors(self, value):
self._errors = value
errors = property(_get_errors, _set_errors)
def rebind(self, instances=None, session=None, data=None):
self.session = session
self.data = data
if instances is not None:
self.rows = instances
def bind(self, instances=None, session=None, data=None):
mr = FieldSet.bind(self, self.iface, session, data)
mr.rows = instances
return mr
def _set_active(self, instance, session=None):
instance = self.gen_model(instance)
FieldSet.rebind(self, instance, session or self.session, self.data)
| Python |
# -*- coding: utf-8 -*-
__doc__ = """
Define a couchdbkit schema::
>>> from couchdbkit import schema
>>> from formalchemy.ext import couchdb
>>> class Person(couchdb.Document):
... name = schema.StringProperty(required=True)
... @classmethod
... def _render_options(self, fs):
... return [(gawel, gawel._id), (benoitc, benoitc._id)]
... def __unicode__(self): return getattr(self, 'name', None) or u''
>>> gawel = Person(name='gawel')
>>> gawel._id = '123'
>>> benoitc = Person(name='benoitc')
>>> benoitc._id = '456'
>>> class Pet(couchdb.Document):
... name = schema.StringProperty(required=True)
... type = schema.StringProperty(required=True)
... birthdate = schema.DateProperty(auto_now=True)
... weight_in_pounds = schema.IntegerProperty()
... spayed_or_neutered = schema.BooleanProperty()
... owner = schema.SchemaProperty(Person)
... friends = schema.SchemaListProperty(Person)
Configure your FieldSet::
>>> fs = couchdb.FieldSet(Pet)
>>> fs.configure(include=[fs.name, fs.type, fs.birthdate, fs.weight_in_pounds])
>>> p = Pet(name='dewey')
>>> p.name = 'dewey'
>>> p.type = 'cat'
>>> p.owner = gawel
>>> p.friends = [benoitc]
>>> fs = fs.bind(p)
Render it::
>>> # rendering
>>> fs.name.is_required()
True
>>> print fs.render() # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
<div>
<label class="field_req" for="Pet--name">Name</label>
<input id="Pet--name" name="Pet--name" type="text" value="dewey" />
</div>
<script type="text/javascript">
//<![CDATA[
document.getElementById("Pet--name").focus();
//]]>
</script>
<div>
<label class="field_req" for="Pet--type">Type</label>
<input id="Pet--type" name="Pet--type" type="text" value="cat" />
</div>
<div>
<label class="field_opt" for="Pet--birthdate">Birthdate</label>
<span id="Pet--birthdate"><select id="Pet--birthdate__month" name="Pet--birthdate__month">
<option value="MM">Month</option>
...
Same for grids::
>>> # grid
>>> grid = couchdb.Grid(Pet, [p, Pet()])
>>> grid.configure(include=[grid.name, grid.type, grid.birthdate, grid.weight_in_pounds, grid.friends])
>>> print grid.render() # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Birthdate</th>
<th>Weight in pounds</th>
<th>Friends</th>
</tr>
</thead>
<tbody>
<tr class="even">
<td>
<input id="Pet--name" name="Pet--name" type="text" value="dewey" />
</td>
<td>
<input id="Pet--type" name="Pet--type" type="text" value="cat" />
</td>
<td>
<span id="Pet--birthdate">...
</td>
<td>
<select id="Pet--friends" multiple="multiple" name="Pet--friends">
<option value="123">gawel</option>
<option selected="selected" value="456">benoitc</option>
</select>
</td>...
"""
from formalchemy.forms import FieldSet as BaseFieldSet
from formalchemy.tables import Grid as BaseGrid
from formalchemy.fields import Field as BaseField
from formalchemy.base import SimpleMultiDict
from formalchemy import fields
from formalchemy import validators
from formalchemy import fatypes
from sqlalchemy.util import OrderedDict
from couchdbkit.schema.properties_proxy import LazySchemaList
from couchdbkit import schema
from datetime import datetime
__all__ = ['Field', 'FieldSet', 'Session', 'Document']
class Pk(property):
def __init__(self, attr='_id'):
self.attr = attr
def __get__(self, instance, cls):
if not instance:
return self
return getattr(instance, self.attr, None) or None
def __set__(self, instance, value):
setattr(instance, self.attr, value)
class Document(schema.Document):
_pk = Pk()
class Query(list):
"""A list like object to emulate SQLAlchemy's Query. This mostly exist to
work with ``webhelpers.paginate.Page``"""
def __init__(self, model, **options):
self.model = model
self._init = False
self.options = options
def get(self, id):
"""Get a record by id"""
return self.model.get(id)
def view(self, view_name, **kwargs):
"""set self to a list of record returned by view named ``{model_name}/{view_name}``"""
kwargs = kwargs or self.options
if not self._init:
self.extend([r for r in self.model.view('%s/%s' % (self.model.__name__.lower(), view_name), **kwargs)])
self._init = True
return self
def all(self, **kwargs):
"""set self to a list of record returned by view named ``{model_name}/all``"""
kwargs = kwargs or self.options
return self.view('all', **kwargs)
def __len__(self):
if not self._init:
self.all()
return list.__len__(self)
class Session(object):
"""A SA like Session to implement couchdb"""
def __init__(self, db):
self.db = db
def add(self, record):
"""add a record"""
record.save()
def update(self, record):
"""update a record"""
record.save()
def delete(self, record):
"""delete a record"""
del self.db[record._id]
def query(self, model, *args, **kwargs):
"""return a :class:`~formalchemy.ext.couchdb.Query` bound to model object"""
return Query(model, *args, **kwargs)
def commit(self):
"""do nothing since there is no transaction in couchdb"""
remove = commit
def _stringify(value):
if isinstance(value, (list, LazySchemaList)):
return [_stringify(v) for v in value]
if isinstance(value, schema.Document):
return value._id
return value
class Field(BaseField):
"""Field for CouchDB FieldSet"""
def __init__(self, *args, **kwargs):
self.schema = kwargs.pop('schema')
if self.schema and 'renderer' not in kwargs:
kwargs['renderer'] = fields.SelectFieldRenderer
if self.schema and 'options' not in kwargs:
if hasattr(self.schema, '_render_options'):
kwargs['options'] = self.schema._render_options
else:
kwargs['options'] = lambda fs: [(d, d._id) for d in Query(self.schema).all()]
if kwargs.get('type') == fatypes.List:
kwargs['multiple'] = True
BaseField.__init__(self, *args, **kwargs)
@property
def value(self):
if not self.is_readonly() and self.parent.data is not None:
v = self._deserialize()
if v is not None:
return v
value = getattr(self.model, self.name)
return _stringify(value)
@property
def raw_value(self):
try:
value = getattr(self.model, self.name)
return _stringify(value)
except (KeyError, AttributeError):
pass
if callable(self._value):
return self._value(self.model)
return self._value
def sync(self):
"""Set the attribute's value in `model` to the value given in `data`"""
if not self.is_readonly():
value = self._deserialize()
if self.schema:
if isinstance(value, list):
value = [self.schema.get(v) for v in value]
else:
value = self.schema.get(value)
setattr(self.model, self.name, value)
class FieldSet(BaseFieldSet):
"""See :class:`~formalchemy.forms.FieldSet`"""
def __init__(self, model, session=None, data=None, prefix=None):
self._fields = OrderedDict()
self._render_fields = OrderedDict()
self.model = self.session = None
if model is not None and isinstance(model, schema.Document):
BaseFieldSet.rebind(self, model.__class__, data=data)
self.doc = model.__class__
self._bound_pk = fields._pk(model)
else:
BaseFieldSet.rebind(self, model, data=data)
self.doc = model
self.model = model
self.prefix = prefix
self.validator = None
self.readonly = False
self.focus = True
self._errors = []
focus = True
values = self.doc._properties.values()
values.sort(lambda a, b: cmp(a.creation_counter, b.creation_counter))
for v in values:
if getattr(v, 'name'):
k = v.name
sch = None
if isinstance(v, schema.SchemaListProperty):
t = fatypes.List
sch = v._schema
elif isinstance(v, schema.SchemaProperty):
t = fatypes.String
sch = v._schema
else:
try:
t = getattr(fatypes, v.__class__.__name__.replace('Property',''))
except AttributeError:
raise NotImplementedError('%s is not mapped to a type for field %s (%s)' % (v.__class__, k, v.__class__.__name__))
self.append(Field(name=k, type=t, schema=sch))
if v.required:
self._fields[k].validators.append(validators.required)
def bind(self, model=None, session=None, data=None):
"""Bind to an instance"""
if not (model or session or data):
raise Exception('must specify at least one of {model, session, data}')
if not model:
if not self.model:
raise Exception('model must be specified when none is already set')
model = fields._pk(self.model) is None and self.doc() or self.model
# copy.copy causes a stacktrace on python 2.5.2/OSX + pylons. unable to reproduce w/ simpler sample.
mr = object.__new__(self.__class__)
mr.__dict__ = dict(self.__dict__)
# two steps so bind's error checking can work
mr.rebind(model, session, data)
mr._fields = OrderedDict([(key, renderer.bind(mr)) for key, renderer in self._fields.iteritems()])
if self._render_fields:
mr._render_fields = OrderedDict([(field.key, field) for field in
[field.bind(mr) for field in self._render_fields.itervalues()]])
return mr
def rebind(self, model=None, session=None, data=None):
if model is not None and model is not self.doc:
if not isinstance(model, self.doc):
try:
model = model()
except Exception, e:
raise Exception('''%s appears to be a class, not an instance,
but FormAlchemy cannot instantiate it. (Make sure
all constructor parameters are optional!) %r - %s''' % (
model, self.doc, e))
else:
model = self.doc()
self.model = model
self._bound_pk = fields._pk(model)
if data is None:
self.data = None
elif hasattr(data, 'getall') and hasattr(data, 'getone'):
self.data = data
else:
try:
self.data = SimpleMultiDict(data)
except:
raise Exception('unsupported data object %s. currently only dicts and Paste multidicts are supported' % self.data)
def jsonify(self):
if isinstance(self.model, schema.Document):
return self.model.to_json()
return self.doc().to_json()
class Grid(BaseGrid, FieldSet):
"""See :class:`~formalchemy.tables.Grid`"""
def __init__(self, cls, instances=[], session=None, data=None, prefix=None):
FieldSet.__init__(self, cls, session, data, prefix)
self.rows = instances
self.readonly = False
self._errors = {}
def _get_errors(self):
return self._errors
def _set_errors(self, value):
self._errors = value
errors = property(_get_errors, _set_errors)
def rebind(self, instances=None, session=None, data=None):
FieldSet.rebind(self, self.model, data=data)
if instances is not None:
self.rows = instances
def bind(self, instances=None, session=None, data=None):
mr = FieldSet.bind(self, self.model, session, data)
mr.rows = instances
return mr
def _set_active(self, instance, session=None):
FieldSet.rebind(self, instance, session or self.session, self.data)
| Python |
# Copyright (C) 2007 Alexandre Conrad, alexandre (dot) conrad (at) gmail (dot) com
#
# This module is part of FormAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
# todo 2.0 pass field and value (so exception can refer to field name, for instance)
from exceptions import ValidationError
from i18n import _
if 'any' not in locals():
# pre-2.5 support
def any(seq):
"""
>>> any(xrange(10))
True
>>> any([0, 0, 0])
False
"""
for o in seq:
if o:
return True
return False
def accepts_none(func):
"""validator decorator to validate None value"""
func.accepts_none = True
return func
def required(value, field=None):
"""Successful if value is neither None nor the empty string (yes, including empty lists)"""
if value is None or value == '':
msg = isinstance(value, list) and _('Please select a value') or _('Please enter a value')
raise ValidationError(msg)
required = accepts_none(required)
# other validators will not be called for empty values
def integer(value, field=None):
"""Successful if value is an int"""
# the validator contract says you don't have to worry about "value is None",
# but this is called from deserialize as well as validation
if isinstance(value, int):
return value
if value is None or not value.strip():
return None
try:
return int(value)
except:
raise ValidationError(_('Value is not an integer'))
def float_(value, field=None):
"""Successful if value is a float"""
# the validator contract says you don't have to worry about "value is None",
# but this is called from deserialize as well as validation
if value is None or not value.strip():
return None
try:
return float(value)
except:
raise ValidationError(_('Value is not a number'))
from decimal import Decimal
def decimal_(value, field=None):
"""Successful if value can represent a decimal"""
# the validator contract says you don't have to worry about "value is None",
# but this is called from deserialize as well as validation
if value is None or not value.strip():
return None
try:
return Decimal(value)
except:
raise ValidationError(_('Value is not a number'))
def currency(value, field=None):
"""Successful if value looks like a currency amount (has exactly two digits after a decimal point)"""
if '%.2f' % float_(value) != value:
raise ValidationError('Please specify full currency value, including cents (e.g., 12.34)')
def email(value, field=None):
"""
Successful if value is a valid RFC 822 email address.
Ignores the more subtle intricacies of what is legal inside a quoted region,
and thus may accept some
technically invalid addresses, but will never reject a valid address
(which is a much worse problem).
"""
if not value.strip():
return None
reserved = r'()<>@,;:\"[]'
try:
recipient, domain = value.split('@', 1)
except ValueError:
raise ValidationError(_('Missing @ sign'))
if any([ord(ch) < 32 for ch in value]):
raise ValidationError(_('Control characters present'))
if any([ord(ch) > 127 for ch in value]):
raise ValidationError(_('Non-ASCII characters present'))
# validate recipient
if not recipient:
raise ValidationError(_('Recipient must be non-empty'))
if recipient.endswith('.'):
raise ValidationError(_("Recipient must not end with '.'"))
# quoted regions, aka the reason any regexp-based validator is wrong
i = 0
while i < len(recipient):
if recipient[i] == '"' and (i == 0 or recipient[i - 1] == '.' or recipient[i - 1] == '"'):
# begin quoted region -- reserved characters are allowed here.
# (this implementation allows a few addresses not strictly allowed by rfc 822 --
# for instance, a quoted region that ends with '\' appears to be illegal.)
i += 1
while i < len(recipient):
if recipient[i] == '"':
break # end of quoted region
i += 1
else:
raise ValidationError(_("Unterminated quoted section in recipient"))
i += 1
if i < len(recipient) and recipient[i] != '.':
raise ValidationError(_("Quoted section must be followed by '@' or '.'"))
continue
if recipient[i] in reserved:
raise ValidationError(_("Reserved character present in recipient"))
i += 1
# validate domain
if not domain:
raise ValidationError(_('Domain must be non-empty'))
if domain.endswith('.'):
raise ValidationError(_("Domain must not end with '.'"))
if '..' in domain:
raise ValidationError(_("Domain must not contain '..'"))
if any([ch in reserved for ch in domain]):
raise ValidationError(_("Reserved character present in domain"))
# parameterized validators return the validation function
def maxlength(length):
"""Returns a validator that is successful if the input's length is at most the given one."""
if length <= 0:
raise ValueError('Invalid maximum length')
def f(value, field=None):
if len(value) > length:
raise ValidationError(_('Value must be no more than %d characters long') % length)
return f
def minlength(length):
"""Returns a validator that is successful if the input's length is at least the given one."""
if length <= 0:
raise ValueError('Invalid minimum length')
def f(value, field=None):
if len(value) < length:
raise ValidationError(_('Value must be at least %d characters long') % length)
return f
def regex(exp, errormsg=_('Invalid input')):
"""
Returns a validator that is successful if the input matches (that is,
fulfils the semantics of re.match) the given expression.
Expressions may be either a string or a Pattern object of the sort returned by
re.compile.
"""
import re
if type(exp) != type(re.compile('')):
exp = re.compile(exp)
def f(value, field=None):
if not exp.match(value):
raise ValidationError(errormsg)
return f
# possible others:
# oneof raises if input is not one of [or a subset of for multivalues] the given list of possibilities
# url(check_exists=False)
# address parts
# cidr
# creditcard number/securitycode (/expires?)
# whole-form validators
# fieldsmatch
# requiredipresent/missing
| Python |
#! /usr/bin/env python
# -*- coding: iso-8859-1 -*-
# Written by Martin v. Loewis <loewis@informatik.hu-berlin.de>
#
# Changed by Christian 'Tiran' Heimes <tiran@cheimes.de> for the placeless
# translation service (PTS) of zope
#
# Slightly updated by Hanno Schlichting <plone@hannosch.info>
#
# Included by Ingeniweb from PlacelessTranslationService 1.4.8
"""Generate binary message catalog from textual translation description.
This program converts a textual Uniforum-style message catalog (.po file) into
a binary GNU catalog (.mo file). This is essentially the same function as the
GNU msgfmt program, however, it is a simpler implementation.
This file was taken from Python-2.3.2/Tools/i18n and altered in several ways.
Now you can simply use it from another python module:
from msgfmt import Msgfmt
mo = Msgfmt(po).get()
where po is path to a po file as string, an opened po file ready for reading or
a list of strings (readlines of a po file) and mo is the compiled mo
file as binary string.
Exceptions:
* IOError if the file couldn't be read
* msgfmt.PoSyntaxError if the po file has syntax errors
"""
import struct
import array
import types
from cStringIO import StringIO
__version__ = "1.1pts"
class PoSyntaxError(Exception):
""" Syntax error in a po file """
def __init__(self, msg):
self.msg = msg
def __str__(self):
return 'Po file syntax error: %s' % self.msg
class Msgfmt:
""" """
def __init__(self, po, name='unknown'):
self.po = po
self.name = name
self.messages = {}
def readPoData(self):
""" read po data from self.po and store it in self.poLines """
output = []
if isinstance(self.po, types.FileType):
self.po.seek(0)
output = self.po.readlines()
if isinstance(self.po, list):
output = self.po
if isinstance(self.po, str):
output = open(self.po, 'rb').readlines()
if not output:
raise ValueError, "self.po is invalid! %s" % type(self.po)
return output
def add(self, id, str, fuzzy):
"Add a non-empty and non-fuzzy translation to the dictionary."
if str and not fuzzy:
self.messages[id] = str
def generate(self):
"Return the generated output."
keys = self.messages.keys()
# the keys are sorted in the .mo file
keys.sort()
offsets = []
ids = strs = ''
for id in keys:
# For each string, we need size and file offset. Each string is NUL
# terminated; the NUL does not count into the size.
offsets.append((len(ids), len(id), len(strs), len(self.messages[id])))
ids += id + '\0'
strs += self.messages[id] + '\0'
output = ''
# The header is 7 32-bit unsigned integers. We don't use hash tables, so
# the keys start right after the index tables.
# translated string.
keystart = 7*4+16*len(keys)
# and the values start after the keys
valuestart = keystart + len(ids)
koffsets = []
voffsets = []
# The string table first has the list of keys, then the list of values.
# Each entry has first the size of the string, then the file offset.
for o1, l1, o2, l2 in offsets:
koffsets += [l1, o1+keystart]
voffsets += [l2, o2+valuestart]
offsets = koffsets + voffsets
output = struct.pack("Iiiiiii",
0x950412deL, # Magic
0, # Version
len(keys), # # of entries
7*4, # start of key index
7*4+len(keys)*8, # start of value index
0, 0) # size and offset of hash table
output += array.array("i", offsets).tostring()
output += ids
output += strs
return output
def get(self):
""" """
ID = 1
STR = 2
section = None
fuzzy = 0
lines = self.readPoData()
# Parse the catalog
lno = 0
for l in lines:
lno += 1
# If we get a comment line after a msgstr or a line starting with
# msgid, this is a new entry
# XXX: l.startswith('msgid') is needed because not all msgid/msgstr
# pairs in the plone pos have a leading comment
if (l[0] == '#' or l.startswith('msgid')) and section == STR:
self.add(msgid, msgstr, fuzzy)
section = None
fuzzy = 0
# Record a fuzzy mark
if l[:2] == '#,' and 'fuzzy' in l:
fuzzy = 1
# Skip comments
if l[0] == '#':
continue
# Now we are in a msgid section, output previous section
if l.startswith('msgid'):
section = ID
l = l[5:]
msgid = msgstr = ''
# Now we are in a msgstr section
elif l.startswith('msgstr'):
section = STR
l = l[6:]
# Skip empty lines
l = l.strip()
if not l:
continue
# XXX: Does this always follow Python escape semantics?
# XXX: eval is evil because it could be abused
try:
l = eval(l, globals())
except Exception, msg:
raise PoSyntaxError('%s (line %d of po file %s): \n%s' % (msg, lno, self.name, l))
if section == ID:
msgid += l
elif section == STR:
msgstr += l
else:
raise PoSyntaxError('error in line %d of po file %s' % (lno, self.name))
# Add last entry
if section == STR:
self.add(msgid, msgstr, fuzzy)
# Compute output
return self.generate()
def getAsFile(self):
return StringIO(self.get())
def __call__(self):
return self.getAsFile()
| Python |
"""
A small module to wrap WebHelpers in FormAlchemy.
"""
from webhelpers.html.tags import text
from webhelpers.html.tags import hidden
from webhelpers.html.tags import password
from webhelpers.html.tags import textarea
from webhelpers.html.tags import checkbox
from webhelpers.html.tags import radio
from webhelpers.html import tags
from webhelpers.html import HTML, literal
def html_escape(s):
return HTML(s)
escape_once = html_escape
def content_tag(name, content, **options):
"""
Create a tag with content
Takes the same keyword args as ``tag``
Examples::
>>> print content_tag("p", "Hello world!")
<p>Hello world!</p>
>>> print content_tag("div", content_tag("p", "Hello world!"), class_="strong")
<div class="strong"><p>Hello world!</p></div>
"""
if content is None:
content = ''
tag = HTML.tag(name, _closed=False, **options) + HTML(content) + literal('</%s>' % name)
return tag
def text_field(name, value=None, **options):
"""
Creates a standard text field.
``value`` is a string, the content of the text field
Options:
* ``disabled`` - If set to True, the user will not be able to use this input.
* ``size`` - The number of visible characters that will fit in the input.
* ``maxlength`` - The maximum number of characters that the browser will allow the user to enter.
Remaining keyword options will be standard HTML options for the tag.
"""
_update_fa(options, name)
return text(name, value=value, **options)
def password_field(name="password", value=None, **options):
"""
Creates a password field
Takes the same options as text_field
"""
_update_fa(options, name)
return password(name, value=value, **options)
def text_area(name, content='', **options):
"""
Creates a text input area.
Options:
* ``size`` - A string specifying the dimensions of the textarea.
Example::
>>> print text_area("Body", '', size="25x10")
<textarea cols="25" id="Body" name="Body" rows="10"></textarea>
"""
_update_fa(options, name)
if 'size' in options:
options["cols"], options["rows"] = options["size"].split("x")
del options['size']
return textarea(name, content=content, **options)
def check_box(name, value="1", checked=False, **options):
"""
Creates a check box.
"""
_update_fa(options, name)
if checked:
options["checked"] = "checked"
return tags.checkbox(name, value=value, **options)
def hidden_field(name, value=None, **options):
"""
Creates a hidden field.
Takes the same options as text_field
"""
_update_fa(options, name)
return tags.hidden(name, value=value, **options)
def file_field(name, value=None, **options):
"""
Creates a file upload field.
If you are using file uploads then you will also need to set the multipart option for the form.
Example::
>>> print file_field('myfile')
<input id="myfile" name="myfile" type="file" />
"""
_update_fa(options, name)
return tags.file(name, value=value, type="file", **options)
def radio_button(name, *args, **options):
_update_fa(options, name)
return radio(name, *args, **options)
def tag_options(**options):
strip_unders(options)
if 'options' in options:
del options['options']
cleaned_options = convert_booleans(dict([(x, y) for x, y in options.iteritems() if y is not None]))
optionlist = ['%s="%s"' % (x, escape_once(y)) for x, y in cleaned_options.iteritems()]
optionlist.sort()
if optionlist:
return ' ' + ' '.join(optionlist)
else:
return ''
def tag(name, open=False, **options):
"""
Returns an XHTML compliant tag of type ``name``.
``open``
Set to True if the tag should remain open
All additional keyword args become attribute/value's for the tag. To pass in Python
reserved words, append _ to the name of the key. For attributes with no value (such as
disabled and readonly), a value of True is permitted.
Examples::
>>> print tag("br")
<br />
>>> print tag("br", True)
<br>
>>> print tag("input", type="text")
<input type="text" />
>>> print tag("input", type='text', disabled='disabled')
<input disabled="disabled" type="text" />
"""
return HTML.tag(name, _closed=not open, **options)
def label(value, **kwargs):
"""
Return a label tag
>>> print label('My label', for_='fieldname')
<label for="fieldname">My label</label>
"""
if 'for_' in kwargs:
kwargs['for'] = kwargs.pop('for_')
return tag('label', open=True, **kwargs) + literal(value) + literal('</label>')
def select(name, selected, select_options, **attrs):
"""
Creates a dropdown selection box::
<select id="people" name="people">
<option value="George">George</option>
</select>
"""
if 'options' in attrs:
del attrs['options']
if select_options and isinstance(select_options[0], (list, tuple)):
select_options = [(v, k) for k, v in select_options]
_update_fa(attrs, name)
return tags.select(name, selected, select_options, **attrs)
def options_for_select(container, selected=None):
import warnings
warnings.warn(DeprecationWarning('options_for_select will be removed in FormAlchemy 2.5'))
if hasattr(container, 'values'):
container = container.items()
if not isinstance(selected, (list, tuple)):
selected = (selected,)
options = []
for elem in container:
if isinstance(elem, (list, tuple)):
name, value = elem
n = html_escape(name)
v = html_escape(value)
else :
name = value = elem
n = v = html_escape(elem)
if value in selected:
options.append('<option value="%s" selected="selected">%s</option>' % (v, n))
else :
options.append('<option value="%s">%s</option>' % (v, n))
return "\n".join(options)
def _update_fa(attrs, name):
if 'id' not in attrs:
attrs['id'] = name
if 'options' in attrs:
del attrs['options']
if __name__=="__main__":
import doctest
doctest.testmod()
| Python |
# -*- coding: utf-8 -*-
class PkError(Exception):
"""An exception raised when a primary key conflict occur"""
class ValidationError(Exception):
"""an exception raised when the validation failed
"""
@property
def message(self):
return self.args[0]
def __repr__(self):
return 'ValidationError(%r,)' % self.message
| Python |
# Copyright (C) 2007 Alexandre Conrad, alexandre (dot) conrad (at) gmail (dot) com
#
# This module is part of FormAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import cgi
import warnings
import logging
logger = logging.getLogger('formalchemy.' + __name__)
MIN_SA_VERSION = '0.4.5'
from sqlalchemy import __version__
if __version__.split('.') < MIN_SA_VERSION.split('.'):
raise ImportError('Version %s or later of SQLAlchemy required' % MIN_SA_VERSION)
from sqlalchemy.orm.attributes import InstrumentedAttribute
from sqlalchemy.orm.properties import SynonymProperty
from sqlalchemy.orm import compile_mappers, object_session, class_mapper
from sqlalchemy.orm.session import Session
from sqlalchemy.orm.scoping import ScopedSession
from sqlalchemy.orm.dynamic import DynamicAttributeImpl
from sqlalchemy.util import OrderedDict
try:
from sqlalchemy.orm.exc import UnmappedInstanceError
except ImportError:
class UnmappedInstanceError(Exception):
"""
Exception to provide support for sqlalchemy < 0.6
"""
import fields, fatypes
compile_mappers() # initializes InstrumentedAttributes
try:
# 0.5
from sqlalchemy.orm.attributes import manager_of_class
def _get_attribute(cls, p):
manager = manager_of_class(cls)
return manager[p.key]
except ImportError:
# 0.4
def _get_attribute(cls, p):
return getattr(cls, p.key)
def prettify(text):
"""
Turn an attribute name into something prettier, for a default label where none is given.
>>> prettify("my_column_name")
'My column name'
"""
return text.replace("_", " ").capitalize()
class SimpleMultiDict(dict):
"""
Adds `getone`, `getall` methods to dict. Assumes that values are either
a string or a list of strings.
"""
def getone(self, key):
if key not in self:
raise KeyError(key)
v = dict.get(self, key)
if v is None or isinstance(v, basestring) or isinstance(v, cgi.FieldStorage):
return v
return v[0]
def getall(self, key):
v = dict.get(self, key)
if v is None:
return []
elif isinstance(v, basestring):
return [v]
return v
class ModelRenderer(object):
"""
The `ModelRenderer` class is the superclass for all classes needing to deal
with `model` access and supporting rendering capabilities.
"""
prettify = staticmethod(prettify)
def __init__(self, model, session=None, data=None, prefix=None):
"""
- `model`:
a SQLAlchemy mapped class or instance. New object creation
should be done by passing the class, which will need a default
(no-parameter) constructor. After construction or binding of
the :class:`~formalchemy.forms.FieldSet`, the instantiated object will be available as
the `.model` attribute.
- `session=None`:
the session to use for queries (for relations). If `model` is associated
with a session, that will be used by default. (Objects mapped with a
`scoped_session
<http://www.sqlalchemy.org/docs/05/session.html#contextual-thread-local-sessions>`_
will always have a session. Other objects will
also have a session if they were loaded by a Query.)
- `data=None`:
dictionary-like object of user-submitted data to validate and/or
sync to the `model`. Scalar attributes should have a single
value in the dictionary; multi-valued relations should have a
list, even if there are zero or one values submitted. Currently,
pylons request.params() objects and plain dictionaries are known
to work.
- `prefix=None`:
the prefix to prepend to html name attributes. This is useful to avoid
field name conflicts when there are two fieldsets creating objects
from the same model in one html page. (This is not needed when
editing existing objects, since the object primary key is used as part
of the field name.)
Only the `model` parameter is required.
After binding, :class:`~formalchemy.forms.FieldSet`'s `model` attribute will always be an instance.
If you bound to a class, `FormAlchemy` will call its constructor with no
arguments to create an appropriate instance.
.. NOTE::
This instance will not be added to the current session, even if you are using `Session.mapper`.
All of these parameters may be overridden by the `bind` or `rebind`
methods. The `bind` method returns a new instance bound as specified,
while `rebind` modifies the current :class:`~formalchemy.forms.FieldSet` and has
no return value. (You may not `bind` to a different type of SQLAlchemy
model than the initial one -- if you initially bind to a `User`, you
must subsequently bind `User`'s to that :class:`~formalchemy.forms.FieldSet`.)
Typically, you will configure a :class:`~formalchemy.forms.FieldSet` once in
your common form library, then `bind` specific instances later for editing. (The
`bind` method is thread-safe; `rebind` is not.) Thus:
load stuff:
>>> from formalchemy.tests import FieldSet, User, session
now, in `library.py`
>>> fs = FieldSet(User)
>>> fs.configure(options=[]) # put all configuration stuff here
and in `controller.py`
>>> from library import fs
>>> user = session.query(User).first()
>>> fs2 = fs.bind(user)
>>> html = fs2.render()
The `render_fields` attribute is an OrderedDict of all the `Field`'s
that have been configured, keyed by name. The order of the fields
is the order in `include`, or the order they were declared
in the SQLAlchemy model class if no `include` is specified.
The `_fields` attribute is an OrderedDict of all the `Field`'s
the ModelRenderer knows about, keyed by name, in their
unconfigured state. You should not normally need to access
`_fields` directly.
(Note that although equivalent `Field`'s (fields referring to
the same attribute on the SQLAlchemy model) will equate with
the == operator, they are NOT necessarily the same `Field`
instance. Stick to referencing `Field`'s from their parent
`FieldSet` to always get the "right" instance.)
"""
self._fields = OrderedDict()
self._render_fields = OrderedDict()
self.model = self.session = None
self.prefix = prefix
if not model:
raise Exception('model parameter may not be None')
self._original_cls = isinstance(model, type) and model or type(model)
ModelRenderer.rebind(self, model, session, data)
cls = isinstance(self.model, type) and self.model or type(self.model)
try:
class_mapper(cls)
except:
# this class is not managed by SA. extract any raw Fields defined on it.
keys = cls.__dict__.keys()
keys.sort(lambda a, b: cmp(a.lower(), b.lower())) # 2.3 support
for key in keys:
field = cls.__dict__[key]
if isinstance(field, fields.Field):
if field.name and field.name != key:
raise Exception('Fields in a non-mapped class have the same name as their attribute. Do not manually give them a name.')
field.name = field.key = key
self.append(field)
if not self._fields:
raise Exception("not bound to a SA instance, and no manual Field definitions found")
else:
# SA class.
# load synonyms so we can ignore them
synonyms = set(p for p in class_mapper(cls).iterate_properties
if isinstance(p, SynonymProperty))
# load discriminators so we can ignore them
discs = set(p for p in class_mapper(cls).iterate_properties
if hasattr(p, '_is_polymorphic_discriminator')
and p._is_polymorphic_discriminator)
# attributes we're interested in
attrs = []
for p in class_mapper(cls).iterate_properties:
attr = _get_attribute(cls, p)
if ((isinstance(p, SynonymProperty) or attr.property.key not in (s.name for s in synonyms))
and not isinstance(attr.impl, DynamicAttributeImpl)
and p not in discs):
attrs.append(attr)
# sort relations last before storing in the OrderedDict
L = [fields.AttributeField(attr, self) for attr in attrs]
L.sort(lambda a, b: cmp(a.is_relation, b.is_relation)) # note, key= not used for 2.3 support
self._fields.update((field.key, field) for field in L)
def append(self, field):
"""Add a form Field. By default, this Field will be included in the rendered form or table."""
if not isinstance(field, fields.Field) and not isinstance(field, fields.AttributeField):
raise ValueError('Can only add Field or AttributeField objects; got %s instead' % field)
field.parent = self
_fields = self._render_fields or self._fields
_fields[field.name] = field
def add(self, field):
warnings.warn(DeprecationWarning('FieldSet.add is deprecated. Use FieldSet.append instead. Your validator will break in FA 1.5'))
self.append(field)
def extend(self, fields):
"""Add a list of fields. By default, each Field will be included in the
rendered form or table."""
for field in fields:
self.append(field)
def insert(self, field, new_field):
"""Insert a new field *before* an existing field.
This is like the normal ``insert()`` function of ``list`` objects. It
takes the place of the previous element, and pushes the rest forward.
"""
fields_ = self._render_fields or self._fields
if not isinstance(new_field, fields.Field):
raise ValueError('Can only add Field objects; got %s instead' % field)
if isinstance(field, fields.AbstractField):
try:
index = fields_.keys().index(field.name)
except ValueError:
raise ValueError('%s not in fields' % field.name)
else:
raise TypeError('field must be a Field. Got %r' % field)
new_field.parent = self
items = list(fields_.iteritems()) # prepare for Python 3
items.insert(index, (new_field.name, new_field))
if self._render_fields:
self._render_fields = OrderedDict(items)
else:
self._fields = OrderedDict(items)
def insert_after(self, field, new_field):
"""Insert a new field *after* an existing field.
Use this if your business logic requires to add after a certain field,
and not before.
"""
fields_ = self._render_fields or self._fields
if not isinstance(new_field, fields.Field):
raise ValueError('Can only add Field objects; got %s instead' % field)
if isinstance(field, fields.AbstractField):
try:
index = fields_.keys().index(field.name)
except ValueError:
raise ValueError('%s not in fields' % field.name)
else:
raise TypeError('field must be a Field. Got %r' % field)
new_field.parent = self
items = list(fields_.iteritems())
new_item = (new_field.name, new_field)
if index + 1 == len(items): # after the last element ?
items.append(new_item)
else:
items.insert(index + 1, new_item)
if self._render_fields:
self._render_fields = OrderedDict(items)
else:
self._fields = OrderedDict(items)
@property
def render_fields(self):
"""
The set of attributes that will be rendered, as a (ordered)
dict of `{fieldname: Field}` pairs
"""
if not self._render_fields:
self._render_fields = OrderedDict([(field.key, field) for field in self._get_fields()])
return self._render_fields
def configure(self, pk=False, exclude=[], include=[], options=[]):
"""
The `configure` method specifies a set of attributes to be rendered.
By default, all attributes are rendered except primary keys and
foreign keys. But, relations `based on` foreign keys `will` be
rendered. For example, if an `Order` has a `user_id` FK and a `user`
relation based on it, `user` will be rendered (as a select box of
`User`'s, by default) but `user_id` will not.
Parameters:
* `pk=False`:
set to True to include primary key columns
* `exclude=[]`:
an iterable of attributes to exclude. Other attributes will
be rendered normally
* `include=[]`:
an iterable of attributes to include. Other attributes will
not be rendered
* `options=[]`:
an iterable of modified attributes. The set of attributes to
be rendered is unaffected
* `global_validator=None`:
global_validator` should be a function that performs
validations that need to know about the entire form.
* `focus=True`:
the attribute (e.g., `fs.orders`) whose rendered input element
gets focus. Default value is True, meaning, focus the first
element. False means do not focus at all.
Only one of {`include`, `exclude`} may be specified.
Note that there is no option to include foreign keys. This is
deliberate. Use `include` if you really need to manually edit FKs.
If `include` is specified, fields will be rendered in the order given
in `include`. Otherwise, fields will be rendered in alphabetical
order.
Examples: given a `FieldSet` `fs` bound to a `User` instance as a
model with primary key `id` and attributes `name` and `email`, and a
relation `orders` of related Order objects, the default will be to
render `name`, `email`, and `orders`. To render the orders list as
checkboxes instead of a select, you could specify::
>>> from formalchemy.tests import FieldSet, User
>>> fs = FieldSet(User)
>>> fs.configure(options=[fs.orders.checkbox()])
To render only name and email,
>>> fs.configure(include=[fs.name, fs.email])
or
>>> fs.configure(exclude=[fs.orders])
Of course, you can include modifications to a field in the `include`
parameter, such as here, to render name and options-as-checkboxes:
>>> fs.configure(include=[fs.name, fs.orders.checkbox()])
"""
self._render_fields = OrderedDict([(field.key, field) for field in self._get_fields(pk, exclude, include, options)])
def bind(self, model=None, session=None, data=None):
"""
Return a copy of this FieldSet or Grid, bound to the given
`model`, `session`, and `data`. The parameters to this method are the
same as in the constructor.
Often you will create and `configure` a FieldSet or Grid at application
startup, then `bind` specific instances to it for actual editing or display.
"""
if not (model or session or data):
raise Exception('must specify at least one of {model, session, data}')
if not model:
if not self.model:
raise Exception('model must be specified when none is already set')
model = fields._pk(self.model) is None and type(self.model) or self.model
# copy.copy causes a stacktrace on python 2.5.2/OSX + pylons. unable to reproduce w/ simpler sample.
mr = object.__new__(self.__class__)
mr.__dict__ = dict(self.__dict__)
# two steps so bind's error checking can work
ModelRenderer.rebind(mr, model, session, data)
mr._fields = OrderedDict([(key, renderer.bind(mr)) for key, renderer in self._fields.iteritems()])
if self._render_fields:
mr._render_fields = OrderedDict([(field.key, field) for field in
[field.bind(mr) for field in self._render_fields.itervalues()]])
return mr
def copy(self, *args):
"""return a copy of the fieldset. args is a list of field names or field
objects to render in the new fieldset"""
mr = self.bind(self.model, self.session, self.data)
_fields = self._render_fields or self._fields
_new_fields = []
if args:
for field in args:
if isinstance(field, basestring):
if field in _fields:
field = _fields.get(field)
else:
raise AttributeError('%r as not field named %s' % (self, field))
assert isinstance(field, fields.AbstractField), field
field.bind(mr)
_new_fields.append(field)
mr._render_fields = OrderedDict([(field.key, field) for field in _new_fields])
return mr
def rebind(self, model=None, session=None, data=None):
"""
Like `bind`, but acts on this instance. No return value.
Not all parameters are treated the same; specifically, what happens if they are NOT specified is different:
* if `model` is not specified, the old model is used
* if `session` is not specified, FA tries to re-guess session from the model
* if data is not specified, it is rebound to None.
"""
original_model = model
if model:
if isinstance(model, type):
try:
model = model()
except Exception, e:
model_error = str(e)
msg = ("%s appears to be a class, not an instance, but "
"FormAlchemy cannot instantiate it. "
"(Make sure all constructor parameters are "
"optional!). The error was:\n%s")
raise Exception(msg % (model, model_error))
# take object out of session, if present
try:
_obj_session = object_session(model)
except (AttributeError, UnmappedInstanceError):
pass # non-SA object; doesn't need session
else:
if _obj_session:
_obj_session.expunge(model)
else:
try:
session_ = object_session(model)
except:
# non SA class
if fields._pk(model) is None:
error = ('Mapped instances to be bound must either have '
'a primary key set or not be in a Session. When '
'creating a new object, bind the class instead '
'[i.e., bind(User), not bind(User())]')
raise Exception(error)
else:
if session_:
# for instances of mapped classes, require that the instance
# have a PK already
try:
class_mapper(type(model))
except:
pass
else:
if fields._pk(model) is None:
error = ('Mapped instances to be bound must either have '
'a primary key set or not be in a Session. When '
'creating a new object, bind the class instead '
'[i.e., bind(User), not bind(User())]')
raise Exception(error)
if (self.model and type(self.model) != type(model) and
not issubclass(model.__class__, self._original_cls)):
raise ValueError('You can only bind to another object of the same type or subclass you originally bound to (%s), not %s' % (type(self.model), type(model)))
self.model = model
self._bound_pk = fields._pk(model)
if data is None:
self.data = None
elif hasattr(data, 'getall') and hasattr(data, 'getone'):
self.data = data
else:
try:
self.data = SimpleMultiDict(data)
except:
raise Exception('unsupported data object %s. currently only dicts and Paste multidicts are supported' % self.data)
if session:
if not isinstance(session, Session) and not isinstance(session, ScopedSession):
raise ValueError('Invalid SQLAlchemy session object %s' % session)
self.session = session
elif model:
if '_obj_session' in locals():
# model may be a temporary object, expunged from its session -- grab the existing reference
self.session = _obj_session
else:
try:
o_session = object_session(model)
except (AttributeError, UnmappedInstanceError):
pass # non-SA object
else:
if o_session:
self.session = o_session
# if we didn't just instantiate (in which case object_session will be None),
# the session should be the same as the object_session
if self.session and model == original_model:
try:
o_session = object_session(self.model)
except (AttributeError, UnmappedInstanceError):
pass # non-SA object
else:
if o_session and self.session is not o_session:
raise Exception('You may not explicitly bind to a session when your model already belongs to a different one')
def sync(self):
"""
Sync (copy to the corresponding attributes) the data passed to the constructor or `bind` to the `model`.
"""
if self.data is None:
raise Exception("No data bound; cannot sync")
for field in self.render_fields.itervalues():
field.sync()
if self.session:
self.session.add(self.model)
def _raw_fields(self):
return self._fields.values()
def _get_fields(self, pk=False, exclude=[], include=[], options=[]):
# sanity check
if include and exclude:
raise Exception('Specify at most one of include, exclude')
# help people who meant configure(include=[X]) but just wrote configure(X), resulting in pk getting the positional argument
if pk not in [True, False]:
raise ValueError('pk option must be True or False, not %s' % pk)
# verify that options that should be lists of Fields, are
for iterable in ['include', 'exclude', 'options']:
try:
L = list(eval(iterable))
except:
raise ValueError('`%s` parameter should be an iterable' % iterable)
for field in L:
if not isinstance(field, fields.AbstractField):
raise TypeError('non-AbstractField object `%s` found in `%s`' % (field, iterable))
if field not in self._fields.values():
raise ValueError('Unrecognized Field `%s` in `%s` -- did you mean to call append() first?' % (field, iterable))
# if include is given, those are the fields used. otherwise, include those not explicitly (or implicitly) excluded.
if not include:
ignore = list(exclude) # don't modify `exclude` directly to avoid surprising caller
if not pk:
ignore.extend([wrapper for wrapper in self._raw_fields() if wrapper.is_pk and not wrapper.is_collection])
ignore.extend([wrapper for wrapper in self._raw_fields() if wrapper.is_raw_foreign_key])
include = [field for field in self._raw_fields() if field not in ignore]
# in the returned list, replace any fields in `include` w/ the corresponding one in `options`, if present.
# this is a bit clunky because we want to
# 1. preserve the order given in `include`
# 2. not modify `include` (or `options`) directly; that could surprise the caller
options_dict = {} # create + update for 2.3's benefit
options_dict.update(dict([(wrapper, wrapper) for wrapper in options]))
L = []
for wrapper in include:
if wrapper in options_dict:
L.append(options_dict[wrapper])
else:
L.append(wrapper)
return L
def __getattr__(self, attrname):
try:
return self._render_fields[attrname]
except KeyError:
try:
return self._fields[attrname]
except KeyError:
raise AttributeError(attrname)
__getitem__ = __getattr__
def __setattr__(self, attrname, value):
if attrname not in ('_fields', '__dict__', 'focus', 'model', 'session', 'data') and \
(attrname in self._fields or isinstance(value, fields.AbstractField)):
raise AttributeError('Do not set field attributes manually. Use append() or configure() instead')
object.__setattr__(self, attrname, value)
def __delattr__(self, attrname):
if attrname in self._render_fields:
del self._render_fields[attrname]
elif attrname in self._fields:
raise RuntimeError("You try to delete a field but your form is not configured")
else:
raise AttributeError("field %s does not exist" % attrname)
__delitem__ = __delattr__
def render(self, **kwargs):
raise NotImplementedError()
class EditableRenderer(ModelRenderer):
default_renderers = {
fatypes.String: fields.TextFieldRenderer,
fatypes.Unicode: fields.TextFieldRenderer,
fatypes.Text: fields.TextFieldRenderer,
fatypes.Integer: fields.IntegerFieldRenderer,
fatypes.Float: fields.FloatFieldRenderer,
fatypes.Numeric: fields.FloatFieldRenderer,
fatypes.Interval: fields.IntervalFieldRenderer,
fatypes.Boolean: fields.CheckBoxFieldRenderer,
fatypes.DateTime: fields.DateTimeFieldRenderer,
fatypes.Date: fields.DateFieldRenderer,
fatypes.Time: fields.TimeFieldRenderer,
fatypes.LargeBinary: fields.FileFieldRenderer,
fatypes.List: fields.SelectFieldRenderer,
fatypes.Set: fields.SelectFieldRenderer,
'dropdown': fields.SelectFieldRenderer,
'checkbox': fields.CheckBoxSet,
'radio': fields.RadioSet,
'password': fields.PasswordFieldRenderer,
'textarea': fields.TextAreaFieldRenderer,
}
| Python |
# Copyright (C) 2007 Alexandre Conrad, alexandre (dot) conrad (at) gmail (dot) com
#
# This module is part of FormAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from formalchemy import templates
from formalchemy import config
from formalchemy.base import SimpleMultiDict
from formalchemy.tables import *
from formalchemy.forms import *
from formalchemy.fields import *
from formalchemy.validators import ValidationError
import formalchemy.validators as validators
import formalchemy.fatypes as types
__all__ = ["FieldSet", "AbstractFieldSet", "Field", "FieldRenderer", "Grid", "form_data", "ValidationError", "validators", "SimpleMultiDict", "types"]
__version__ = "1.3.6"
| Python |
# This module is part of FormAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from sqlalchemy.types import TypeEngine, Integer, Float, String, Unicode, Text, Boolean, Date, DateTime, Time, Numeric, Interval
try:
from sqlalchemy.types import LargeBinary
except ImportError:
# SA < 0.6
from sqlalchemy.types import Binary as LargeBinary
sa_types = set([Integer, Float, String, Unicode, Text, LargeBinary, Boolean, Date, DateTime, Time, Numeric, Interval])
class List(TypeEngine):
def get_dbapi_type(self):
raise NotImplementedError()
class Set(TypeEngine):
def get_dbapi_type(self):
raise NotImplementedError()
| Python |
# Copyright (C) 2007 Alexandre Conrad, alexandre (dot) conrad (at) gmail (dot) com
#
# This module is part of FormAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import os
from gettext import GNUTranslations
i18n_path = os.path.join(os.path.dirname(__file__), 'i18n_resources')
try:
from pylons.i18n import get_lang
HAS_PYLONS = True
except:
HAS_PYLONS = False
if not HAS_PYLONS:
def get_lang(): return []
class _Translator(object):
"""dummy translator"""
def gettext(self, value):
return value
def get_translator(lang=None):
"""
return a GNUTranslations instance for `lang`::
>>> translator = get_translator('fr')
... assert translator.gettext('Remove') == 'Supprimer'
... assert translator.gettext('month_01') == 'Janvier'
>>> translator = get_translator('en')
... assert translator.gettext('Remove') == 'Remove'
... assert translator.gettext('month_01') == 'January'
"""
# get possible fallback languages
try:
langs = get_lang() or []
except TypeError:
# this occurs when Pylons is available and we are not in a valid thread
langs = []
# insert lang if provided
if lang and lang not in langs:
langs.insert(0, lang)
if not langs:
langs = ['en']
# get the first available catalog
for lang in langs:
filename = os.path.join(i18n_path, lang, 'LC_MESSAGES','formalchemy.mo')
if os.path.isfile(filename):
translations_path = os.path.join(i18n_path, lang, 'LC_MESSAGES','formalchemy.mo')
return GNUTranslations(open(translations_path, 'rb'))
# dummy translator
return _Translator()
def _(value):
"""dummy 'translator' to mark translation strings in python code"""
return value
# month translation
_('Year')
_('Month')
_('Day')
_('month_01')
_('month_02')
_('month_03')
_('month_04')
_('month_05')
_('month_06')
_('month_07')
_('month_08')
_('month_09')
_('month_10')
_('month_11')
_('month_12')
| 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.