Exemplo n.º 1
0
 def register_form(self):
     return form.Form(
         form.Textbox('email',
                      form.notnull,
                      vemail,
                      form.Validator('This email address is already taken.',
                                     lambda x: users.is_email_available(x)),
                      description=u'* 邮箱',
                      class_="form-control"),
         form.Password('password',
                       form.notnull,
                       form.Validator(
                           'Password must at least 5 characters long.',
                           lambda x: users.is_valid_password(x)),
                       description=u'* 密码',
                       class_="form-control"),
         form.Password('re_password',
                       form.notnull,
                       description=u"* 确认密码",
                       class_="form-control"),
         form.Button('SingUp',
                     type='submit',
                     value='SignUp',
                     html=u"注册",
                     class_="btn btn-primary"),
         validators=[
             form.Validator('Password Not Match!.',
                            lambda i: i.password == i.re_password)
         ])
Exemplo n.º 2
0
 def registration_form(self):
     return form.Form(
         form.Dropdown('college', [u'==请选择您所在学院=='] + CUMTSchoolList,
                       form.Validator("select college.",
                                      lambda i: i in CUMTSchoolList),
                       form.notnull,
                       description=u"* 学院",
                       class_="form-control"),
         form.Textbox('telephone',
                      form.notnull,
                      description=u"* 手机号码",
                      class_="form-control"),
         mww.MyRadio('gender', [u'男', u'女'],
                     form.notnull,
                     description=u"* 性别"),
         form.Textbox('studentid',
                      form.notnull,
                      description=u'* 学号',
                      class_="form-control"),
         form.Textbox('name',
                      form.notnull,
                      description=u'* 姓名',
                      class_="form-control"),
         form.Button('submit',
                     submit='submit',
                     class_="btn btn-primary",
                     html=u"保存修改"))
Exemplo n.º 3
0
class edit:        
    newuser = form.Form(
	        form.Textbox('username', description="Username:"******"Password:"******"Password (Again):"),
                form.Button('submit', type="submit", class_="form_control btn btn-primary", description="Add User" ), 
		validators = [
        		form.Validator("Passwords did't match", lambda i: i.password == i.password2)]
    )

    @IsAuthorized
    def GET(self):
	f = self.newuser()
	users = model.listUsers()
        return render.edit(users,f)

    @IsAuthorized 
    def POST(self):
	users = model.listUsers()
	f = self.newuser()
        if not f.validates():
		print f.render_css()
		return render.edit(users,f)
	else:
		success = model.insertuser( f.d.username, f.d.password )
		web.seeother('/door')
Exemplo n.º 4
0
class Signup:
    vpass = form.regexp(r".{3,20}$", 'must be between 3 and 20 characters')
    vemail = form.regexp(r".*@.*", "must be a valid email address")

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

)
    def GET(self):
        # do $:f.render() in the template
        f =self.signup_form()
        return render.signup(f)
    def POST(self):
        f =self.signup_form()
        if not f.validates():
            return render.signup(f)
        else:
            model.sign_up(f.d.username,f.d.email,f.d.password,f.d.sex)
            raise web.seeother('/login')
Exemplo n.º 5
0
def AdminUpdateForm(administrator):
    """ 管理员账号更新表单

        administrator_old_email                                    原邮箱
        administrator_old_password                           原密码
        administrator_email                                            新邮箱
        administrator_password                                    新密码
        administrator_password_confirm                   确认密码
        administrator_submit                                          提交
    """
    updateForm = form.Form(
        form.Textbox("administrator_old_email",
                     readonly="true",
                     description=u"原邮箱:",
                     value=administrator.email),
        form.Password("administrator_old_password",
                      Validation['password'],
                      description=u"原密码:"),
        form.Textbox("administrator_email",
                     Validation['email'],
                     description=u"新邮箱:"),
        form.Password("administrator_password",
                      Validation['password'],
                      description=u"新密码:"),
        form.Password("administrator_password_confirm",
                      Validation['password'],
                      description=u"确认密码:"),
        form.Button("administrator_submit", type="submit", html=u'提交'),
        validators=[
            form.Validator(
                "确认密码不正确", lambda i: i.administrator_password == i.
                administrator_password_confirm)
        ],
    )
    return updateForm
Exemplo n.º 6
0
 def __init__(self):
     self._login_form = form.Form(
         form.Textbox('username', form.notnull),
         form.Password(
             'password', form.notnull, form.regexp('\d+', 'Digits only'),
             form.Validator('Must be larger or equal than 8',
                            lambda x: len(x) >= 8)))
Exemplo n.º 7
0
class register:
	registration_form = form.Form(
		form.Textbox("username", description="Login"),
		form.Password("password1", description="Password"),
		form.Password("password2", description="Repeat password"),
		form.Button("submit", type="submit", description="Register!"),
		validators = [
			form.Validator("Passwords must match!", lambda i: i.password1 == i.password2),
			form.Validator("Password is too short!", lambda i: len(i.password1) <= 9)
		]
	)

	def GET(self):
		f = register.registration_form()
		return render.register(f)

	def POST(self):
		f = register.registration_form()
		if not f.validates():
			return render.register(f)

		i = web.input()
		username, passwd = i.username, i.password1

		try:
			namecheck = db.query("SELECT exists(SELECT 1 FROM gallery.users WHERE username=${un})", vars={'un':username})
			profilecheck = db.query("SELECT exists(SELECT 1 FROM gallery.profiles WHERE urlname=${un})", vars={'un':username})
		except Exception as e:
			return "Unhandled database exception."

		if namecheck[0]['exists'] or profilecheck[0]['exists']:
			return "<p>This username is not available.</p>"
		else:
			self.createuser(i.username, i.password1)
			return "<p>Created user!  Try to <a href=/login>log in</a>.</p>"

	def createuser(self, username, password):
		from passlib.context import CryptContext
		password_context = CryptContext(schemes=["pbkdf2_sha512"], deprecated="auto")

		cryptedpassword = password_context.hash(password)
		db.insert('gallery.users', admin=False, password=cryptedpassword, username=username)

		createduser = db.select('gallery.users', where="username=${un}", vars={'un':username})
		db.insert('gallery.userflags', userid=createduser[0]['id'], flagtype="newuser")
Exemplo n.º 8
0
class Index(object):


    form = form.Form(
        form.Textbox("Name", 
            form.notnull,
            class_="form-control", 
            description=None,
            placeholder="Your Name",
            ),
        form.Password("pass1", 
            class_="form-control", 
            description=None,
            placeholder="Password"),
        form.Password("pass2", 
            class_="form-control", 
            description=None,
            placeholder="Password Again"),
        validators = [form.Validator("Password did'nt match", lambda i: i.pass1 == i.pass2),
                        form.Validator("User name already exist! Try something else.", lambda x: model.user_exist(x.Name))]
        )

    

    def GET(self):
        register = self.form()
        players_data = model.scores()
        return render.login(register, notify=None, players_data=players_data)

    # for submission of signup form only
    def POST(self):
        register = self.form()
        if not register.validates():
            players_data = model.scores()
            return render.login(register, notify=None, players_data=players_data)

        # incomming = web.input('Name', 'pass1')
        
        # this is used to "setup" the session with starting values
        session.room = map.START
        session.username = register.d.Name
        model.signup(register.d.Name, register.d.pass1)
        raise web.seeother("/game")
Exemplo n.º 9
0
 def article_select_form(self):
     return form.Form(
         form.Dropdown('article',
                       sorted(map(lambda x:x.name,articles.get_all_articles())),
                       form.notnull,
                       form.Validator('This Article Not Exist!',
                                      lambda x:articles.name_exist_p(x)),
                       description = "Article ",
                       class_="form-control"),
         form.Button('submit',type='submit',class_="btn btn-primary")
     )
Exemplo n.º 10
0
 def del_article_form(self):
     return form.Form(
         form.Dropdown('name',
                       sorted(map(lambda x:x.name,articles.get_all_articles())),
                       form.notnull,
                       form.Validator('This Article Not Exist!',
                                      lambda x:articles.name_exist_p(x)),
                       description = "Delte Article Name:",
                       class_="form-control"),
         form.Button('submit', submit='submit', value='Delete it!',class_="btn btn-primary")
     )
Exemplo n.º 11
0
 def reset_password_form(self):
     return form.Form(form.Password(
         'new_password',
         form.notnull,
         form.Validator('Your password must at least 5 characters long.',
                        lambda x: users.is_valid_password(x)),
         description='新密码',
         class_="form-control"),
                      form.Password('re_password',
                                    form.notnull,
                                    description='确认密码',
                                    class_="form-control"),
                      form.Button('Reset Password',
                                  submit='submit',
                                  class_="btn btn-primary",
                                  html=u"提交"),
                      validators=[
                          form.Validator(
                              'Password Not Match!.',
                              lambda i: i.new_password == i.re_password)
                      ])
Exemplo n.º 12
0
 def POST(self, id):
     bids = model.getBids(int(id))
     D = model.get_by_id(int(id))
     if D.open == 0:
         raise web.seeother('/')
     highestBid = model.highestBid(int(id))
     buy_price = D.price
     if highestBid is not None:
         self.bid.validators.append(
             form.Validator(
                 "Bid is too low insert higher bid (" +
                 str(highestBid.price) + " by " + highestBid.buyer + ")",
                 lambda i: float(i.price) > highestBid.price))
     self.bid.validators.append(
         form.Validator(
             "Bid is too high insert lower bid (" + str(buy_price) + ")",
             lambda i: float(i.price) <= buy_price))
     if not self.bid.validates():
         return render.viewItem(D, id, bids, self.bid)
     else:
         model.newBid(id, self.bid.d.buyer, self.bid.d.price)
     raise web.seeother('/viewItem/' + str(id))
Exemplo n.º 13
0
 def add_article_form(self):
     return form.Form(
         form.Textbox('name',
                      form.notnull,
                      form.Validator('name already exists.',
                                     lambda x: not articles.name_exist_p(x)),
                      description = 'Name:',
                      class_="form-control"),
         form.Textbox('title',form.notnull,description = 'Title:',class_="form-control"),
         #form.Textbox('parent',description="Parent Name"),
         form.Dropdown('parent',
                       ["NEW_TOPIC"]+articles.get_all_first_level(),
                       form.notnull,
                       description="Parent Name:",
                       class_="form-control"),
         form.Textarea('content',description="Content",class_="form-control",rows="10"),
         form.Button('submit', type='submit', value='OK Publish this article!!',class_="btn btn-primary"),
         validators = [
             form.Validator("Parent Not Exist. If this is a first level article, use 'NEW_TOPIC",
                            lambda i:(i.parent=="NEW_TOPIC" or articles.parent_sans_p(i.parent)))
         ]
     )
Exemplo n.º 14
0
    def POST(self):
        if not session.user_id:
            raise web.seeother('/panel')

        f = user_edit_profile.edit_form()

        if not f.validates():
            return render.editprofile(f)

        if f.d['password']:
            userrow = get_userrow()

            def check_old_password(i):
                return hash_password(userrow['login'],
                                     i) == userrow['password']

            check_password_validator = form.Validator('is invalid',
                                                      check_old_password)

            f.validators.append(password_match_validator)
            f.password.validators = [password_validator]
            f.old_password.validators = [
                password_validator, check_password_validator
            ]

        if f.d['display_name']:
            f.validators.append(unique_display_name_validator)
            f.display_name.validators = [display_name_validator]

        if not f.validates():
            return render.editprofile(f)

        data_to_change = {'where': 'id = $id', 'vars': {'id': session.user_id}}

        if f.d['password']:  # changing password
            data_to_change['password'] = hash_password(userrow['login'],
                                                       f.d.password)

        if f.d['display_name']:  # changing display name
            data_to_change['display_name'] = f.d['display_name']

        if len(data_to_change.keys()) > 2:  # if changing anything
            db.update('whois_users', **data_to_change)

        raise web.seeother('/panel')
Exemplo n.º 15
0
 def login_form(self):
     return form.Form(
         form.Textbox('email',
                      form.notnull,
                      vemail,
                      description=u'邮箱',
                      class_="form-control"),
         form.Password('password',
                       form.notnull,
                       description=u'密码',
                       class_="form-control"),
         form.Button('Login',
                     submit='submit',
                     class_="btn btn-primary",
                     html=u"登陆"),
         validators=[
             form.Validator(
                 'Incorrect email / password combination.',
                 lambda i: users.is_correct_password(i.email, i.password)),
         ])
Exemplo n.º 16
0
 def POST(self):
     global currentUser
     item_id = web.cookies().get('item_id')
     item = get_item(int(item_id))
     bids = get_bids(int(item_id))
     if item.open == 0:
         raise web.seeother('/bid/' + item_id)
     highest_bid = get_highest_bid((int(item_id)))
     buy_price = item.price
     if highest_bid is not None:
         self.bid.validators.append(
             form.Validator("Price must be higher than highest bid (" + str(highest_bid.new_price) + " by " +
                            highest_bid.item_buyer + ")", lambda i: float(i.Price) > highest_bid.new_price))
     if not self.bid.validates():
         return render.bid(item, bids, self.bid, currentUser)
     else:
         db.insert('Bids', items_id=int(item_id), item_buyer=currentUser, 
                 new_price=self.bid['Price'].value, 
                 b_time=get_current_time().strftime(time_format))   
         raise web.seeother('/bid/' + item_id)
Exemplo n.º 17
0
    msg = property(get_msg)


def emailnotexists(email):
    "Return True if account with email `email` does not exist"
    exists = bool(db.select('users', where='email=$email', vars=locals()))
    return not (exists)


def check_len(phone):
    return len(web.numify(phone)) <= 15


petitionform = form.Form(
    form.Textbox('ptitle',
                 form.Validator("Title can't be blank", bool),
                 description="Title:",
                 size='80'),
    form.Textbox('pid',
                 form.Validator("Address can't be blank", bool),
                 form.Validator('ID already exists, Choose a different one.',
                                petitionnotexists),
                 pre='http://watchdog.net/c/',
                 description='URL:',
                 size='30'),
    form.Textarea('msg',
                  form.Validator("Description can't be blank", bool),
                  description="Description:",
                  rows='15',
                  cols='80'),
    form.Checkbox('tocongress', value='', description="Petition to Congress?"),
Exemplo n.º 18
0
import web
from web import form

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

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

myform = form.Form(
    form.Textbox("Nombre"),
    form.Textbox("Telefono", form.notnull, form.regexp('\d+',
                                                       'Must be a digit'),
                 form.Validator('Must be more than 5', lambda x: int(x) > 5)),
    form.Textbox(
        "Nacimiento", form.notnull, form.regexp('\d+', 'Must be a digit'),
        form.Validator('No puede ser mayor a 2016', lambda x: int(x) < 2016)),
    form.Textarea('Email'), form.Checkbox('INE', value='INE'),
    form.Dropdown('Genero', ['Macho Alfa', 'Mujer']))


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.formtest(form)

    def POST(self):
        form = myform()
        if not form.validates():
            return render.formtest(form)
Exemplo n.º 19
0
    def create_form(self):
        """ Create an HTML form for user input """

        myform = form.Form(
            Label("Project Configuration", True),
            SizedTextbox("URL",
                         100,
                         'Starting URL for the project',
                         form.Validator("", lambda x: len(x)),
                         value='http://www.foo.com'),
            SizedTextbox("Name",
                         20,
                         'Name for the project',
                         form.Validator("", lambda x: len(x)),
                         value='foo'),
            SizedTextbox("Base Directory",
                         50,
                         'Directory for saving downloaded files',
                         form.Validator("", lambda x: len(x)),
                         value='~/websites'),
            MyDropbox("Verbosity",
                      "0=>No messages, 5=>Maximum messages",
                      [0, 1, 2, 3, 4, 5],
                      value=2),
            Label("Network Configuration", True),
            SizedTextbox("Proxy Server", 50,
                         "Proxy server address for your network, if any"),
            SizedTextbox("Proxy Server Port",
                         10,
                         "Port number for the proxy server",
                         value=80),
            SizedTextbox(
                "Proxy Server Username", 20,
                "Username for authenticating the proxy server (leave blank for unauthenticated proxies)"
            ),
            SizedTextbox(
                "Proxy Server Password", 20,
                "Password for authenticating the proxy server (leave blank for unauthenticated proxies)"
            ),
            Label("Download Types/Caching/Protocol Configuration", True),
            MyDropbox("HTML", 'Save HTML pages ?', ["Yes", "No"]),
            MyDropbox("Images", 'Save images in pages ?', ["Yes", "No"]),
            MyDropbox("Video", 'Save video URLs (movies) ?', ["No", "Yes"]),
            MyDropbox("Flash", 'Save Adobe Flash URLs ?', ["No", "Yes"]),
            MyDropbox("Audio", 'Save audio URLs (sounds) ?', ["No", "Yes"]),
            MyDropbox(
                "Documents",
                'Save Microsoft Office, Openoffice, PDF and Postscript files ?',
                ["Yes", "No"]),
            MyDropbox("Javascript", 'Save server-side javascript URLs ?',
                      ["Yes", "No"]),
            MyDropbox("Javaapplet", 'Save java applet class files ?',
                      ["Yes", "No"]),
            MyDropbox(
                "Query Links",
                'Save links of the form "http://www.foo.com/query?param=val" ?',
                ["Yes", "No"]),
            MyDropbox("Caching", 'Enable URL caching in HarvestMan ?',
                      ["Yes", "No"]),
            MyDropbox(
                "Data Caching",
                'Enable caching of URL data in the cache (requires more space) ?',
                ["No", "Yes"]),
            MyDropbox("HTTP Compression",
                      'Accept gzip compressed data from web servers ?',
                      ["Yes", "No"]),
            SizedTextbox(
                "Retry Attempts",
                10,
                'Number of additional download tries for URLs which produce errors',
                value=1),
            Label("Download Limits/Extent Configuration", True),
            MyDropbox("Fetch Level", 'Fetch level for the crawl (see FAQ)',
                      [0, 1, 2, 3, 4]),
            MyDropbox(
                "Crawl Sub-domains",
                'Crawls "http://bar.foo.com" when starting URL belongs to "http://foo.com"',
                ["No", "Yes"]),
            SizedTextbox(
                "Maximum Files Limit",
                10,
                'Stops crawl when number of files downloaded reaches this limit',
                value=5000),
            SizedTextbox("Maximum File Size Limit",
                         10,
                         'Ignore URLs whose size is larger than this limit',
                         value=5242880),
            SizedTextbox(
                "Maximum Connections Limit",
                10,
                'Maximum number of simultaneously open HTTP connections',
                value=5),
            SizedTextbox(
                "Maximum Bandwidth Limit(kb)",
                10,
                'Maximum number of bandwidth used for given HTTP connections',
                value=0),
            SizedTextbox(
                "Crawl Time Limit",
                10,
                'Stops crawl after the crawl duration reaches this limit',
                value=-1),
            Label("Download Rules/Filters Configuration", True),
            MyDropbox("Robots Rules",
                      'Obey robots.txt and META ROBOTS rules ?',
                      ["Yes", "No"]),
            SizedTextbox("URL Filter String", 100,
                         'A filter string for URLs (see FAQ)'),
            # SizedTextbox("Server Filter String",100, 'A filter string for servers (see FAQ)'),
            SizedTextbox(
                "Word Filter String", 100,
                'A generic word filter based on regular expressions to filter web pages'
            ),
            MyDropbox(
                "JunkFilter",
                'Enable the advertisement/banner/other junk URL filter ?',
                ["Yes", "No"]),
            Label("Download Plugins Configuration", True),
            Label("Add up-to 5 valid plugins in the boxes below", italic=True),
            SizedTextbox(
                "Plugin 1", 20,
                'Enter the name of your plugin module here, without the .py* suffix'
            ),
            SizedTextbox(
                "Plugin 2", 20,
                'Enter the name of your plugin module here, without the .py* suffix'
            ),
            SizedTextbox(
                "Plugin 3", 20,
                'Enter the name of your plugin module here, without the .py* suffix'
            ),
            SizedTextbox(
                "Plugin 4", 20,
                'Enter the name of your plugin module here, without the .py* suffix'
            ),
            SizedTextbox(
                "Plugin 5", 20,
                'Enter the name of your plugin module here, without the .py* suffix'
            ),
            Label("Files Configuration", True),
            SizedTextbox(
                "Url Tree File",
                20,
                'A filename which will capture parent/child relationship of all processed URLs',
                value=''),
            MyDropbox(
                "Archive Saved Files",
                'Archive all saved files to a single tar archive file ?',
                ["No", "Yes"]),
            MyDropbox("Archive Format", 'Archive format (tar.bz2 or tar.gz)',
                      ["bzip", "gzip"]),
            MyDropbox("Serialize URL Headers",
                      'Serialize all URL headers to a file (urlheaders.db) ?',
                      ["Yes", "No"]),
            MyDropbox(
                "Localise Links",
                'Convert outward (web) pointing links to disk pointing links ?',
                ["No", "Yes"]),
            Label("Misc Configuration", True),
            MyDropbox(
                "Create Project Browse Page",
                'Create an HTML page which summarizes all crawled projects ?',
                ["No", "Yes"]),
            Label("Advanced Configuration Settings", True),
            Label(
                'These are configuration parameters which are useful only for advanced tweaking. Most users can ignore the following settings and use the defaults',
                italic=True),
            Label("Download Limits/Extent/Filters/Rules Configuration", True,
                  True),
            MyDropbox("Fetch Image Links Always",
                      'Ignore download rules when fetching images ?',
                      ["Yes", "No"]),
            MyDropbox("Fetch Stylesheet Links Always",
                      'Ignore download rules when fetching stylesheets ?',
                      ["Yes", "No"]),
            SizedTextbox(
                "Links Offset Start",
                10,
                'Offset of child links measured from zero (useful for crawling web directories)',
                value=0),
            SizedTextbox(
                "Links Offset End",
                10,
                'Offset of child links measured from end (useful for crawling web directories)',
                value=-1),
            MyDropbox(
                "URL Depth",
                'Maximum depth of a URL in relation to the starting URL',
                [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]),
            MyDropbox(
                "External URL Depth",
                'Maximum depth of an external URL in relation to its server root (useful for only fetchlevels >1)',
                [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]),
            MyDropbox(
                "Ignore TLDs (Top level domains)",
                'Consider http://foo.com and http://foo.org as the same server (dangerous)',
                ["No", "Yes"]),
            SizedTextbox("URL Priority String", 100,
                         'A priority string for URLs (see FAQ)'),
            # SizedTextbox("Server Priority String",100, 'A priority string for servers (see FAQ)'),
            Label("Parser Configuration", True, True),
            Label("Enable/Disable parsing of the tags shown below",
                  italic=True),
            MyDropbox("Tag <a>", 'Enable parsing of <a> tags ?',
                      ["Yes", "No"]),
            MyDropbox("Tag <applet>", 'Enable parsing of <applet> tags ?',
                      ["Yes", "No"]),
            MyDropbox("Tag <area>", 'Enable parsing of <area> tags ?',
                      ["Yes", "No"]),
            MyDropbox("Tag <base>", 'Enable parsing of <base> tags ?',
                      ["Yes", "No"]),
            MyDropbox("Tag <body>", 'Enable parsing of <body> tags ?',
                      ["Yes", "No"]),
            MyDropbox("Tag <embed>", 'Enable parsing of <embed> tags ?',
                      ["Yes", "No"]),
            MyDropbox("Tag <form>", 'Enable parsing of <form> tags ?',
                      ["Yes", "No"]),
            MyDropbox("Tag <frame>", 'Enable parsing of <frame> tags ?',
                      ["Yes", "No"]),
            MyDropbox("Tag <img>", 'Enable parsing of <img> tags ?',
                      ["Yes", "No"]),
            MyDropbox("Tag <link>", 'Enable parsing of <link> tags ?',
                      ["Yes", "No"]),
            MyDropbox("Tag <meta>", 'Enable parsing of <meta> tags ?',
                      ["Yes", "No"]),
            MyDropbox("Tag <object>", 'Enable parsing of <object> tags ?',
                      ["Yes", "No"]),
            MyDropbox("Tag <option>", 'Enable parsing of <option> tags ?',
                      ["No", "Yes"]),
            MyDropbox("Tag <script>", 'Enable parsing of <script> tags ?',
                      ["Yes", "No"]),
            Label("Crawler System Configuration", True, True),
            MyDropbox("Worker Threads",
                      'Enable worker (downloader) thread pool ?',
                      ["Yes", "No"]),
            SizedTextbox("Worker Thread Count",
                         10,
                         'Size of the worker thread pool',
                         value=10),
            SizedTextbox("Worker Thread Timeout",
                         10,
                         'Timeout for the worker thread pool',
                         value=1200.0),
            SizedTextbox("Tracker Thread Count",
                         10,
                         'Size of the tracker (crawler/fetcher) thread pool',
                         value=10),
            SizedTextbox("Tracker Thread Timeout",
                         10,
                         'Timeout for the tracker thread pool',
                         value=240.0),
            SizedTextbox(
                "Tracker Sleep Time",
                10,
                'Duration of sleep time for tracker threads between cycles of activity',
                value=3.0),
            MyDropbox("Tracker Sleep Randomized",
                      'Randomize the tracker thread sleep time ?',
                      ["Yes", "No"]))

        return myform
    form.Textbox("firstname", form.notnull),
    form.Textbox("lastname", form.notnull),
    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.Password(
        "password",
        form.notnull,
        form.regexp(r'^.{8,}$', "debe ser mayor de 7")  #
        # form.Validator("Debe ser de minimo 7 caracteres", lambda i: len(i) > 7)
    ),
    form.Password("re_password", form.notnull),
    form.Checkbox("accept_license",
                  form.Validator("Acepta las clausulas",
                                 lambda i: i == 'true'),
                  value='true'),
    form.Button("submit"),
    validators=[
        form.Validator("Los passwords no coinciden",
                       lambda i: i.password == i.re_password)
    ])


class index:
    def GET(self2):

        user = ''
        if ses._initializer['logged_in'] == True:
            user = ses._initializer['user']
Exemplo n.º 21
0
from config import view, encryption_key, site_name, db

user = session.get_session()
siteName = site_name
vemail = form.regexp(r'.+@.+', '邮箱格式不对')
p = re.compile(r"(?:^|\s)[-a-z0-9_.+]+@(?:[-a-z0-9]+\.)+[a-z]{2,6}(?:\s|$)",
               re.IGNORECASE)

#表单
login_form = form.Form(
    form.Textbox('email', form.notnull, vemail, description='邮箱:'),
    form.Password('password', form.notnull, description='密码:'),
    validators=[
        form.Validator(
            '邮箱地址或密码不正确',
            lambda i: users.is_correct_password(i.email, i.password))
    ])

register_form = form.Form(
    form.Textbox(
        'username',
        form.notnull,
        form.Validator('用户名已存在.', lambda x: users.is_username_available(x)),
        #form.Validator('请以字母开头,不超过15个字母、数字,保存后不可修改', #todo
        #lambda x: users.is_username_available(x)),
        description='用户名(以字母开头的2-16个字母、数字组合):'),
    form.Textbox('email',
                 form.notnull,
                 vemail,
                 form.Validator('邮箱已经存在.',
Exemplo n.º 22
0
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)
                          ])

HTMLurls = (
    "/register",
    "register",
    "/done",
    "done",
    "/.*",
    "defaultUrl",
)


def sendMyHeader(myTitle):
    # web.ctx.env
Exemplo n.º 23
0
        if gv.sd['password'] == password_hash(qdict['pw'], gv.sd['salt']):
            return True
        if redirect:
            raise web.unauthorized()
        return False

    if redirect:
        raise web.seeother('/login')
    return False


signin_form = form.Form(form.Password('password',
                                      description=_('Password') + ':'),
                        validators=[
                            form.Validator(
                                _("Incorrect password, please try again"),
                                lambda x: gv.sd['password'] == password_hash(
                                    x.password, gv.sd['salt']))
                        ])


def get_input(qdict, key, default=None, cast=None):
    """
    Checks data returned from a UI web page.
    
    
    """
    result = default
    if key in qdict:
        result = qdict[key]
        if cast is not None:
            result = cast(result)
Exemplo n.º 24
0
store = web.session.DiskStore('sessions')

session = web.session.Session(app, store, initializer={'count': 0})

#Makes sure the template engine looks under the folder 'templates/' for my html files.  Also makes globals do something(?) so that I can save variables as a session.

render = web.template.render('templates/', globals={'context': session})

# The Forms used for input

age_form = form.Form(
    form.Textbox('number',
                 form.notnull,
                 form.regexp('^-?\d+$', 'Not a number.'),
                 form.Validator("Too young, don't use this tool.",
                                lambda x: int(x) > 17),
                 size="1",
                 maxlength="2",
                 description='Age:'))

#At some point I would like to figure out how to validate age_form to prevent age < 18.

gender_form = form.Form(form.Radio('Gender:', ['Female', 'Male'],
                                   form.notnull))

smoke_form = form.Form(
    form.Radio('Smoking:', ['Never Smoker', 'Past Smoker', 'Current Smoker'],
               form.notnull))

sex_form = form.Form(
    form.Radio('Sexually Active?:', [
Exemplo n.º 25
0
myform = form.Form( 
    form.Textbox('nombre', maxlength="40", description="Nombre:"),
	form.Textbox('apellidos', maxlength="50", description="Apellidos:"),
	form.Textbox('dni', maxlength="9", size="9", description="DNI:"),
	form.Textbox('correo', maxlength="50", size="15", description="Correo Electronico:"),
	form.Dropdown('dia', range(1,32), description="Dia:"),
	form.Dropdown('mes', range(1,13), description="Mes:"),
	form.Dropdown('anio', range(1940,2014), description="Anio:"),
	form.Textarea('direccion', maxlength="55", size="35", description="Direccion:"),	
	form.Password('passw', maxlength="10", size="12", description="Password:"******"10", size="12", description="Repetir:"),
	form.Radio('forma_pago', ['contra reembolso', 'tarjeta visa'], description="Forma de pago:"),
	form.Textbox('numero_visa', maxlength="19", size="20", description="Numero Visa"),
    form.Checkbox('check',
		form.Validator("Debe aceptar las clausulas.", lambda i: "check" not in i), description="Acepto las clausulas"), 
	form.Button('Aceptar'),
	
	
    validators = [
    	form.Validator('El campo nombre no puede estar vacio.', lambda i: len(str(i.nombre))>0),
		form.Validator('El campo apellidos no puede estar vacio.', lambda i: len(str(i.apellidos))>0),
		form.Validator('El campo dni no puede estar vacio.', lambda i: len(str(i.dni))>0),
		form.Validator('El campo correo no puede estar vacio.', lambda i: len(str(i.correo))>0),
		form.Validator('El campo direccion no puede estar vacio.', lambda i: len(str(i.direccion))>0),
		form.Validator('El campo numero visa no puede estar vacio.', lambda i: len(str(i.numero_visa))>0),
		form.Validator('Fecha Incorrecta.', lambda x: not(
			(int(x.dia)==31 and int(x.mes)==2) or 
			(int(x.dia)==30 and int(x.mes)==2) or 
			(int(x.dia)==29 and int(x.mes)==2 and int(x.anio)%4!=0) or 
			(int(x.dia)==31 and (int(x.mes)==4 or int(x.mes)==6 or int(x.mes)==9 or int(x.mes)==11))
Exemplo n.º 26
0
    # '/login', 'login',
)

# this line creates the application object
# just no better place to put it, in a big app we'd 
# have better code structure
app = web.application(urls, globals(), autoreload=False)

#
# This is the form object that is renderdd on the webpage
# Here is an example of the form we used as a guide: http://webpy.org/form#example
#
form_comparators=['Psychiatry','Cognition','Other Neurologic','Fall Risk','Bleeding']

myform = form.Form(
    form.Textbox('Index_drug',form.Validator('Field cannot be empty', lambda x: not x=="hello")),
    form.Dropdown('Comparator',form_comparators,value=0),
    form.Textarea('Druglist',value='None'),
    form.Checkbox('Option_1',value="0"),
    form.Checkbox('Option_2',value="0"),
  ) 

# this is one "view"
# it has GET and POST methods, which do different things
# GET is for just viewing the form, and POST is for submitting data
class index: 
    def GET(self): 

        # on a get request, 1) create the form object 
        # 2) render the page, passing the form object to the template
        # (it infers the basicform.html from the name of the basicform method) 
Exemplo n.º 27
0
        if result:
            raise web.badrequest(u'Twoje urządzenie jest już zarejestrowane!')

        db.insert('whois_devices',
                  mac_addr=user_mac,
                  user_id=uid,
                  last_seen=int(time.time()))

        return u'Brawo! Właśnie dokonałeś rejestracji swojego urządzenia w systemie :) Od tej chwili jego obecność będzie oznaczało również Twoją.'


password_validator = form.regexp(r'.{3,100}$', u'od 3 do 100 znaków')
display_name_validator = form.regexp(r'.{3,100}$', u'od 3 do 100 znaków')
unique_username_validator = form.Validator(
    u'Podana nazwa użytkownika jest już zajęta', lambda f: db.query(
        'SELECT COUNT(id) AS cnt FROM whois_users WHERE login == $login',
        vars={'login': f.login})[0]['cnt'] == 0)
password_match_validator = form.Validator(
    u'Hasła w dwóch polach się nie zgadzają',
    lambda i: i.password == i.password2)
unique_display_name_validator = form.Validator(
    u'Ktoś już używa takiej nazwy...', lambda f: db.query(
        'SELECT COUNT(id) AS cnt FROM whois_users WHERE display_name == $display_name',
        vars={'display_name': f.display_name})[0]['cnt'] == 0)
login_validator = form.regexp(r'[a-zA-Z0-9_]{3,32}$',
                              u'od 3 do 32 znaków, alfanumeryczny')


class register_user:
    register_form = form.Form(form.Textbox('login',
                                           login_validator,
Exemplo n.º 28
0
    ('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 = urllib.request.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
        rec_len = int(data)
Exemplo n.º 29
0
        '/result_sensor_ultrasonic', 'Result_sensor_ultrasonic',
        '/result_sensor_infrared','Result_sensor_infrared',
        '/toggle_ultrasonic','Toggle_ultrasonic',
        '/toggle_infrared','Toggle_infrared',
        '/camera/(.*)','Camera_angle',
       # '/','',
     #   '/','',
        '/(.*)','Error_page'
)

app = web.application(urls, globals())

loginform = form.Form(
    form.Textbox("USERNAME",
        form.notnull,
        form.Validator('wrong', lambda x: x == "martin")),
    form.Textbox("PASSWORD",
        form.notnull,
        form.Validator('wrong', lambda x: x == "12341234")),
    form.Checkbox('I am not a robot')
)

routeform = form.Form(

)

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

def gpio_startup():
    global a1,a2,b1,b2,gpiodidstartup,p,servomotor_camera,p1
    GPIO.setmode(GPIO.BOARD)
Exemplo n.º 30
0
)

app = web.application(urls, globals())
render = web.template.render('templates/')
if web.config.get('_session') is None:
  session = web.session.Session(app, web.session.DiskStore('sessions'), {'user':None})
  web.config._session = session
else:
  session = web.config._session

register_form = form.Form(
  form.Textbox("username", description="Username"),
  form.Password("password", description="Password"),
  form.Button("submit", type="submit", description="Login"),
  validators = [
    form.Validator("All fields are mandatory", lambda i: i.username == "" or i.password == "")]
)

#-----------------------------------------------------------------------
# FUNCTIONS

#-----------------------------------------------------------------------
def myrepr(buf):
  if buf:
    return repr(buf)
  return

#-----------------------------------------------------------------------
# CLASSES

#-----------------------------------------------------------------------