One of the nifty things in FunFormKit is the easy-to-use validators, that can also do conversion. Since entering 50 megabytes in bytes is really hard to do, I wrote a simple converter to change '50M' into 52428800.
from FunFormKit.Form import *
from FunFormKit.Field import *
from FunFormKit.Validator import ValidatorConverter
import re
spaces = re.compile(' +')
class TrafficConverter(ValidatorConverter):
def convert(self, value):
scales = 'B', 'K', 'M', 'G', 'T'
value = spaces.sub('', value)
if value[-1] not in scales:
return value
unit = value[-1]
value = float(value[:-1])
c = 0
while scales[c] != unit:
c = c + 1
return value * (1024 ** c)
Then, when I set up my form, I just put it in the validators list for my traffic allocation field:
fields = [
TextField('allocation', size=10, maxLength=20,
validators = [TrafficConverter()]),
SubmitButton('submit',
description='Submit'),
]
formDef = FormDefinition('', # the form action
fields, name='form')
I'd previously written a function to pretty-print a bytes value into user-friendly descriptive, so I just use the friendly format when I display it in the field too:
def pretty_traffic(traffic, kilo = 1024.0):
scales = "B", "K", "M", "G", "T"
amount = int(traffic)
for scale in scales:
if amount < kilo:
return "%.3f%s" % (amount, scale)
amount = amount / kilo