PEP8 improvements white space here and there

I search with regexp ",[^\s-]" to spot missing space after comma. I also, add double break line in front of function or class. I change a couple of comparator in order to add space in front and after " == " for instance.
This commit is contained in:
BuhtigithuB
2014-04-24 12:25:34 -04:00
parent accc7bdf38
commit bc1e9b5c98
+128 -115
View File
@@ -41,13 +41,15 @@ try:
import gluon.settings as settings import gluon.settings as settings
is_gae = settings.global_settings.web2py_runtime_gae is_gae = settings.global_settings.web2py_runtime_gae
except ImportError: except ImportError:
is_gae = False # this is an assumption (if settings missing) is_gae = False # this is an assumption (if settings missing)
widget_class = re.compile('^\w*') widget_class = re.compile('^\w*')
def add_class(a,b):
def add_class(a, b):
return a+' '+b if a else b return a+' '+b if a else b
def represent(field, value, record): def represent(field, value, record):
f = field.represent f = field.represent
if not callable(f): if not callable(f):
@@ -83,18 +85,18 @@ def show_if(cond):
base = "%s_%s" % (cond.first.tablename, cond.first.name) base = "%s_%s" % (cond.first.tablename, cond.first.name)
if ((cond.op.__name__ == 'EQ' and cond.second == True) or if ((cond.op.__name__ == 'EQ' and cond.second == True) or
(cond.op.__name__ == 'NE' and cond.second == False)): (cond.op.__name__ == 'NE' and cond.second == False)):
return base,":checked" return base, ":checked"
if ((cond.op.__name__ == 'EQ' and cond.second == False) or if ((cond.op.__name__ == 'EQ' and cond.second == False) or
(cond.op.__name__ == 'NE' and cond.second == True)): (cond.op.__name__ == 'NE' and cond.second == True)):
return base,":not(:checked)" return base, ":not(:checked)"
if cond.op.__name__ == 'EQ': if cond.op.__name__ == 'EQ':
return base,"[value='%s']" % cond.second return base, "[value='%s']" % cond.second
if cond.op.__name__ == 'NE': if cond.op.__name__ == 'NE':
return base,"[value!='%s']" % cond.second return base, "[value!='%s']" % cond.second
if cond.op.__name__ == 'CONTAINS': if cond.op.__name__ == 'CONTAINS':
return base,"[value~='%s']" % cond.second return base, "[value~='%s']" % cond.second
if cond.op.__name__ == 'BELONGS' and isinstance(cond.second,(list,tuple)): if cond.op.__name__ == 'BELONGS' and isinstance(cond.second, (list, tuple)):
return base,','.join("[value='%s']" % (v) for v in cond.second) return base, ','.join("[value='%s']" % (v) for v in cond.second)
raise RuntimeError("Not Implemented Error") raise RuntimeError("Not Implemented Error")
@@ -124,7 +126,7 @@ class FormWidget(object):
_name=field.name, _name=field.name,
requires=field.requires, requires=field.requires,
) )
if getattr(field,'show_if',None): if getattr(field, 'show_if', None):
trigger, cond = show_if(field.show_if) trigger, cond = show_if(field.show_if)
attr['_data-show-trigger'] = trigger attr['_data-show-trigger'] = trigger
attr['_data-show-if'] = cond attr['_data-show-if'] = cond
@@ -191,9 +193,11 @@ class TimeWidget(StringWidget):
class DateWidget(StringWidget): class DateWidget(StringWidget):
_class = 'date' _class = 'date'
class DatetimeWidget(StringWidget): class DatetimeWidget(StringWidget):
_class = 'datetime' _class = 'datetime'
class TextWidget(FormWidget): class TextWidget(FormWidget):
_class = 'text' _class = 'text'
@@ -209,6 +213,7 @@ class TextWidget(FormWidget):
attr = cls._attributes(field, default, **attributes) attr = cls._attributes(field, default, **attributes)
return TEXTAREA(**attr) return TEXTAREA(**attr)
class JSONWidget(FormWidget): class JSONWidget(FormWidget):
_class = 'json' _class = 'json'
@@ -226,6 +231,7 @@ class JSONWidget(FormWidget):
attr = cls._attributes(field, default, **attributes) attr = cls._attributes(field, default, **attributes)
return TEXTAREA(**attr) return TEXTAREA(**attr)
class BooleanWidget(FormWidget): class BooleanWidget(FormWidget):
_class = 'boolean' _class = 'boolean'
@@ -294,7 +300,7 @@ class ListWidget(StringWidget):
_class = 'string' _class = 'string'
requires = field.requires if isinstance( requires = field.requires if isinstance(
field.requires, (IS_NOT_EMPTY, IS_LIST_OF)) else None field.requires, (IS_NOT_EMPTY, IS_LIST_OF)) else None
if isinstance(value,str): value = [value] if isinstance(value, str): value = [value]
nvalue = value or [''] nvalue = value or ['']
items = [LI(INPUT(_id=_id, _class=_class, _name=_name, items = [LI(INPUT(_id=_id, _class=_class, _name=_name,
value=v, hideerror=k < len(nvalue) - 1, value=v, hideerror=k < len(nvalue) - 1,
@@ -335,7 +341,7 @@ class RadioWidget(OptionsWidget):
see also: `FormWidget.widget` see also: `FormWidget.widget`
""" """
if isinstance(value, (list,tuple)): if isinstance(value, (list, tuple)):
value = str(value[0]) value = str(value[0])
else: else:
value = str(value) value = str(value)
@@ -408,7 +414,7 @@ class CheckboxesWidget(OptionsWidget):
attr = cls._attributes(field, {}, **attributes) attr = cls._attributes(field, {}, **attributes)
attr['_class'] = add_class(attr.get('_class'), 'web2py_checkboxeswidget') attr['_class'] = add_class(attr.get('_class'), 'web2py_checkboxeswidget')
label = attr.get('label',True) label = attr.get('label', True)
requires = field.requires requires = field.requires
if not isinstance(requires, (list, tuple)): if not isinstance(requires, (list, tuple)):
@@ -449,7 +455,7 @@ class CheckboxesWidget(OptionsWidget):
requires=attr.get('requires', None), requires=attr.get('requires', None),
hideerror=True, _value=k, hideerror=True, _value=k,
value=r_value), value=r_value),
LABEL(v, _for='%s%s' % (field.name, k)) LABEL(v, _for='%s%s' % (field.name, k))
if label else '')) if label else ''))
opts.append(child(tds)) opts.append(child(tds))
@@ -522,7 +528,7 @@ class UploadWidget(FormWidget):
download_url: url for the file download (default = None) download_url: url for the file download (default = None)
""" """
default = dict(_type='file',) default = dict(_type='file', )
attr = cls._attributes(field, default, **attributes) attr = cls._attributes(field, default, **attributes)
inp = INPUT(**attr) inp = INPUT(**attr)
@@ -555,7 +561,7 @@ class UploadWidget(FormWidget):
else: else:
inp = DIV(inp, inp = DIV(inp,
SPAN('[', SPAN('[',
A(current.T(cls.GENERIC_DESCRIPTION),_href=url), A(current.T(cls.GENERIC_DESCRIPTION), _href=url),
']', _style='white-space:nowrap'), ']', _style='white-space:nowrap'),
br, image) br, image)
return inp return inp
@@ -814,6 +820,7 @@ def formstyle_bootstrap(form, fields):
parent.append(DIV(label, _controls, _class='control-group', _id=id)) parent.append(DIV(label, _controls, _class='control-group', _id=id))
return parent return parent
def formstyle_bootstrap3(form, fields): def formstyle_bootstrap3(form, fields):
""" bootstrap 3 format form layout """ bootstrap 3 format form layout
@@ -865,7 +872,7 @@ def formstyle_bootstrap3(form, fields):
if _submit: if _submit:
# submit button has unwrapped label and controls, different class # submit button has unwrapped label and controls, different class
parent.append(DIV(label, DIV(controls,_class="col-lg-4 col-lg-offset-2"), _class='form-group', _id=id)) parent.append(DIV(label, DIV(controls, _class="col-lg-4 col-lg-offset-2"), _class='form-group', _id=id))
# unflag submit (possible side effect) # unflag submit (possible side effect)
_submit = False _submit = False
else: else:
@@ -1224,7 +1231,7 @@ class SQLFORM(FORM):
css = 'delete' css = 'delete'
for f in self.table.fields: for f in self.table.fields:
on_del = self.table[f].ondelete on_del = self.table[f].ondelete
if isinstance(on_del,str) and 'cascade' in on_del.lower(): if isinstance(on_del, str) and 'cascade' in on_del.lower():
css += ' cascade_delete' css += ' cascade_delete'
break break
widget = INPUT(_type='checkbox', widget = INPUT(_type='checkbox',
@@ -1286,7 +1293,7 @@ class SQLFORM(FORM):
for id, a, b, c in xfields: for id, a, b, c in xfields:
newrows = formstyle(id, a, b, c) newrows = formstyle(id, a, b, c)
self.field_parent[id] = getattr(b, 'parent', None) \ self.field_parent[id] = getattr(b, 'parent', None) \
if isinstance(b,XmlComponent) else None if isinstance(b, XmlComponent) else None
if type(newrows).__name__ != "tuple": if type(newrows).__name__ != "tuple":
newrows = [newrows] newrows = [newrows]
for newrow in newrows: for newrow in newrows:
@@ -1295,7 +1302,7 @@ class SQLFORM(FORM):
table = formstyle(self, xfields) table = formstyle(self, xfields)
for id, a, b, c in xfields: for id, a, b, c in xfields:
self.field_parent[id] = getattr(b, 'parent', None) \ self.field_parent[id] = getattr(b, 'parent', None) \
if isinstance(b,XmlComponent) else None if isinstance(b, XmlComponent) else None
else: else:
raise RuntimeError('formstyle not supported') raise RuntimeError('formstyle not supported')
return table return table
@@ -1727,7 +1734,7 @@ class SQLFORM(FORM):
else: else:
ftype = field.type.split(' ')[0] ftype = field.type.split(' ')[0]
if ftype.startswith('decimal'): ftype = 'double' if ftype.startswith('decimal'): ftype = 'double'
elif ftype=='bigint': ftype = 'integer' elif ftype == 'bigint': ftype = 'integer'
elif ftype.startswith('big-'): ftype = ftype[4:] elif ftype.startswith('big-'): ftype = ftype[4:]
# end # end
options = search_options.get(ftype, None) options = search_options.get(ftype, None)
@@ -1736,43 +1743,43 @@ class SQLFORM(FORM):
field.label, str) and T(field.label) or field.label field.label, str) and T(field.label) or field.label
selectfields.append(OPTION(label, _value=str(field))) selectfields.append(OPTION(label, _value=str(field)))
operators = SELECT(*[OPTION(T(option), _value=option) for option in options]) operators = SELECT(*[OPTION(T(option), _value=option) for option in options])
_id = "%s_%s" % (value_id,name) _id = "%s_%s" % (value_id, name)
if field.type == 'boolean': if field.type == 'boolean':
value_input = SQLFORM.widgets.boolean.widget(field,field.default,_id=_id) value_input = SQLFORM.widgets.boolean.widget(field, field.default, _id=_id)
elif field.type == 'double': elif field.type == 'double':
value_input = SQLFORM.widgets.double.widget(field,field.default,_id=_id) value_input = SQLFORM.widgets.double.widget(field, field.default, _id=_id)
elif field.type == 'time': elif field.type == 'time':
value_input = SQLFORM.widgets.time.widget(field,field.default,_id=_id) value_input = SQLFORM.widgets.time.widget(field, field.default, _id=_id)
elif field.type == 'date': elif field.type == 'date':
iso_format = {'_data-w2p_date_format' : '%Y-%m-%d'} iso_format = {'_data-w2p_date_format' : '%Y-%m-%d'}
value_input = SQLFORM.widgets.date.widget(field,field.default,_id=_id, **iso_format) value_input = SQLFORM.widgets.date.widget(field, field.default, _id=_id, **iso_format)
elif field.type == 'datetime': elif field.type == 'datetime':
iso_format = iso_format = {'_data-w2p_datetime_format' : '%Y-%m-%d %H:%M:%S'} iso_format = iso_format = {'_data-w2p_datetime_format' : '%Y-%m-%d %H:%M:%S'}
value_input = SQLFORM.widgets.datetime.widget(field,field.default,_id=_id, **iso_format) value_input = SQLFORM.widgets.datetime.widget(field, field.default, _id=_id, **iso_format)
elif (field.type.startswith('reference ') or elif (field.type.startswith('reference ') or
field.type.startswith('list:reference ')) and \ field.type.startswith('list:reference ')) and \
hasattr(field.requires,'options'): hasattr(field.requires, 'options'):
value_input = SELECT( value_input = SELECT(
*[OPTION(v, _value=k) *[OPTION(v, _value=k)
for k,v in field.requires.options()], for k, v in field.requires.options()],
**dict(_id=_id)) **dict(_id=_id))
elif field.type == 'integer' or \ elif field.type == 'integer' or \
field.type.startswith('reference ') or \ field.type.startswith('reference ') or \
field.type.startswith('list:integer') or \ field.type.startswith('list:integer') or \
field.type.startswith('list:reference '): field.type.startswith('list:reference '):
value_input = SQLFORM.widgets.integer.widget(field,field.default,_id=_id) value_input = SQLFORM.widgets.integer.widget(field, field.default, _id=_id)
else: else:
value_input = INPUT( value_input = INPUT(
_type='text', _id=_id, _class=field.type) _type='text', _id=_id, _class=field.type)
new_button = INPUT( new_button = INPUT(
_type="button", _value=T('New Search'), _class="btn btn-default", _title = T('Start building a new search'), _type="button", _value=T('New Search'), _class="btn btn-default", _title=T('Start building a new search'),
_onclick="%s_build_query('new','%s')" % (prefix,field)) _onclick="%s_build_query('new','%s')" % (prefix, field))
and_button = INPUT( and_button = INPUT(
_type="button", _value=T('+ And'), _class="btn btn-default", _title = T('Add this to the search as an AND term'), _type="button", _value=T('+ And'), _class="btn btn-default", _title=T('Add this to the search as an AND term'),
_onclick="%s_build_query('and','%s')" % (prefix, field)) _onclick="%s_build_query('and','%s')" % (prefix, field))
or_button = INPUT( or_button = INPUT(
_type="button", _value=T('+ Or'), _class="btn btn-default",_title = T('Add this to the search as an OR term'), _type="button", _value=T('+ Or'), _class="btn btn-default", _title=T('Add this to the search as an OR term'),
_onclick="%s_build_query('or','%s')" % (prefix, field)) _onclick="%s_build_query('or','%s')" % (prefix, field))
close_button = INPUT( close_button = INPUT(
_type="button", _value=T('Close'), _class="btn btn-default", _type="button", _value=T('Close'), _class="btn btn-default",
@@ -1786,8 +1793,8 @@ class SQLFORM(FORM):
_style='display:inline')) _style='display:inline'))
criteria.insert(0, SELECT( criteria.insert(0, SELECT(
_id=fields_id, _id=fields_id,
_onchange="jQuery('.w2p_query_row').hide();jQuery('#%s_'+jQuery('#%s').val().replace('.','-')).show();" % (field_id,fields_id), _onchange="jQuery('.w2p_query_row').hide();jQuery('#%s_'+jQuery('#%s').val().replace('.','-')).show();" % (field_id, fields_id),
_style='float:left', _style='float:left',
*selectfields)) *selectfields))
@@ -1805,14 +1812,13 @@ class SQLFORM(FORM):
if(aggregator=='new') k.val(s); else k.val((v?(v+' '+ aggregator +' '):'')+s); if(aggregator=='new') k.val(s); else k.val((v?(v+' '+ aggregator +' '):'')+s);
} }
""" % dict( """ % dict(
prefix=prefix,fields_id=fields_id,keywords_id=keywords_id, prefix=prefix, fields_id=fields_id, keywords_id=keywords_id,
field_id=field_id,value_id=value_id field_id=field_id, value_id=value_id
) )
) )
return CAT( return CAT(
DIV(_id=panel_id, _style="display:none;", *criteria), fadd) DIV(_id=panel_id, _style="display:none;", *criteria), fadd)
@staticmethod @staticmethod
def grid(query, def grid(query,
fields=None, fields=None,
@@ -1972,7 +1978,7 @@ class SQLFORM(FORM):
if user_signature: if user_signature:
if not ( if not (
'/'.join(str(a) for a in args) == '/'.join(request.args) or '/'.join(str(a) for a in args) == '/'.join(request.args) or
URL.verify(request,user_signature=user_signature, URL.verify(request, user_signature=user_signature,
hash_vars=False) or hash_vars=False) or
(request.args(len(args))=='view' and not logged)): (request.args(len(args))=='view' and not logged)):
session.flash = T('not authorized') session.flash = T('not authorized')
@@ -2001,7 +2007,7 @@ class SQLFORM(FORM):
_class=ui.get('buttontext'), _class=ui.get('buttontext'),
cid=request.cid) cid=request.cid)
dbset = db(query,ignore_common_filters=ignore_common_filters) dbset = db(query, ignore_common_filters=ignore_common_filters)
tablenames = db._adapter.tables(dbset.query) tablenames = db._adapter.tables(dbset.query)
if left is not None: if left is not None:
if not isinstance(left, (list, tuple)): if not isinstance(left, (list, tuple)):
@@ -2012,21 +2018,21 @@ class SQLFORM(FORM):
if fields: if fields:
#add missing tablename to virtual fields #add missing tablename to virtual fields
for table in tables: for table in tables:
for k,f in table.iteritems(): for k, f in table.iteritems():
if isinstance(f,Field.Virtual): if isinstance(f, Field.Virtual):
f.tablename = table._tablename f.tablename = table._tablename
columns = [f for f in fields if f.tablename in tablenames] columns = [f for f in fields if f.tablename in tablenames]
else: else:
fields = [] fields = []
columns = [] columns = []
filter1 = lambda f:isinstance(f,Field) filter1 = lambda f:isinstance(f, Field)
filter2 = lambda f:isinstance(f,Field) and f.readable filter2 = lambda f:isinstance(f, Field) and f.readable
for table in tables: for table in tables:
fields += filter(filter1, table) fields += filter(filter1, table)
columns += filter(filter2, table) columns += filter(filter2, table)
for k,f in table.iteritems(): for k, f in table.iteritems():
if not k.startswith('_'): if not k.startswith('_'):
if isinstance(f,Field.Virtual) and f.readable: if isinstance(f, Field.Virtual) and f.readable:
f.tablename = table._tablename f.tablename = table._tablename
fields.append(f) fields.append(f)
columns.append(f) columns.append(f)
@@ -2039,7 +2045,7 @@ class SQLFORM(FORM):
field_id = groupby.first #take the first groupby field field_id = groupby.first #take the first groupby field
table = field_id.table table = field_id.table
tablename = table._tablename tablename = table._tablename
if not any(str(f)==str(field_id) for f in fields): if not any(str(f) == str(field_id) for f in fields):
fields = [f for f in fields]+[field_id] fields = [f for f in fields]+[field_id]
if upload == '<default>': if upload == '<default>':
upload = lambda filename: url(args=['download', filename]) upload = lambda filename: url(args=['download', filename])
@@ -2069,8 +2075,8 @@ class SQLFORM(FORM):
def linsert(lst, i, x): def linsert(lst, i, x):
"""Internal use only: inserts x list into lst at i pos:: """Internal use only: inserts x list into lst at i pos::
a = [1,2] a = [1, 2]
linsert(a, 1, [0,3]) linsert(a, 1, [0, 3])
a = [1, 0, 3, 2] a = [1, 0, 3, 2]
""" """
lst[i:i] = x lst[i:i] = x
@@ -2174,14 +2180,14 @@ class SQLFORM(FORM):
redirect(referrer, client_side=client_side_delete) redirect(referrer, client_side=client_side_delete)
exportManager = dict( exportManager = dict(
csv_with_hidden_cols=(ExporterCSV_hidden, 'CSV (hidden cols)',T('Comma-separated export including columns not shown; fields from other tables are exported as raw values for faster export')), csv_with_hidden_cols=(ExporterCSV_hidden, 'CSV (hidden cols)', T('Comma-separated export including columns not shown; fields from other tables are exported as raw values for faster export')),
csv=(ExporterCSV, 'CSV',T('Comma-separated export of visible columns. Fields from other tables are exported as they appear on-screen but this may be slow for many rows')), csv=(ExporterCSV, 'CSV', T('Comma-separated export of visible columns. Fields from other tables are exported as they appear on-screen but this may be slow for many rows')),
xml=(ExporterXML, 'XML',T('XML export of columns shown')), xml=(ExporterXML, 'XML', T('XML export of columns shown')),
html=(ExporterHTML, 'HTML',T('HTML export of visible columns')), html=(ExporterHTML, 'HTML', T('HTML export of visible columns')),
json=(ExporterJSON, 'JSON',T('JSON export of visible columns')), json=(ExporterJSON, 'JSON', T('JSON export of visible columns')),
tsv_with_hidden_cols= tsv_with_hidden_cols=
(ExporterTSV, 'TSV (Spreadsheets, hidden cols)',T('Spreadsheet-optimised export of tab-separated content including hidden columns. May be slow')), (ExporterTSV, 'TSV (Spreadsheets, hidden cols)', T('Spreadsheet-optimised export of tab-separated content including hidden columns. May be slow')),
tsv=(ExporterTSV, 'TSV (Spreadsheets)',T('Spreadsheet-optimised export of tab-separated content, visible columns only. May be slow.'))) tsv=(ExporterTSV, 'TSV (Spreadsheets)', T('Spreadsheet-optimised export of tab-separated content, visible columns only. May be slow.')))
if not exportclasses is None: if not exportclasses is None:
""" """
remember: allow to set exportclasses=dict(csv=False, csv_with_hidden_cols=False) to disable the csv format remember: allow to set exportclasses=dict(csv=False, csv_with_hidden_cols=False) to disable the csv format
@@ -2202,20 +2208,20 @@ class SQLFORM(FORM):
orderby = (order[:1] == '~' and ~sort_field) or sort_field orderby = (order[:1] == '~' and ~sort_field) or sort_field
expcolumns = [str(f) for f in columns] expcolumns = [str(f) for f in columns]
selectable_columns = [str(f) for f in columns if not isinstance(f,Field.Virtual)] selectable_columns = [str(f) for f in columns if not isinstance(f, Field.Virtual)]
if export_type.endswith('with_hidden_cols'): if export_type.endswith('with_hidden_cols'):
#expcolumns = [] start with the visible columns, which includes visible virtual fields #expcolumns = [] start with the visible columns, which includes visible virtual fields
selectable_columns=[] #like expcolumns but excluding virtual selectable_columns = [] #like expcolumns but excluding virtual
for table in tables: for table in tables:
for field in table: for field in table:
if field.readable and field.tablename in tablenames: if field.readable and field.tablename in tablenames:
if not str(field) in expcolumns: if not str(field) in expcolumns:
expcolumns.append(str(field)) expcolumns.append(str(field))
if not(isinstance(field,Field.Virtual)): if not(isinstance(field, Field.Virtual)):
selectable_columns.append(str(field)) selectable_columns.append(str(field))
#look for virtual fields not displayed (and virtual method fields to be added here?) #look for virtual fields not displayed (and virtual method fields to be added here?)
for (field_name,field) in table.iteritems(): for (field_name, field) in table.iteritems():
if isinstance(field,Field.Virtual) and not str(field) in expcolumns: if isinstance(field, Field.Virtual) and not str(field) in expcolumns:
expcolumns.append(str(field)) expcolumns.append(str(field))
if export_type in exportManager and exportManager[export_type]: if export_type in exportManager and exportManager[export_type]:
@@ -2223,7 +2229,7 @@ class SQLFORM(FORM):
try: try:
#the query should be constructed using searchable fields but not virtual fields #the query should be constructed using searchable fields but not virtual fields
sfields = reduce(lambda a, b: a + b, sfields = reduce(lambda a, b: a + b,
[[f for f in t if f.readable and not isinstance(f,Field.Virtual)] for t in tables]) [[f for f in t if f.readable and not isinstance(f, Field.Virtual)] for t in tables])
dbset = dbset(SQLFORM.build_query( dbset = dbset(SQLFORM.build_query(
sfields, request.vars.get('keywords', ''))) sfields, request.vars.get('keywords', '')))
rows = dbset.select(left=left, orderby=orderby, rows = dbset.select(left=left, orderby=orderby,
@@ -2233,11 +2239,11 @@ class SQLFORM(FORM):
rows = [] rows = []
else: else:
rows = dbset.select(left=left, orderby=orderby, rows = dbset.select(left=left, orderby=orderby,
cacheable=True, *selectable_columns) cacheable=True, *selectable_columns)
value = exportManager[export_type] value = exportManager[export_type]
clazz = value[0] if hasattr(value, '__getitem__') else value clazz = value[0] if hasattr(value, '__getitem__') else value
rows.colnames = expcolumns # expcolumns is all cols to be exported including virtual fields rows.colnames = expcolumns # expcolumns is all cols to be exported including virtual fields
oExp = clazz(rows) oExp = clazz(rows)
filename = '.'.join(('rows', oExp.file_ext)) filename = '.'.join(('rows', oExp.file_ext))
response.headers['Content-Type'] = oExp.content_type response.headers['Content-Type'] = oExp.content_type
@@ -2373,17 +2379,17 @@ class SQLFORM(FORM):
not all([isinstance(link, dict) for link in links]))) not all([isinstance(link, dict) for link in links])))
if include_buttons_column: if include_buttons_column:
if buttons_placement in ['right', 'both']: if buttons_placement in ['right', 'both']:
headcols.append(TH(_class=ui.get('default',''))) headcols.append(TH(_class=ui.get('default', '')))
right_cols += 1 right_cols += 1
if buttons_placement in ['left', 'both']: if buttons_placement in ['left', 'both']:
headcols.insert(0, TH(_class=ui.get('default',''))) headcols.insert(0, TH(_class=ui.get('default', '')))
left_cols += 1 left_cols += 1
head = TR(*headcols, **dict(_class=ui.get('header'))) head = TR(*headcols, **dict(_class=ui.get('header')))
cursor = True cursor = True
#figure out what page we are one to setup the limitby #figure out what page we are one to setup the limitby
if paginate and dbset._db._adapter.dbengine=='google:datastore': if paginate and dbset._db._adapter.dbengine == 'google:datastore':
cursor = request.vars.cursor or True cursor = request.vars.cursor or True
limitby = (0, paginate) limitby = (0, paginate)
try: page = int(request.vars.page or 1)-1 try: page = int(request.vars.page or 1)-1
@@ -2391,22 +2397,22 @@ class SQLFORM(FORM):
elif paginate and paginate<nrows: elif paginate and paginate<nrows:
try: page = int(request.vars.page or 1)-1 try: page = int(request.vars.page or 1)-1
except ValueError: page = 0 except ValueError: page = 0
limitby = (paginate*page,paginate*(page+1)) limitby = (paginate*page, paginate*(page+1))
else: else:
limitby = None limitby = None
try: try:
table_fields = [field for field in fields table_fields = [field for field in fields
if (field.tablename in tablenames and not(isinstance(field,Field.Virtual)))] if (field.tablename in tablenames and not(isinstance(field, Field.Virtual)))]
if dbset._db._adapter.dbengine=='google:datastore': if dbset._db._adapter.dbengine == 'google:datastore':
rows = dbset.select(left=left,orderby=orderby, rows = dbset.select(left=left, orderby=orderby,
groupby=groupby,limitby=limitby, groupby=groupby, limitby=limitby,
reusecursor=cursor, reusecursor=cursor,
cacheable=True,*table_fields) cacheable=True, *table_fields)
next_cursor = dbset._db.get('_lastcursor', None) next_cursor = dbset._db.get('_lastcursor', None)
else: else:
rows = dbset.select(left=left,orderby=orderby, rows = dbset.select(left=left, orderby=orderby,
groupby=groupby,limitby=limitby, groupby=groupby, limitby=limitby,
cacheable=True,*table_fields) cacheable=True, *table_fields)
except SyntaxError: except SyntaxError:
rows = None rows = None
next_cursor = None next_cursor = None
@@ -2414,31 +2420,31 @@ class SQLFORM(FORM):
except Exception, e: except Exception, e:
rows = None rows = None
next_cursor = None next_cursor = None
error = T("Query Not Supported: %s")%e error = T("Query Not Supported: %s") % e
message = error message = error
if not message and nrows: if not message and nrows:
if dbset._db._adapter.dbengine=='google:datastore' and nrows>=1000: if dbset._db._adapter.dbengine == 'google:datastore' and nrows >= 1000:
message = T('at least %(nrows)s records found') % dict(nrows=nrows) message = T('at least %(nrows)s records found') % dict(nrows=nrows)
else: else:
message = T('%(nrows)s records found') % dict(nrows=nrows) message = T('%(nrows)s records found') % dict(nrows=nrows)
console.append(DIV(message or T('None'),_class='web2py_counter')) console.append(DIV(message or T('None'), _class='web2py_counter'))
paginator = UL() paginator = UL()
if paginate and dbset._db._adapter.dbengine=='google:datastore': if paginate and dbset._db._adapter.dbengine == 'google:datastore':
#this means we may have a large table with an unknown number of rows. #this means we may have a large table with an unknown number of rows.
try: try:
page = int(request.vars.page or 1)-1 page = int(request.vars.page or 1)-1
except ValueError: except ValueError:
page = 0 page = 0
paginator.append(LI('page %s'%(page+1))) paginator.append(LI('page %s' % (page+1)))
if next_cursor: if next_cursor:
d = dict(page=page+2, cursor=next_cursor) d = dict(page=page+2, cursor=next_cursor)
if order: d['order']=order if order: d['order'] = order
if request.vars.keywords: d['keywords']=request.vars.keywords if request.vars.keywords: d['keywords'] = request.vars.keywords
paginator.append(LI( paginator.append(LI(
A('next',_href=url(vars=d),cid=request.cid))) A('next', _href=url(vars=d), cid=request.cid)))
elif paginate and paginate<nrows: elif paginate and paginate < nrows:
npages, reminder = divmod(nrows, paginate) npages, reminder = divmod(nrows, paginate)
if reminder: if reminder:
npages += 1 npages += 1
@@ -2475,13 +2481,13 @@ class SQLFORM(FORM):
if rows: if rows:
cols = [COL(_id=str(c).replace('.', '-'), cols = [COL(_id=str(c).replace('.', '-'),
data={'column': left_cols + i + 1}) data={'column': left_cols + i + 1})
for i,c in enumerate(columns)] for i, c in enumerate(columns)]
cols = [COL(data={'column': i + 1}) for i in range(left_cols)] + \ cols = [COL(data={'column': i + 1}) for i in range(left_cols)] + \
cols + \ cols + \
[COL(data={'column': left_cols + len(cols) + i + 1}) [COL(data={'column': left_cols + len(cols) + i + 1})
for i in range(right_cols)] for i in range(right_cols)]
htmltable = TABLE(COLGROUP(*cols),THEAD(head)) htmltable = TABLE(COLGROUP(*cols), THEAD(head))
tbody = TBODY() tbody = TBODY()
numrec = 0 numrec = 0
for row in rows: for row in rows:
@@ -2490,7 +2496,7 @@ class SQLFORM(FORM):
if selectable: if selectable:
trcols.append( trcols.append(
INPUT(_type="checkbox", _name="records", _value=id, INPUT(_type="checkbox", _name="records", _value=id,
value=request.vars.records)) value=request.vars.records))
for field in columns: for field in columns:
if not field.readable: if not field.readable:
continue continue
@@ -2525,7 +2531,7 @@ class SQLFORM(FORM):
elif not isinstance(value, DIV): elif not isinstance(value, DIV):
value = field.formatter(value) value = field.formatter(value)
trcols.append(TD(value)) trcols.append(TD(value))
row_buttons = TD(_class='row_buttons',_nowrap=True) row_buttons = TD(_class='row_buttons', _nowrap=True)
if links and links_in_grid: if links and links_in_grid:
toadd = [] toadd = []
for link in links: for link in links:
@@ -2629,7 +2635,7 @@ class SQLFORM(FORM):
order=request.vars.order or '', order=request.vars.order or '',
_export_type=k, _export_type=k,
keywords=request.vars.keywords or '')) keywords=request.vars.keywords or ''))
export_links.append(A(T(label), _href=link,_title=title,_class='btn btn-default')) export_links.append(A(T(label), _href=link, _title=title, _class='btn btn-default'))
export_menu = \ export_menu = \
DIV(T('Export:'), _class="w2p_export_menu", *export_links) DIV(T('Export:'), _class="w2p_export_menu", *export_links)
else: else:
@@ -2670,15 +2676,15 @@ class SQLFORM(FORM):
Example: Example:
given you defined a model as:: given you defined a model as::
db.define_table('person',Field('name'),format='%(name)s') db.define_table('person', Field('name'), format='%(name)s')
db.define_table('dog', db.define_table('dog',
Field('name'),Field('owner',db.person),format='%(name)s') Field('name'), Field('owner', db.person), format='%(name)s')
db.define_table('comment',Field('body'),Field('dog',db.dog)) db.define_table('comment', Field('body'), Field('dog', db.dog))
if db(db.person).isempty(): if db(db.person).isempty():
from gluon.contrib.populate import populate from gluon.contrib.populate import populate
populate(db.person,300) populate(db.person, 300)
populate(db.dog,300) populate(db.dog, 300)
populate(db.comment,1000) populate(db.comment, 1000)
in a controller, you can do:: in a controller, you can do::
@@ -2708,10 +2714,11 @@ class SQLFORM(FORM):
constraints = {} constraints = {}
field = None field = None
name = None name = None
def format(table,row):
def format(table, row):
if not row: if not row:
return T('Unknown') return T('Unknown')
elif isinstance(table._format,str): elif isinstance(table._format, str):
return table._format % row return table._format % row
elif callable(table._format): elif callable(table._format):
return table._format(row) return table._format(row)
@@ -2743,7 +2750,7 @@ class SQLFORM(FORM):
raise HTTP(400) raise HTTP(400)
previous_tablename, previous_fieldname, previous_id = \ previous_tablename, previous_fieldname, previous_id = \
tablename, fieldname, id tablename, fieldname, id
name = format(db[referee],record) name = format(db[referee], record)
breadcrumbs.append( breadcrumbs.append(
LI(A(T(db[referee]._plural), LI(A(T(db[referee]._plural),
cid=request.cid, cid=request.cid,
@@ -2790,19 +2797,19 @@ class SQLFORM(FORM):
if linked_tables is None: if linked_tables is None:
linked_tables = db.tables() linked_tables = db.tables()
if isinstance(linked_tables, dict): if isinstance(linked_tables, dict):
linked_tables = linked_tables.get(table._tablename,[]) linked_tables = linked_tables.get(table._tablename, [])
if linked_tables: if linked_tables:
for item in linked_tables: for item in linked_tables:
tb = None tb = None
if isinstance(item,Table) and item._tablename in check: if isinstance(item, Table) and item._tablename in check:
tablename = item._tablename tablename = item._tablename
linked_fieldnames = check[tablename] linked_fieldnames = check[tablename]
tb = item tb = item
elif isinstance(item,str) and item in check: elif isinstance(item, str) and item in check:
tablename = item tablename = item
linked_fieldnames = check[item] linked_fieldnames = check[item]
tb = db[item] tb = db[item]
elif isinstance(item,Field) and item.name in check.get(item._tablename,[]): elif isinstance(item, Field) and item.name in check.get(item._tablename, []):
tablename = item._tablename tablename = item._tablename
linked_fieldnames = [item.name] linked_fieldnames = [item.name]
tb = item.table tb = item.table
@@ -2827,7 +2834,7 @@ class SQLFORM(FORM):
header = table._plural header = table._plural
next = grid.create_form or grid.update_form or grid.view_form next = grid.create_form or grid.update_form or grid.view_form
breadcrumbs.append(LI( breadcrumbs.append(LI(
A(T(header), cid=request.cid,_href=url()), A(T(header), cid=request.cid, _href=url()),
SPAN(divider, _class='divider') if next else '', SPAN(divider, _class='divider') if next else '',
_class='active w2p_grid_breadcrumb_elem')) _class='active w2p_grid_breadcrumb_elem'))
if grid.create_form: if grid.create_form:
@@ -2842,7 +2849,7 @@ class SQLFORM(FORM):
grid.view_form.record)) grid.view_form.record))
if next: if next:
breadcrumbs.append(LI( breadcrumbs.append(LI(
A(T(header), cid=request.cid,_href=url()), A(T(header), cid=request.cid, _href=url()),
_class='active w2p_grid_breadcrumb_elem')) _class='active w2p_grid_breadcrumb_elem'))
grid.insert( grid.insert(
0, DIV(UL(*breadcrumbs, **{'_class': breadcrumbs_class}), 0, DIV(UL(*breadcrumbs, **{'_class': breadcrumbs_class}),
@@ -2880,10 +2887,10 @@ class SQLTABLE(TABLE):
Extracolumns example Extracolumns example
:: ::
[{'label':A('Extra',_href='#'), [{'label':A('Extra', _href='#'),
'class': '', #class name of the header 'class': '', #class name of the header
'width':'', #width in pixels or % 'width':'', #width in pixels or %
'content':lambda row, rc: A('Edit',_href='edit/%s'%row.id), 'content':lambda row, rc: A('Edit', _href='edit/%s'%row.id),
'selected': False #agregate class selected to this column}] 'selected': False #agregate class selected to this column}]
@@ -2921,7 +2928,7 @@ class SQLTABLE(TABLE):
if headers == 'fieldname:capitalize': if headers == 'fieldname:capitalize':
headers = {} headers = {}
for c in columns: for c in columns:
(t,f) = REGEX_TABLE_DOT_FIELD.match(c).groups() (t, f) = REGEX_TABLE_DOT_FIELD.match(c).groups()
headers[t + '.' + f] = f.replace('_', ' ').title() headers[t + '.' + f] = f.replace('_', ' ').title()
elif headers == 'labels': elif headers == 'labels':
headers = {} headers = {}
@@ -2930,7 +2937,7 @@ class SQLTABLE(TABLE):
field = sqlrows.db[t][f] field = sqlrows.db[t][f]
headers[c] = field.label headers[c] = field.label
if colgroup: if colgroup:
cols = [COL(_id=c.replace('.', '-'), data={'column': i + 1}) cols = [COL(_id=c.replace('.', '-'), data={'column': i + 1})
for i, c in enumerate(columns)] for i, c in enumerate(columns)]
if extracolumns: if extracolumns:
cols += [COL(data={'column': len(cols) + i + 1}) cols += [COL(data={'column': len(cols) + i + 1})
@@ -3167,13 +3174,14 @@ class ExportClass(object):
def export(self): def export(self):
raise NotImplementedError raise NotImplementedError
class ExporterTSV(ExportClass): class ExporterTSV(ExportClass):
label = 'TSV' label = 'TSV'
file_ext = "csv" file_ext = "csv"
content_type = "text/tab-separated-values" content_type = "text/tab-separated-values"
def __init__(self, rows): def __init__(self, rows):
ExportClass.__init__(self,rows) ExportClass.__init__(self, rows)
def export(self): def export(self):
out = cStringIO.StringIO() out = cStringIO.StringIO()
@@ -3203,6 +3211,7 @@ class ExporterTSV(ExportClass):
out.truncate(0) out.truncate(0)
return str(final.getvalue()) return str(final.getvalue())
class ExporterCSV(ExportClass): class ExporterCSV(ExportClass):
#CSV, represent == True #CSV, represent == True
label = 'CSV' label = 'CSV'
@@ -3215,11 +3224,12 @@ class ExporterCSV(ExportClass):
def export(self): #export CSV with rows.represent def export(self): #export CSV with rows.represent
if self.rows: if self.rows:
s = cStringIO.StringIO() s = cStringIO.StringIO()
self.rows.export_to_csv_file(s,represent=True) self.rows.export_to_csv_file(s, represent=True)
return s.getvalue() return s.getvalue()
else: else:
return None return None
class ExporterCSV_hidden(ExportClass): class ExporterCSV_hidden(ExportClass):
#pure csv, no represent. #pure csv, no represent.
label = 'CSV' label = 'CSV'
@@ -3227,7 +3237,7 @@ class ExporterCSV_hidden(ExportClass):
content_type = "text/csv" content_type = "text/csv"
def __init__(self, rows): def __init__(self, rows):
ExportClass.__init__(self,rows) ExportClass.__init__(self, rows)
def export(self): def export(self):
if self.rows: if self.rows:
@@ -3235,6 +3245,7 @@ class ExporterCSV_hidden(ExportClass):
else: else:
return '' return ''
class ExporterHTML(ExportClass): class ExporterHTML(ExportClass):
label = 'HTML' label = 'HTML'
file_ext = "html" file_ext = "html"
@@ -3247,6 +3258,7 @@ class ExporterHTML(ExportClass):
xml = self.rows.xml() if self.rows else '' xml = self.rows.xml() if self.rows else ''
return '<html>\n<head>\n<meta http-equiv="content-type" content="text/html; charset=UTF-8" />\n</head>\n<body>\n%s\n</body>\n</html>' % (xml or '') return '<html>\n<head>\n<meta http-equiv="content-type" content="text/html; charset=UTF-8" />\n</head>\n<body>\n%s\n</body>\n</html>' % (xml or '')
class ExporterXML(ExportClass): class ExporterXML(ExportClass):
label = 'XML' label = 'XML'
file_ext = "xml" file_ext = "xml"
@@ -3261,6 +3273,7 @@ class ExporterXML(ExportClass):
else: else:
return '<rows></rows>' return '<rows></rows>'
class ExporterJSON(ExportClass): class ExporterJSON(ExportClass):
label = 'JSON' label = 'JSON'
file_ext = "json" file_ext = "json"