Exemple #1
0
    def GET(self):
        try:
            posts=db.posts
            query=posts.find({"user":web.cookies().user})
            form_reg_editar = form.Form(
                form.Textbox('nombre', form.notnull, form.regexp('^[A-Z, a-z]', 'No hay nadie en el mundo cuyo nombre tenga números.¡Use letras!'), description="Nombre", value=query[0]["nombre"]),
                form.Textbox('apellidos', form.notnull, form.regexp('^[A-Z, a-z]', 'No hay nadie en el mundo cuyo apellido tenga números.¡Use letras!'), description="Apellido", value=query[0]["apellidos"]),
                form.Textbox('correo', form.notnull,  form.regexp('^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$', 'Introduzca un correo válido'), description="Correo electrónico", value=query[0]["correo"]),

                form.Dropdown('dias', dias, description="Dia", value=int(query[0]["dia"])),
                form.Dropdown('meses', meses, description="Mes", value=int(query[0]["mes"])),
                form.Dropdown('anios', anios, description="Anio", value=int(query[0]["anio"])),

                form.Textarea('direccion', form.notnull,  description="Dirección", value=query[0]["direccion"]),
                form.Password('clave', form.notnull, description="Contraseña", value=query[0]["password"]),
                form.Password('clave2', form.notnull, description="Repetir contraseña", value=query[0]["password"]),
                form.Radio('pago', ['Contra reembolso', 'Tarjeta VISA'], description="Forma de pago", value=query[0]["pago"]),
                form.Textbox('visa', form.regexp('((\d{4})[\-,\s](\d{4})[\-,\s](\d{4})[\-,\s](\d{4}))', 'Introduzca un número de tarjeta VISA válido'), description="Tarjeta VISA", value=query[0]["visa"]),
                form.Button('Editar'),
                validators = [form.Validator("Fecha de nacimiento no válida.", lambda i: (((int(i.meses) == 2) and  ((int(i.dias) <= 28) and ((int(i.anios) % 4) != 0) or (int(i.dias) <= 29) and ((int(i.anios) % 4) == 0))) or ((int(i.dias) <= 31) and ((int(i.meses) == 1) or (int(i.meses) == 3) or (int(i.meses) == 5) or (int(i.meses) == 7) or (int(i.meses) == 8) or (int(i.meses) == 10) or (int(i.meses) == 12))) or ((int(i.dias) <= 30) and ((int(i.meses) == 4) or (int(i.meses) == 6) or (int(i.meses) == 9) or (int(i.meses) == 11))))), form.Validator("Las contraseñas no coinciden.", lambda i: i.clave == i.clave2),  form.Validator('Míninmo 7 caracteres', lambda x:len(x.clave)>=7), form.Validator('Míninmo 7 caracteres', lambda x:len(x.clave2)>=7)]
            )
            res="Bienvenido usuario: %s " % (web.cookies().user)
            web.setcookie('pagina3', web.cookies().pagina2)
            web.setcookie('pagina2', web.cookies().pagina1)
            web.setcookie('pagina1', "editar_perfil")
            web.header('Content-Type', 'text/html; charset=utf-8')
            return plantillas.editar_perfil(formulario=res, registro=form_reg_editar.render())
        except:
            l=form_log()
            web.header('Content-Type', 'text/html; charset=utf-8')
            return plantillas.pagina_desconectado(formulario=l.render(), mensaje="Se ha producido algun error. Inicie sesion de nuevo.")
Exemple #2
0
def settingsForm(_guideUrl, _ip, _chButLeft, _chButTop, _chButSpc, _guideHeight, _useOnbrd):
    return form.Form(
        form.Textbox("guideUrl", form.notnull, size="50", description="Web guide address", value=_guideUrl),
        form.Textbox("ip", form.notnull, description="MythTV frontend IP address", value=_ip),
        form.Textbox("chButLeft",
            form.notnull,
            form.regexp('\d+', 'Must be a digit'),
            form.Validator('Must be more than 0', lambda x:int(x)>0),
            description="Channel buttons left margin",
            value=_chButLeft),
        form.Textbox("chButTop",
            form.notnull,
            form.regexp('\d+', 'Must be a digit'),
            form.Validator('Must be more than 0', lambda x:int(x)>0),
            description="Channel buttons top margin",
            value=_chButTop),
        form.Textbox("chButSpc",
            form.notnull,
            form.regexp('\d+', 'Must be a digit'),
            form.Validator('Must be more than 0', lambda x:int(x)>0),
            description="Channel buttons vertical spacing",
            value=_chButSpc),
        form.Textbox("guideHeight",
            form.notnull,
            form.regexp('\d+', 'Must be a digit'),
            form.Validator('Must be more than 1000', lambda x:int(x)>1000),
            description="Web guide height",
            value=_guideHeight),
        form.Checkbox('useonbrd', checked=_useOnbrd, value="cb1", description="Use Onboard keyboard"))
Exemple #3
0
    def check(self):
        from web import form
        validList=(
            form.Textbox("username", form.regexp(r".{3,20}$", 'User name: 3-20 chars')),
            form.Password("password", form.regexp(r".{3,20}$", 'Password: 3-20 chars')),
        )

        if not self.validates(validList):
            return self.error(self.errorMessage)

        inputData = self.getInput()
        if config.ADMIN_USERNAME == inputData['username'] and config.ADMIN_PASSWORD == inputData['password']:
            self.setLogin(inputData['username'])
            return self.success(msg='管理员登陆成功', url=self.makeUrl('/admin'))
        else:
            if not self.isInstalled():
                return self.error(msg='用户登录失败, 系统未初始化!', url=self.makeUrl('/admin'))

            userName = inputData['username']
            password = hashlib.md5(inputData['password']).hexdigest()
            try:
                userObj = Users().select().where(Users.name == userName)
                if userObj.where(Users.name == userName, Users.password == password).exists() == False:
                    return self.error(msg='用户登录失败,请检查用户名和密码是否匹配', url=self.makeUrl('/admin'))
                self.setLogin(inputData['username'])
                return self.success(msg='用户登陆成功', url=self.makeUrl('/admin'))
            except  Users.DoesNotExist:
                return self.error(msg='用户登录失败,请检查用户名和密码是否匹配!', url=self.makeUrl('/admin'))
Exemple #4
0
 def comment(self):
     userInput= self.getInput()
     cmsObj = model.cms()
     cmsId = userInput['cmsId']
     condition = {'status':1,'id':cmsId}
     atl = cmsObj.getOne('*',condition)
     if atl == None:
         return self.error('not exist')
     from web import form
     validList=(
         form.Textbox("name",form.regexp(r".{3,100}$", 'name length 3-100')),
         form.Textbox("content",form.regexp(r".{1,200}$", 'comment length 1-200')),
         form.Textbox("email", form.regexp(r".*@.*", 'error email format')),
         form.Textbox("email",form.regexp(r".{5,100}$", 'email length 5-100')),
         )
     if not self.validates(validList):
         return self.error(self.errorMessage)
     date = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
     ip=web.ctx.ip
     data={
         'cmsId':cmsId,
         'content':userInput['content'],
         'name':userInput['name'],
         'email':userInput['email'],
         'createTime':date,
         'ip':ip,
         'status':1
     }
     commentid = model.comment().insert(data)
     data = {'commentCount':atl['commentCount']+1}
     model.cms().update(data,condition)
     return self.success('comment success, comment id '+str(commentid)+'~',self.referer)
Exemple #5
0
 def comment(self):
     userInput= self.getInput()
     cmsObj = model.cms()
     cmsId = userInput['cmsId']
     condition = {'status':1,'id':cmsId}
     atl = cmsObj.getOne('*',condition)
     if atl == None:
         return self.error('文章不存在')
     from web import form
     validList=(
         form.Textbox("name",form.regexp(r".{3,100}$", '姓名需为3~100个字符')),
         form.Textbox("content",form.regexp(r".{1,100}$", '评论内容需为3~100个字符')),
         form.Textbox("email", form.regexp(r".*@.*", '邮箱格式错误')),
         form.Textbox("email",form.regexp(r".{5,100}$", '邮箱需为5~100个字符')),
         )
     if not self.validates(validList):
         return self.error(self.errorMessage)
     date = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
     HTTP_X_REAL_IP =  web.ctx.env.get('HTTP_X_REAL_IP')
     ip=HTTP_X_REAL_IP if HTTP_X_REAL_IP else web.ctx.ip
     data={
         'cmsId':cmsId,
         'content':userInput['content'],
         'name':userInput['name'],
         'email':userInput['email'],
         'createTime':date,
         'ip':ip,
         'status':1
     }
     model.comment().insert(data)
     data = {'commentCount':atl['commentCount']+1}
     model.cms().update(data,condition)
     return self.success('评论成功',self.referer)
Exemple #6
0
 def getForm(self):
    return form.Form(
       form.Textbox("home",
          form.notnull,
          description="Home location",
          value=settings.get('location_home'),
       ),
       form.Textbox("work",
          form.notnull,
          description="Work location",
          value=settings.get('location_work'),
       ),
       form.Textbox("weatherloc",
          form.notnull,
          description="Weather location",
          value=settings.get('weather_location'),
       ),         
       form.Textbox("snooze",
          form.notnull,
          form.regexp('\d+', 'Must be a digit'),
          description="Snooze Length (minutes)",
          value=settings.getInt('snooze_length'),
       ),
       form.Textbox("wakeup",
          form.notnull,
          form.regexp('\d+', 'Must be a digit'),
          description="Time (mins) before event for alarm",
          value=settings.getInt('wakeup_time'),
       ),
       form.Textbox("precancel",
          form.notnull,
          form.regexp('\d+', 'Must be a digit'),
          description="Pre-empt cancel alarm allowed (secs)",
          value=settings.get('preempt_cancel'),
       ),
       form.Textbox("waketime",
          form.notnull,
          form.regexp('[0-2][0-9][0-5][0-9]', 'Must be a 24hr time'),
          description="Default wakeup time",
          value=settings.get('default_wake'),
       ),
       form.Checkbox("holidaymode",
          description="Holiday mode enabled",
          checked=(settings.getInt('holiday_mode')==1),
          value="holiday",
       ),
       form.Checkbox("weatheronalarm",
          description="Play weather after alarm",
          checked=(settings.getInt('weather_on_alarm')==1),
          value="weatheronalarm",
       ),
       form.Checkbox("sfx",
          description="SFX enabled",
          checked=(settings.getInt('sfx_enabled')==1),
           value="sfx",
       ),
    )
Exemple #7
0
 def getForm(self):
     return form.Form(
         form.Textbox("home", form.notnull, description="Home location", value=settings.get("location_home")),
         form.Textbox("work", form.notnull, description="Work location", value=settings.get("location_work")),
         form.Textbox(
             "weatherloc", form.notnull, description="Weather location", value=settings.get("weather_location")
         ),
         form.Textbox(
             "snooze",
             form.notnull,
             form.regexp("\d+", "Must be a digit"),
             description="Snooze Length (minutes)",
             value=settings.getInt("snooze_length"),
         ),
         form.Textbox(
             "wakeup",
             form.notnull,
             form.regexp("\d+", "Must be a digit"),
             description="Time (mins) before event for alarm",
             value=settings.getInt("wakeup_time"),
         ),
         form.Textbox(
             "precancel",
             form.notnull,
             form.regexp("\d+", "Must be a digit"),
             description="Pre-empt cancel alarm allowed (secs)",
             value=settings.get("preempt_cancel"),
         ),
         form.Textbox(
             "waketime",
             form.notnull,
             form.regexp("[0-2][0-9][0-5][0-9]", "Must be a 24hr time"),
             description="Default wakeup time",
             value=settings.get("default_wake"),
         ),
         form.Checkbox(
             "holidaymode",
             description="Holiday mode enabled",
             checked=(settings.getInt("holiday_mode") == 1),
             value="holiday",
         ),
         form.Checkbox(
             "weatheronalarm",
             description="Play weather after alarm",
             checked=(settings.getInt("weather_on_alarm") == 1),
             value="weatheronalarm",
         ),
         form.Checkbox("sfx", description="SFX enabled", checked=(settings.getInt("sfx_enabled") == 1), value="sfx"),
         form.Textbox("ttspath", description="TTS path", value=settings.get("tts_path")),
     )
def insertarDatosForm(data):
	conDatos = form.Form(
		form.Textbox('Nombre', 
					 form.notnull,
					 class_='form-control',
					 value=str(data["nombre"])),
		form.Textbox('Apellidos',
					 form.notnull,
					 class_='form-control',
					 value=str(data["apellidos"])),
		form.Textbox('Email',
					 form.notnull,
					 form.regexp('[^@]+@[^@]+\.[^@]+', 'Debe se ser un email'),
					 class_='form-control',
					 value=str(data["email"])),
		form.Dropdown('Dia', 
					  range(1, 31),
					  class_='form-control',
					  value=int(data["dia"])),
		form.Dropdown('Mes', 
					  range(1, 12),
					  class_='form-control',
					  value=int(data["mes"])),
		form.Dropdown('Ano', 
					  range(1900, 2014),
					  class_='form-control',
					  value=int(data["ano"])),
		form.Textarea('Direccion',
					  form.notnull,
					  class_='form-control',
					  value=str(data["direccion"])),
		form.Password('Contrasena',
					  form.regexp('[\d\w]{7,}',"Ha de tener al menos 7 caracteres"),
					  class_='form-control'),
		form.Password('Contrasena2',
					  class_='form-control',
					  description="Repite contrasena: "),
		form.Radio('Pago', ['Efectivo', 'VISA'],
				   class_='radio-inline',
				   checked=str(data["pago"])),
		form.Textbox('Visa',
					 form.regexp('([0-9]{4}[\s-]){3}[0-9]{4}', 'La tarjeta ha de ser XXXX-XXXX-XXXX-XXXX con guiones o con espacios'),
					 class_='form-control',
					 description="Numero de tarjeta VISA: ",
					 value=str(data["visa"])),
		validators=[form.Validator('Las contrasenas han de ser iguales.', lambda i: i.Contrasena == i['Repite contrasena'])])
	
	return conDatos
Exemple #9
0
def num_box(name, desc):
    return form.Textbox(
        name,
        form.notnull,
        form.regexp('^\s*\d+\s*$', "Digits only, please."),
        size="10",
        description=desc)
Exemple #10
0
 def check(self):
     from web import form
     validList=(
         form.Textbox("username",form.regexp(r".{3,20}$", '用户名为3~20个字符')),
         form.Password("password", form.regexp(r".{3,20}$", '密码为3~20个字符')),
     )
     if not self.validates(validList):
         return self.error(self.errorMessage)
     inputData = self.getInput()
     settings = self.getSettings()
     if settings.ADMIN_USERNAME == inputData['username'] and settings.ADMIN_PASSWORD == inputData['password']:
         userData={'username':inputData['username']}
         self.setLogin(userData)
         return self.success('登陆成功',self.makeUrl('cms','list'))
     else:
         return self.error('账号或密码错误',self.makeUrl('admin',''))
Exemple #11
0
    def check(self):
        from web import form

        validList = (
            form.Textbox("username", form.regexp(r".{3,20}$", "User name: 3-20 chars")),
            form.Password("password", form.regexp(r".{3,20}$", "Password: 3-20 chars")),
        )

        if not self.validates(validList):
            return self.error(self.errorMessage)

        inputData = self.getInput()
        if config.ADMIN_USERNAME == inputData["username"] and config.ADMIN_PASSWORD == inputData["password"]:
            self.setLogin(inputData["username"])
            return self.success(msg="管理员登陆成功", url=self.makeUrl("/admin"))

        return self.error(msg="用户登录失败,请检查用户名和密码是否匹配!", url=self.makeUrl("/admin"))
Exemple #12
0
	def __init__ ( self ):
	    Form.__init__ ( self,
	         Textbox('name', size=30, description="用户名", class_='sl', disabled='disabled'),
	         Textbox('email', EmailValidator, size=30, description="邮箱", class_='sl'),
	         Textbox('signature', regexp(r".{0,100}$", ' 请不要超过100个字符'), size=30, description="签名", class_='sl'),
	         Textbox('outsite_link', LinkValidator, size=30, description="主页", class_='sl'),
	         Button('保存设置', class_='super normal button')
     	)
	def buildForm():
		return form.Form(
			form.Textbox("userDispName", form.notnull, description="Display name"),
			form.Textbox("glId", form.notnull, description="SPOT key"),
			form.Textbox("userEmail", form.regexp(r".*@.*", "Must be a valid email address"), description="Email address"),
			form.Textbox("userWebsite", description="Website"),
			form.File("userImage", description="Optional custom user image"),
			# form.Textbox("userIM", description="IM nickname")
			)
Exemple #14
0
 def make_profile_form(self):
     f = form.Form(form.Textbox('email',
                                form.notnull,
                                form.regexp('^[\w-]+(\.[\w-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$', 'Invalid email address'),
                                value=self.user.email),
                   form.Textbox('homepage', value=self.user.homepage),
                   form.Textarea('description',
                                 value=self.user.description),
                   form.Button('Save'))
     return f
Exemple #15
0
 def make_edit_form(self, proj):
     edit_form = form.Form(
         form.Textbox(
             "name",
             form.notnull,
             form.regexp("^[a-z0-9._-]+$", "Name must only include low-case letters, digits, '.'. '_' and '-'"),
             value=proj.name,
         ),
         form.Textbox("homepage", value=proj.homepage),
         form.Textarea("description", value=proj.description),
         form.Button("Save"),
     )
     return edit_form
Exemple #16
0
   def getAlarmForm(self):
      global alarm

      nextAlarm = alarm.getNextAlarm()
      alarmTime = ""

      if nextAlarm is not None:
         alarmTime = nextAlarm.strftime("%I%M")

      return form.Form(
         form.Textbox("time",
            form.notnull,
            form.regexp('[0-2][0-9][0-5][0-9]', 'Must be a 24hr time'),
            description="Set alarm time",
            value = alarmTime,
         ),
      )
Exemple #17
0
def Login():
	"""
	Generates Login Form
	"""
	vusername = form.regexp(r".{3,50}$", 'must be between 3 and 20 characters')
	#validator of the username
	
	login = form.Form(
		form.Textbox(
			'username',vusername,
			description="USERNAME"
		),
		form.Password(
			'password',
			description="PASSWORD"
		),
		validators = [
		form.Validator(
			"Username and Password can't be the same",
			lambda i: i.username != i.password
			)
		]
	)
	return login
Exemple #18
0
import urllib

render = web.template.render('')

myform = form.Form(
    form.Textbox(
        "search_query",
        id="search_query",
        description="Search",
        value="Machine learning",
        class_="form-control",
    ),
    form.Textbox(
        "start",
        form.notnull,
        form.regexp('\d+', 'Must be a digit'),
        form.Validator('Must be >= 0', lambda x: int(x) >= 0),
        description="Start",
        value="0",
        id="start",
        class_="form-control",
    ),
    form.Textbox(
        "numb_results",
        form.notnull,
        form.regexp('\d+', 'Must be a digit'),
        form.Validator('Must be more than 0', lambda x: int(x) > 0),
        description="Results in page",
        value="10",
        id="numb_results",
        class_="form-control",
# Templates de mako
render = render_mako(
	directories = ['templates'],
	input_encoding = 'utf-8',
	output_encoding = 'utf-8')

# Formulario de acceso
form_acceso = form.Form(
	form.Textbox("usuario", form.notnull, description="Usuario:"),
	form.Password("password", form.notnull, description="Contraseña:"),
	form.Button("Acceder", type="submit"),
)

# Expresiones regulares validación
vTexto = form.regexp(r"^[\w\s]+$", '* Campo vacío.')
vEmail = form.regexp(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$", '* Correo electrónico no válido.')
vVISA = form.regexp(r"^([0-9]{4}) ([0-9]{4}) ([0-9]{4}) ([0-9]{4})$|^([0-9]{4})-([0-9]{4})-([0-9]{4})-([0-9]{4})$", '* Número tarjeta VISA no válido.')
vpass = form.regexp(r"\w{8,}$", '* Mínimo 8 caracteres.')

# Formulario de registro
form_datos = form.Form( 
	form.Textbox("usuario", vTexto, description = "Usuario:"),
	form.Password("password", vpass, description = "Contraseña:"),
	form.Password("verificacion", vpass, description = "Verificar contraseña:"),
	form.Textbox("nombre", vTexto, description = "Nombre:"),
	form.Textbox("apellidos", vTexto, description = "Apellidos:"),
	form.Textbox("correo", vEmail, description = "Correo electrónico:"),
	form.Textbox("visa", vVISA, description = "Número de VISA:"),
	form.Dropdown("dia", range(1, 32), description = "Día:"),
	form.Dropdown("mes", range(1, 13), description = "Mes:"),
Exemple #20
0
    ('bpl139.mrc', 50000),
    ('bpl140.mrc', 50000),
    ('bpl141.mrc', 50000),
    ('bpl142.mrc', 50000),
    ('bpl143.mrc', 50000),
    ('bpl144.mrc', 50000),
    ('bpl145.mrc', 50000),
    ('bpl146.mrc', 50000),
    ('bpl147.mrc', 41036),
)

myform = form.Form( 
    form.Dropdown('file', [(i, "%s - %d records" % (i, j)) for i, j in files]),
    form.Textbox("start", 
        form.notnull,
        form.regexp('\d+', 'Must be a digit'),
        form.Validator('Must be less than 50000', lambda x:int(x)>50000)),
    form.Textbox("count", 
        form.notnull,
        form.regexp('\d+', 'Must be a digit'),
        form.Validator('Must be less than 50000', lambda x:int(x)>50000)))

def start_and_len(file, start, count):
    f = urllib2.urlopen("http://archive.org/download/bpl_marc/" + file)
    pos = 0
    num = 0
    start_pos = None
    while num < start + count:
        data = f.read(5)
        if data == '':
            break
Exemple #21
0
            session.loggedin = True
            session.username = username
            raise web.seeother("/")
        else:
            return homepage_render.login("Login Failed", session.loggedin)


class Logout(object):
    def GET(self):
        session.loggedin = False
        session.kill()
        raise web.seeother("/")


# email validator
vemail = form.regexp(r".*@.*", "must be a valid email address")

# New user form
new_user_form = form.Form(
    form.Textbox("username", description="Username"),
    form.Textbox("email", vemail, description="E-Mail"),
    form.Password("password", description="Password"),
    form.Password("password_again", description="Confirm Password"),
    validators=[form.Validator("Passwords didn't match.", lambda i: i.password == i.password_again)],
)

# Create a new user page
class NewUser(object):
    def GET(self):
        cur_form = new_user_form()
        return homepage_render.newuser("New User", cur_form, session.loggedin)
Exemple #22
0
import web
from web import form

urls = ("/registe", "register")
render = web.template.render("templates")  # your templates
app = web.application(urls, globals())
vpass = form.regexp(r".{3,20}$", "must be between 3 and 20 characters")
vemail = form.regexp(r".*@.*", "must be a valid email address")

register_form = form.Form(
    form.Textbox("username", description="Username"),
    form.Textbox("email", vemail, description="E-Mail"),
    form.Password("password", vpass, description="Password"),
    form.Password("password2", description="Repeat password"),
    form.Button("submit", type="submit", description="Register"),
    validators=[form.Validator("Passwords did't match", lambda i: i.password == i.password2)],
)


class register:
    def GET(self):
        # do $:f.render() in the template
        f = register_form()
        return render.register(f)

    def POST(self):
        f = register_form()
        if not f.validates():
            return render.register(f)
        else:
            # do whatever is required for registration
Exemple #23
0
LONG_PRESS = 1500 
#Software GPIO for Button Inputs
print(GPIO.VERSION)
GPIO.setmode(GPIO.BCM)
GPIO.setup(24, GPIO.IN, pull_up_down = GPIO.PUD_UP)

myform = form.Form(
    form.Radio(name='Style', args=['Increase', 'Decrease'],value='Increase'),
    form.Radio(name='Brightness', args=['Low', 'Medium', 'High'],value='Medium'),
    form.Dropdown(name='Hour', args=['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],value='6'),
    form.Dropdown(name='Minute', args=['00', '05', '10', '15', '20', '25', '30', '35', '40', '45', '50', '55'], value='30'),
    form.Radio(name='AM/PM', args=['AM', 'PM'],value='AM'),
    form.Checkbox('Now', id='Now', value='True'),
    form.Textbox("Length",
        form.notnull,
        form.regexp('\d+', 'Need a numerical length here...')))

print("Welcome to the prototype sunrise alarm clock. Follow the online prompts to decide on a color, fade in time, blink rate, etc")
def button():
    global running
    global reset
    global red
    global green
    global blue
    override = 0
    presstime = 0
    while True:
	try:
	    timelib.sleep(0.05)
	    GPIO.wait_for_edge(24, GPIO.FALLING)
#	    print("Button Pressed")
como una frase que dependa de la informacion introducida en dicho formulario).
"""

import web
from web import form

render = web.template.render('templates/')

urls = ('/', 'index')
app = web.application(urls, globals())

myform = form.Form( 
    form.Textbox("Nombre"), 
    form.Textbox("Edad", 
        form.notnull,
        form.regexp('\d+', 'Debe ser un numero'),
        form.Validator('Debe ser mayor o igual a 18', lambda x:int(x)>=18))
    )

class index: 
    def GET(self): 
        form = myform()
        # make sure you create a copy of the form by calling it (line above)
        # Otherwise changes will appear globally
        return render.ejercicio_04(form)

    def POST(self): 
        form = myform() 
        if not form.validates(): 
            return render.ejercicio_04(form)
        else:
Exemple #25
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

import web
from web import form


urls = (
	'/Formulario', 'Formulario',
	)

Email = form.regexp(r'(\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}\b)', 'El e-mail tiene que tener la forma [email protected]')
Visa = form.regexp(r'([0-9]{4}) ([0-9]{4}) ([0-9]{4}) ([0-9]{4})|([0-9]{4})-([0-9]{4})-([0-9]{4})-([0-9]{4})', '4 grupos de 4 digitos separados por un espacio o -')

# Formulario
singUP = form.Form(
	form.Textbox("Nombre", form.notnull, description = "Nombre:"),
	form.Textbox("Apellidos", form.notnull, description = "Apellidos:", value = "Mengano"),
	form.Textbox("email", Email, description = "E-mail:", value = "tu email"),
	form.Dropdown('Dia', [('01', '01'), ('02','02'), ('04','04'), ('05','05'), ('06', '06'), ('07', '07'), ('08', '08'), ('09', '09'), ('10', '10'), ('11', '11'), ('12', '12'), ('13', '13'), ('14', '14'), ('15', '15'), ('16', '16'), ('17', '17'), ('18', '18'), ('19', '19'), ('20', '20'), ('21', '21'), ('22', '22'), ('23', '23'), ('24', '24'), ('25', '25'), ('26', '26'), ('27', '27'), ('28', '28'), ('29', '29'), ('30', '30'), ('31', '31')], description="Dia:"),
	form.Dropdown('Mes', [('Enero', 'Enero'), ('Febrero', 'Febrero'), ('Marzo','Marzo'), ('Abril', 'Abril'), ('Mayo', 'Mayo'), ('Junio', 'Junio'), ('Julio', 'Julio'), ('Agosto', 'Agosto'), ('Septiembre', 'Septiembre'), ('Octubre', 'Octubre'), ('Noviembre', 'Noviembre'), ('Diciembre','Diciembre')], description = "Mes:"),
	form.Dropdown('Ano', [('1995', '1995'), ('1994', '1994'), ('1993', '1993'), ('1992', '1992'), ('1991', '1991'), ('1990', '1990'), ('1989', '1989')], description= "Anio:"),
	form.Textarea("Direccion", form.notnull, description = "Direccion:",),
	form.Password("Contrasena", form.notnull, description = "Contrasenia:"),
	form.Password("ReContrasena", form.notnull, description = "Reescribe contrasenia:"),
	form.Radio("MetodoDePago", [('Reembolso', 'Reembolso'),('VISA','VISA')], form.Validator('Tienes que seleccionar un metodo de pago', lambda x:'MetodoDePago' not in x), description = "Metodo de Pago"),
	form.Textbox("numVisa", Visa, description = "Numero tarjeta VISA:"),
	form.Checkbox("AceptoClausula", form.Validator('Tienes que aceptar las clausulas', lambda i:'AceptoClausula' not in i), description = "Acepto las clausulas de proteccion de datos"),
	form.Button("Enviar"),
	validators = [
		form.Validator("Las contraseñas no coinciden.", lambda y: y.Contrasena == y.ReContrasena)]
Exemple #26
0
import sys, xmlrpclib, os, time, re, getpass, httplib
from optparse import OptionParser
import web
import model
from web import form

XMLRPC_SERVER = 'https://xmlrpc.rhn.redhat.com/rpc/api'

render = web.template.render('templates/')
urls = ('/', 'index', '/approve', 'approve', '/add/(\d+)', 'add', '/del/(\d+)',
        'delete')
app = web.application(urls, globals())

userdetails = {}

vpass = form.regexp(r".{3,20}$", "must be between 3 and 20 characters")
vemail = form.regexp(r".*@.*", "must be a valid email address")
vphone = form.regexp(r".*-.*-.*", "must be a valid phone number")

addform = form.Form(
    form.Textbox("login", form.notnull, description="Username"),
    form.Password("password", vpass, form.notnull, description="Password"),
    form.Password("password2", form.notnull, description="Repeat Password"),
    form.Dropdown("prefix",
                  ['Mr.', 'Mrs.', 'Dr.', 'Miss', 'Ms.', 'Sr.', 'Hr.'],
                  description="Prefix"),
    form.Textbox("firstname", form.notnull, description="First Names"),
    form.Textbox("lastname", form.notnull, description="Last Name"),
    form.Textbox("email", vemail, form.notnull, description="Email"),
    form.Textbox("phone", vphone, form.notnull, description="Phone Number"),
    form.Textbox("addr1", form.notnull, description="Address 1"),
Exemple #27
0
try:
    client = MongoClient()
    db = client.usuarios
    print "Conexión realizada con éxito"
except pymongo.errors.ConnectionFailure, e:
    print "Error al conectar con MongoDB: %s" % e


#Elementos del formulario
dias=range(1,32)
meses=range(1,13)
anios=range(1915,2015)

form_reg = form.Form(
    form.Textbox('user', form.notnull, description="Nombre de Usuario"),
    form.Textbox('nombre', form.notnull, form.regexp('^[A-Z, a-z]', 'No hay nadie en el mundo cuyo nombre tenga números.¡Use letras!'), description="Nombre"),
    form.Textbox('apellidos', form.notnull, form.regexp('^[A-Z, a-z]', 'No hay nadie en el mundo cuyo apellido tenga números.¡Use letras!'), description="Apellido"),
    form.Textbox('correo', form.notnull,  form.regexp('^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$', 'Introduzca un correo válido'), description="Correo electrónico"),

    form.Dropdown('dias', dias, description="Dia"),
    form.Dropdown('meses', meses, description="Mes"),
    form.Dropdown('anios', anios, description="Anio"),

    form.Textarea('direccion', form.notnull,  description="Dirección"),
    form.Password('clave', form.notnull, description="Contraseña"),
    form.Password('clave2', form.notnull, description="Repetir contraseña"),
    form.Radio('pago', ['Contra reembolso', 'Tarjeta VISA'], description="Forma de pago"),
    form.Textbox('visa', form.regexp('((\d{4})[\-,\s](\d{4})[\-,\s](\d{4})[\-,\s](\d{4}))', 'Introduzca un número de tarjeta VISA válido'), description="Tarjeta VISA"),
    form.Checkbox('clausula', form.Validator("Acepta las clausulas", lambda i: i == 'true'), value='true', description="¿Nos vende su alma?"),
    form.Button('Registrarse'),
    validators = [form.Validator("Fecha de nacimiento no válida.", lambda i: (((int(i.meses) == 2) and  ((int(i.dias) <= 28) and ((int(i.anios) % 4) != 0) or (int(i.dias) <= 29) and ((int(i.anios) % 4) == 0))) or ((int(i.dias) <= 31) and ((int(i.meses) == 1) or (int(i.meses) == 3) or (int(i.meses) == 5) or (int(i.meses) == 7) or (int(i.meses) == 8) or (int(i.meses) == 10) or (int(i.meses) == 12))) or ((int(i.dias) <= 30) and ((int(i.meses) == 4) or (int(i.meses) == 6) or (int(i.meses) == 9) or (int(i.meses) == 11))))), form.Validator("Las contraseñas no coinciden.", lambda i: i.clave == i.clave2),  form.Validator('Míninmo 7 caracteres', lambda x:len(x.clave)>=7), form.Validator('Míninmo 7 caracteres', lambda x:len(x.clave2)>=7)]
Exemple #28
0
	form.Textbox ('trabajo', form.notnull, description = 'Tu salario'),
	form.Textbox ('premios', form.notnull, description = 'Premios economicos'),
	form.Textbox ('ventas', form.notnull, description = 'Ingresos por ventas'),
	form.Textbox ('otros', form.notnull, description = 'Otros ingresos'),
	#form.Textbox ('cantidad', form.notnull, form.regexp('^([0-9]{2})$', 'La cantidad introducida no es válida', description='Cantidad')
	form.Button ('Enviar'),
	#for i in tipo_gasto:
		#validators = [form.Validator(i, lambda j: (int (j.cantidad) > 0))],
	validators = [form.Validator("Valor introducido incorrecto", lambda i: ((int (i.deudas) >= 0)) and (int (i.trabajo) >= 0) and (int (i.premios) >= 0) and (int (i.ventas) >= 0) and (int (i.otro) >= 0))]
)

#Register form #
registro_form = form.Form(
	form.Textbox ('nombre', form.notnull, description = 'Nombre'), 
	form.Textbox ('apellidos', form.notnull, description = 'Apellidos'),
	form.Textbox ('email', form.notnull, form.regexp('^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$', 'Formato de correo electronico incorrecto'), description = 'E-mail'),
	form.Dropdown("dia", [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31], description="Dia de nacimiento"),
	form.Dropdown("mes", ['enero','febrero','marzo','abril','mayo','junio','julio','agosto','septiembre','octubre','noviembre','diciembre'], description="Mes de nacimiento"),
	form.Dropdown("anio", [1980,1981,1982,1983,1984,1985,1986,1987,1988,1989,1990,1991,1992,1993,1994,1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014], description="Anio de nacimiento"),
	form.Password ('password', form.notnull, description = 'Password', post = 'La contrasenia debe tener al menos 6 caracteres.'),
	form.Password ('passv', form.notnull, description = 'Repita su contrasenia'),
	form.Checkbox ('permission', form.Validator('Debes aceptar las clausulas de proteccion de datos.', lambda i: 'permission' not in i), description = 'Aceptacion de clausulas de proteccion de datos'),
	form.Button('Enviar'),
	validators = [form.Validator("La contrasenia no coincide", lambda i: i.password == i.passv), form.Validator("Tamanio de contrasenia incorrecto", lambda i: len(i.password) >= 6), form.Validator("Fecha de nacimiento incorrecta", lambda i: (((str(i.mes) == 'febrero') and ((int(i.dia) <= 28) and ((int(i.anio) % 4) != 0) or (int(i.dia) <= 29) and ((int(i.anio) % 4) == 0))) or ((int(i.dia) <= 31) and ((str(i.mes) == 'enero') or (str(i.mes) == 'marzo') or (str(i.mes) == 'julio') or (str(i.mes) == 'agosto') or (str(i.mes) == 'octubre') or (str(i.mes) == 'diciembre'))) or ((int(i.dia) <= 30) and ((str(i.mes) == 'abril') or (str(i.mes) == 'junio') or (str(i.mes) == 'septiembre') or (str(i.mes) == 'noviembre')))))]
)

##### FUNCTIONS ######
def check_identification ():
	usuario = session.usuario #Check in cookies if user is already login
	return usuario 
Exemple #29
0
# coding: utf8
from web import form

ClientForm = form.Form(
    form.Textbox("Nome"),
    form.Textbox("Telefone",
                 form.notnull,
                 form.regexp('\d+', 'Digite um telefone'),
                 form.Validator('Seu telefone deve ter mais que 8 caracteres', lambda x: int(x) > 6)),
    form.Textarea('Digite um texto sobre voce'),
    form.Checkbox('Aceitos os termos de servico'),
    form.Dropdown('Sexo', ['Masculino', 'Feminino']))
Exemple #30
0
from string import translate, maketrans, punctuation
import web
from web import form
import config
import dbus
from util import get_properties, get_raw_value, get_value, get_str_value, \
    get_dict_value, get_service, get_security

vssid = form.regexp(r".{1,32}$", "Must be between 1 and 32 characters")
vprefix = form.Validator('Must be between 0 and 128',
                         lambda x: x == "" or int(x) >= 0 and int(x) <= 128)
vallowempty = form.Validator('', lambda x: x == "")
vpin = form.regexp(r".{4,8}$", "Must be between 4 and 8 characters")

form = web.form.Form(
    form.Hidden('servicetype'),
    form.Radio('autoconnect', args=["Yes", "No"], description="Autoconnect"),
    form.Textbox("domains", class_="textEntry", size=64,
                 description="Domains"),
    form.Textbox("timeservers",
                 class_="textEntry",
                 size=64,
                 description="Timeservers"),
    form.Textbox("nameservers",
                 class_="textEntry",
                 size=64,
                 description="Nameservers"),
    form.Dropdown("ipv4method", [('fixed', 'Fixed'), ('dhcp', 'DHCP'),
                                 ('manual', 'Manual'), ('off', 'Off')],
                  onChange="show_hide_ipv4_fields(this);",
                  description="IPv4 configuration"),
Exemple #31
0
    "quakes",
    "/form",
    "htmlForm",
    "/menu",
    "mainMenu",
    "/zwrd?",
    "zwrd",
    "/zwrd/?",
    "zwrd",
    "/.*",
    "defaultUrl",
)
HTMLapp = web.application(HTMLurls, globals())
myCurrentQueries = C.QUERIESINGLOBALDEFAULTS
render = web.template.render('templates')  # your templates
vpass = form.regexp(r".{3,20}$", 'must be between 3 and 20 characters')
vemail = form.regexp(r".*@.*", "must be a valid email address")
register_form = form.Form(form.Textbox("username", description="Username"),
                          form.Textbox("email", vemail, description="E-Mail"),
                          form.Password("password",
                                        vpass,
                                        description="Password"),
                          form.Password("password2",
                                        description="Repeat password"),
                          form.Button("submit",
                                      type="submit",
                                      description="Register"),
                          validators=[
                              form.Validator(
                                  "Passwords did't match",
                                  lambda i: i.password == i.password2)
templ = web.template.render('templates/')

urls = ('/', 'index')
app = web.application(urls, globals())

myform = form.Form(
    form.Textbox("firstname",
        form.notnull
    ),
    form.Textbox("lastname",
        form.notnull
    ),
    form.Textbox("dni",
        form.notnull,
        form.regexp(r'(\d{7})([-]?)([A-Z]{1})', 'Debe ser un DNI valido')
    ),
    form.Textbox("email",
        form.notnull,
        form.regexp(r'^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$', 'Debe ser un email')
    ),
    form.Dropdown("day", [(d, d) for d in range(1, 32)]),
    form.Dropdown("month", [(d, d) for d in range(1, 13)]),
    form.Dropdown("year", [(d, d) for d in range(1900, 2013)]),

    form.Textbox("address",
        form.notnull
    ),

    form.Password("password",
        form.notnull,
Exemple #33
0
#!/usr/bin/env python
#-*-coding:utf-8-*-

from web import form



vauthor = form.regexp(r".+", "Name can not be empty!")
vemail = form.regexp(r".*@.*", "Email address is empty or not valid!")
vcomment = form.regexp(r".+", "Comment can not be empty!")

comment_form = form.Form(
    form.Textbox("author", vauthor, size="25", tabindex="1", value="", class_="comment"),
    form.Textbox("email", vemail, size="25", tabindex="2", value="", class_="comment"),
    form.Textbox("url", size="25", tabindex="3", value="", class_="comment"),
    form.Textarea("comment", vcomment, cols="100%", rows="10", tabindex="4"),
    form.Button("submit", type="submit", class_="submit", tabindex="5",
                html="Submit Comment", title="Please review your comment before you submit"),
)


settings_form = form.Form(
    form.Textbox("title", maxlength="200", value=""),
    form.Textbox("subtitle", maxlength="200", value=""),
    form.Textarea("notice", rows="2", cols="10"),
    form.Textbox("keywords", maxlength="200", value=""),
    form.Textbox("description", maxlength="200", value=""),
    form.Textbox("email", vemail, maxlength="200", value=""),
    form.Textbox("domain", maxlength="200", class_="regular-text", value=""),
    form.Button("submit", type="submit", class_="button-primary", html="Save changes"),
)
Exemple #34
0
username_msg = web.config.authform.get('username error', 
                                       'Invalid username')
password_msg = web.config.authform.get('password error',
                                       'Password cannot be empty')
email_msg = web.config.authform.get('email error',
                                    'Invalid e-mail address')
pw_confirm_msg = web.config.authform.get('password confirmation error',
                                         'You must correctly retype your password')
email_request_msg = web.config.authform.get('email request error',
                                            'This e-mail corresponds to no user')
account_reg_msg = web.config.authform.get('account registration error',
                                          'Username or e-mail already belongs to a registered user')
authentication_msg = web.config.authform.get('authentication error',
                                             'Please check your username or password.')

username_va = form.regexp('[A-Za-z]{1}[A-Za-z0-9.-_]{3,39}', username_msg)
password_va = form.regexp('^.{%s}.*' % auth.min_pwd_length, password_msg)
email_va = form.regexp(
    r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Za-z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Za-z]+)*"  # dot-atom
    r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' # quoted-string
    r')@(?:[A-Za-z0-9]+(?:-*[A-Za-z0-9]+)*\.)+[A-Za-z]{2,6}$', # domain
    email_msg
)
confirmation_va = form.Validator(pw_confirm_msg,
                                 lambda i: i.password == i.confirm)
new_confirmation_va = form.Validator(pw_confirm_msg,
                                     lambda i: i.new == i.confirm)
email_belongs_va = form.Validator(email_request_msg,
                                  lambda i: auth.User.exists(email=i.email))
account_reg_va = form.Validator(account_reg_msg,
                                lambda i: not auth.User.exists(username=i.username,

db = conn.usuarios
db

col = db.datos
col
print conn.database_names()
print db.collection_names()


# Uso de plantillas mako
plantillas = render_mako(directories=["templates"], input_encoding="utf-8", output_encoding="utf-8")

# Expresiones regulares para los formularios
validatorEmail = form.regexp(r"\b[a-zA-Z\d._-]+@[a-zA-Z.-]+\.[a-zA-Z]{2,4}\b", "* Correo electrónico no válido.")
validatorVISA = form.regexp(
    r"([\d]{4}) ([\d]{4}) ([\d]{4}) ([\d]{4})|([\d]{4})-([\d]{4})-([\d]{4})-([\d]{4})",
    "* Número tarjeta VISA no válido.",
)

login = form.Form(
    form.Textbox("nombre", required=True, description="Nombre del usuario:"),
    form.Textbox("apellidos", required=True, description="Apellidos:"),
    form.Textbox("DNI", required=True),
    form.Textbox("correo_electronico", validatorEmail, required=True, description="Correo electronico:"),
    form.Dropdown(
        "Dia_de_nacimiento",
        [
            ("1", "1"),
            ("2", "2"),
dataform = form.Form(
    form.Dropdown("where", [("../", "Parent Folder to Scripts"),
                            ("", "Same Folder as Scripts")],
                  description="Match Files Location"),
    form.Textbox("prodteam", description="Production Team", size=41),
    form.Textbox("twit",
                 form.Validator("Remove @", lambda x: x[0] != "@"),
                 description="Twitter Handle",
                 size=41),
    form.Textbox("fb", description="Facebook Name", size=41),
    form.Textbox("weblink", description="Website Link", size=41),
    form.Textbox("ename", description="Event Name", size=41),
    form.Textbox("ecode", description="Event Code (ex. 2016arc)"),
    form.Textbox("pID",
                 form.regexp(
                     "^PL",
                     "Must be a playlist ID, all of which start with 'PL'"),
                 form.regexp("^\s*\S+\s*$", "Can not contain spaces."),
                 description="Playlist ID",
                 size=41),
    form.Textbox(
        "tbaID",
        form.Validator(
            "Make sure there are no spaces", lambda x: " " not in x or x ==
            "Go to thebluealliance.com/request/apiwrite to get keys"),
        description="TBA Event ID",
        value="Go to thebluealliance.com/request/apiwrite to get keys",
        size=41),
    form.Textbox(
        "tbaSecret",
        form.Validator(