コード例 #1
0
ファイル: test_auth.py プロジェクト: hucruz/acl.py
def test_registration_fails_if_user_exists():
    user = auth.User(username='******', email='*****@*****.**')
    user.create()
    reg_form = authforms.register_form()
    assert not reg_form.validates(
        web.storify({
            'username': '******',
            'email': '*****@*****.**',
            'password': '******',
            'confirm': 'abc123',
        }))
    assert not reg_form.validates(
        web.storify({
            'username': '******',
            'email': '*****@*****.**',  # still the same e-mail
            'password': '******',
            'confirm': 'abc123',
        }))
    assert not reg_form.validates(
        web.storify({
            'username': '******',
            'email': '*****@*****.**',
            'password': '******',
            'confirm': 'abc123',
        }))
コード例 #2
0
ファイル: test_auth.py プロジェクト: hucruz/acl.py
def test_login_with_real_account():
    user = auth.User(username='******', email='*****@*****.**')
    user.password = '******'
    user.create()
    login_form = authforms.login_form()
    assert not login_form.validates(
        web.storify({
            'username': '******',
            'password': '******',
        }))
    user.activate()
    user.store()
    assert login_form.validates(
        web.storify({
            'username': '******',
            'password': '******',
        })), login_form.note
    assert not login_form.validates(
        web.storify({
            'username': '******',
            'password': '******',
        }))
    assert not login_form.validates(
        web.storify({
            'username': '******',
            'password': '******',
        }))
コード例 #3
0
ファイル: test_auth.py プロジェクト: hucruz/acl.py
def test_email_belongs_to_account_validation():
    user = auth.User(username='******', email='*****@*****.**')
    user.create()
    email_form = authforms.email_request_form()
    assert email_form.validates(web.storify({
        'email': user.email,
    })), email_form.note
    assert not email_form.validates(web.storify({
        'email': '*****@*****.**',
    }))
コード例 #4
0
ファイル: test_auth.py プロジェクト: andyjia/acl.py
def test_email_belongs_to_account_validation():
    user = auth.User(username='******', email='*****@*****.**')
    user.create()
    email_form = authforms.email_request_form()
    assert email_form.validates(web.storify({
        'email': user.email,
    })), email_form.note
    assert not email_form.validates(web.storify({
        'email': '*****@*****.**',
    }))
コード例 #5
0
ファイル: util.py プロジェクト: keizo/kulu
 def __setitem__(self, key, values):
     #make values a storage object if it's not...
     #there is probably a cleaner way to do this
     if issubclass(values,dict) is not True:
         values = web.storify({key:values})
         
     if self.has_key(key):
         web.update(self.table,where=self.index+'=$key',vars=locals(),**web.storify(values,**self[key]))
     else:
         web.insert(self.table,**web.storify({self.index:key},**values))
     dict.__setitem__(self,key,values)
コード例 #6
0
ファイル: test_auth.py プロジェクト: andyjia/acl.py
def test_registration_pw_confirmation():
    reg_form = authforms.register_form()
    assert reg_form.validates(web.storify({
        'username': '******',
        'email': '*****@*****.**',
        'password': '******',
        'confirm': 'abc123'
    })), reg_form.note
    assert not reg_form.validates(web.storify({
        'username': '******',
        'email': '*****@*****.**',
        'password': '******',
        'confirm': 'wont repeat'
    }))
コード例 #7
0
ファイル: account.py プロジェクト: waile23/todo
    def POST(self):
        params = web.input()
        if params.get('v') and params.get('email'):
            row = pdfindpass.find(params.get('email'), params.get('v'))
            user = pduser.loaduser_by_email(params.get('email'))
            if (row is None) or (row.f_create_time <
                                 (time.time() - 60 * 60 * 24 * 30)):
                return render.newpass({
                    'code': -1,
                    'message': '链接过期或者失效',
                    'params': params
                })
            #update info

            updateinfo = web.storify({})
            updateinfo.u_pass = md5.new(params.get('u_pass')).hexdigest()
            updateinfo.u_id = user.u_id
            pduser.update_by_insert(updateinfo)
            #clear info
            pdfindpass.deleteall(params.get('email'))

            return render.newpass({
                'code': 1,
                'message': '密码修改成功',
                'params': params
            })
        return render.newpass({'code': 0, 'message': '', 'params': params})
コード例 #8
0
ファイル: test.py プロジェクト: keizo/kulu
 def GET(self,nid):
     #node = mod.node.load(nid)
     nodes, page_nums = mod.node.listing_default()
     pickled_nodes = []
     for node in nodes:
         pickled_nodes.append(pickle.dumps(node))
     unpickled = []
     start = time.time()
     for node in pickled_nodes:
         unpickled.append(pickle.loads(node))
     print time.time() - start
     print ': time to unpickle some objects'
     
     
     expanded = []
     new = {'readmore':True, 'teaser':'there is nothing to see here',
            'links':'no links to see here', 'time':time.time()}
     start = time.time()
     for node in unpickled:
         expanded = web.storify(new,**node)
     print time.time()-start
     print ': time to storify some nodes'
     
     
     
     for node in unpickled:
         print node.title + '\n'
コード例 #9
0
ファイル: test_auth.py プロジェクト: hucruz/acl.py
def test_registration_pw_confirmation():
    reg_form = authforms.register_form()
    assert reg_form.validates(
        web.storify({
            'username': '******',
            'email': '*****@*****.**',
            'password': '******',
            'confirm': 'abc123'
        })), reg_form.note
    assert not reg_form.validates(
        web.storify({
            'username': '******',
            'email': '*****@*****.**',
            'password': '******',
            'confirm': 'wont repeat'
        }))
コード例 #10
0
ファイル: test_auth.py プロジェクト: andyjia/acl.py
def test_wrong_new_password():
    reset_form = authforms.pw_reset_form()
    assert not reset_form.validates(web.storify({
        'password': '******',
        'new': '123abc',
        'confirm': '123123'
    }))
コード例 #11
0
ファイル: node.py プロジェクト: keizo/kulu
def _node_load(node):
    """Piggy back the data from node modules if available."""
    if mod.has_key(node.type) and hasattr(mod[node.type], 'node_load'):
        additions = mod[node.type].node_load(node.nid,node.vid)
        node = web.storify(additions,**node)
    else: raise "node type does not exist, but it's in the database. check for missing module", node.type
    return node
コード例 #12
0
ファイル: test_auth.py プロジェクト: hucruz/acl.py
def test_wrong_new_password():
    reset_form = authforms.pw_reset_form()
    assert not reset_form.validates(
        web.storify({
            'password': '******',
            'new': '123abc',
            'confirm': '123123'
        }))
コード例 #13
0
 def cookies(self, env, **defaults):
     # adopted from web.cookies
     cookie = Cookie.SimpleCookie()
     cookie.load(env.get('HTTP_COOKIE', ''))
     d = web.storify(cookie, **defaults)
     for k, v in d.items():
         d[k] = v and urllib.unquote(v)
     return d
コード例 #14
0
ファイル: datafile.py プロジェクト: catabram/forecast
def load_stocks(stock_no): 
    lfile = '%s/dailyh_add/%s.csv' % (const_root_local,stock_no)      
    rows=[] 
    with open(lfile,'rb') as f:
        lines = f.readlines()
        rows = [web.storify(json.loads(line.strip())) for line in lines if line] 
    rows = [r for r in rows if int(r['volume'])>0]    
    return rows
コード例 #15
0
ファイル: code.py プロジェクト: RaceList/openlibrary
 def cookies(self, env, **defaults):
     # adopted from web.cookies
     cookie = Cookie.SimpleCookie()
     cookie.load(env.get('HTTP_COOKIE', ''))
     d = web.storify(cookie, **defaults)
     for k, v in d.items():
         d[k] = v and urllib.unquote(v)
     return d
コード例 #16
0
def validateConfig(newConfig):
    messages = {}
    s = web.storify(newConfig, *config.keys())
    try:
        fp = open(s.iTunesFile, 'rb')
        fp.close()
    except IOError:
        messages['iTunesFile'] = "Not a valid iTunes file."
    return messages
コード例 #17
0
def load_stocks(stock_no):
    lfile = '%s/dailyh_add/%s.csv' % (const_root_local, stock_no)
    rows = []
    with open(lfile, 'rb') as f:
        lines = f.readlines()
        rows = [
            web.storify(json.loads(line.strip())) for line in lines if line
        ]
    rows = [r for r in rows if int(r['volume']) > 0]
    return rows
コード例 #18
0
ファイル: threads.py プロジェクト: drew/seddit
def threadtranscript(threadid):
    thread = getthread(threadid)
    messages = getmessages(threadid)
    lastmessage = 0 # see javascript api for more information
    
    thread = web.storify(thread)
    thread.date_started = web.datestr(thread.date_started)
    
    transcript = { 'thread': thread, 'messages': None }
    transcript = web.storify(transcript)
    
    transcript.messages = []
    
    for message in messages:
        transcript.messages.append({ 'id': message.id, 'author_id': message.author_id, 'author': people.getperson(message.author_id).name, 'content': message.content, 'time': web.datestr(message.date_sent)})
        lastmessage = message.id
        
    transcript.thread.last_message = lastmessage
    
    return transcript
コード例 #19
0
ファイル: test_auth.py プロジェクト: andyjia/acl.py
def test_registration_fails_if_user_exists():
    user = auth.User(username='******', email='*****@*****.**')
    user.create()
    reg_form = authforms.register_form()
    assert not reg_form.validates(web.storify({
        'username': '******',
        'email': '*****@*****.**',
        'password': '******',
        'confirm': 'abc123',
    }))
    assert not reg_form.validates(web.storify({
        'username': '******',
        'email': '*****@*****.**', # still the same e-mail
        'password': '******',
        'confirm': 'abc123',
    }))
    assert not reg_form.validates(web.storify({
        'username': '******',
        'email': '*****@*****.**',
        'password': '******',
        'confirm': 'abc123',
    }))
コード例 #20
0
ファイル: test_auth.py プロジェクト: andyjia/acl.py
def test_login_with_real_account():
    user = auth.User(username='******', email='*****@*****.**')
    user.password = '******'
    user.create()
    login_form = authforms.login_form()
    assert not login_form.validates(web.storify({
        'username': '******',
        'password': '******',
    }))
    user.activate()
    user.store()
    assert login_form.validates(web.storify({
        'username': '******',
        'password': '******',
    })), login_form.note
    assert not login_form.validates(web.storify({
        'username': '******',
        'password': '******',
    }))
    assert not login_form.validates(web.storify({
        'username': '******',
        'password': '******',
    }))
コード例 #21
0
ファイル: account.py プロジェクト: waile23/todo
	def POST(self):
		params = web.input()
		if params.get('v') and params.get('email'):
			row = pdfindpass.find(params.get('email'),params.get('v'))	
			user = pduser.loaduser_by_email(params.get('email'))
			if (row is None) or (row.f_create_time < (time.time()-60*60*24*30)):
				return render.newpass({'code':-1,'message':'链接过期或者失效','params':params})
			#update info 
			
			updateinfo = web.storify({})
			updateinfo.u_pass = md5.new(params.get('u_pass')).hexdigest()
			updateinfo.u_id = user.u_id
			pduser.update_by_insert(updateinfo)
			#clear info
			pdfindpass.deleteall(params.get('email'))
			
			return render.newpass({'code':1,'message':'密码修改成功','params':params})
		return render.newpass({'code':0,'message':'','params':params})
コード例 #22
0
    def PUT(self, transferId):
        ''' PUT /transfer/{ID}
        
        Updates one transfer.
        '''
        if not transferId:
            msg = "Cannot PUT to the transfer resource without specifying a valid transfer resource ID in the path transfer/{ID}"
            web.debug(msg)
            raise web.BadRequest(msg)

        try:
            transferId = int(transferId)
        except ValueError as e:
            msg = "Invalid transfer id: " + str(e)
            web.debug(msg)
            raise web.BadRequest(msg)

        try:
            raw = web.data()
            if config.audit:
                web.debug("Request Body: " + str(raw))
            parsed = json.loads(raw)
            transfer = web.storify(parsed)
            transfer = policy.update(transferId, transfer)
            return json.dumps(transfer)
        except TransferNotFound:
            msg = "Cannot PUT to transfer resource transfer/" + str(
                transferId) + ". Resource not found."
            web.debug(msg)
            raise web.BadRequest(msg)
        except MalformedTransfer as e:
            msg = "Bad request body in PUT to transfer/ resource: " + str(e)
            web.debug(msg)
            raise web.BadRequest(msg)
        except NotAllowed as e:
            msg = "Bad request body in PUT to transfer/ resource: " + str(e)
            web.debug(msg)
            raise web.BadRequest(msg)
        except PolicyError as e:
            msg = "Internal server error: " + str(e)
            web.debug(msg)
            raise web.InternalError(msg)
コード例 #23
0
    def POST(self, transferId=None):
        '''POST /transfer
        
        Not allowed to POST /transfer/{ID}.
        '''
        if transferId:
            raise web.NoMethod()

        try:
            raw = web.data()
            if config.audit:
                web.debug("Request Body: " + str(raw))
            parsed = json.loads(raw)
            transfer = web.storify(parsed)
            transfer = policy.add(transfer)
            return json.dumps(transfer)
        except MalformedTransfer as e:
            msg = "Bad request body in POST to transfer/ resource: " + str(e)
            web.debug(msg)
            raise web.BadRequest(msg)
コード例 #24
0
ファイル: service.py プロジェクト: robes/adapt-policy-service
 def POST(self, transferId=None):
     '''POST /transfer
     
     Not allowed to POST /transfer/{ID}.
     '''
     if transferId:
         raise web.NoMethod()
     
     try:
         raw = web.data()
         if config.audit:
             web.debug("Request Body: " + str(raw))
         parsed = json.loads(raw)
         transfer = web.storify(parsed)
         transfer = policy.add(transfer)
         return json.dumps(transfer)
     except MalformedTransfer as e:
         msg = "Bad request body in POST to transfer/ resource: " + str(e)
         web.debug(msg)
         raise web.BadRequest(msg)
コード例 #25
0
ファイル: service.py プロジェクト: robes/adapt-policy-service
 def PUT(self, transferId):
     ''' PUT /transfer/{ID}
     
     Updates one transfer.
     '''
     if not transferId:
         msg = "Cannot PUT to the transfer resource without specifying a valid transfer resource ID in the path transfer/{ID}"
         web.debug(msg)
         raise web.BadRequest(msg)
     
     try:
         transferId = int(transferId)
     except ValueError as e:
         msg = "Invalid transfer id: " + str(e)
         web.debug(msg)
         raise web.BadRequest(msg)
     
     try:
         raw = web.data()
         if config.audit:
             web.debug("Request Body: " + str(raw))
         parsed = json.loads(raw)
         transfer = web.storify(parsed)
         transfer = policy.update(transferId, transfer)
         return json.dumps(transfer)
     except TransferNotFound:
         msg = "Cannot PUT to transfer resource transfer/"+str(transferId)+". Resource not found."
         web.debug(msg)
         raise web.BadRequest(msg)
     except MalformedTransfer as e:
         msg = "Bad request body in PUT to transfer/ resource: " + str(e)
         web.debug(msg)
         raise web.BadRequest(msg)
     except NotAllowed as e:
         msg = "Bad request body in PUT to transfer/ resource: " + str(e)
         web.debug(msg)
         raise web.BadRequest(msg)
     except PolicyError as e:
         msg = "Internal server error: " + str(e)
         web.debug(msg)
         raise web.InternalError(msg)
コード例 #26
0
ファイル: main.py プロジェクト: aalto-ui/SemanticCollage
    def POST(self):

        data = web.input()
        data_info = web.storify(data).image
        filename = randomString('x.png')
        fullPath = "static/images/" + filename

        outfile = open(fullPath, 'wb')
        outfile.write(data_info)
        outfile.close()

        palette = get_data(filename, "[u'upload']", 'upload')
        labels = 0

        pyDictName = {
            'imgSrc': fullPath,
            'labels': labels,
            'colorPalette': palette
        }
        web.header('Content-Type', 'application/json')
        return json.dumps(pyDictName)
コード例 #27
0
ファイル: node.py プロジェクト: keizo/kulu
 def POST(self, nid):
     page = self.page
     node = mod.node.load(nid)
     if node is None:
         pagenotfound()
     else:
         self._checkaccess(node)
         form = _form_node(node.type, page.user.roles.keys())
         
         if form.validates():
             data = form.d
             node.time_now = int(time.time())
             node.uid = page.user.uid
             node = web.storify(data, **node)
             
             # TODO: update all publishing options in 'node' table
             web.update('node', where='nid=$node.nid AND vid=$node.vid',
                 vid=(node.vid+1), vars=locals())
             # Do module specific updates.
             if hasattr(mod[node.type], 'node_update'):
                 mod[node.type].node_update(node)
                 
             web.redirect('/node/'+str(node.nid))
コード例 #28
0
ファイル: app.py プロジェクト: openpolis/voisietequi-computer
    def POST(self):
        """
        Input data is a json string, passed as POST request payload.
        """
        logger.debug('Start computation')

        if not current_status.is_configured:
            logger.error("Computer is not configured")
            raise web.InternalError("Computer is not configured")
        logger.debug('Computer is configured')

        # read json input
        try:
            # emulate web.input with storify of json decoded POST data
            input = web.storify(
                json.loads( web.data() ),
                # required fields
                'election_code',
                'user_answers',
                'user_data',
            )
        except KeyError, ex: # can be raised from storify if miss some required fields
            logger.error("BadRequest: required field '%s' is missing" % ex)
            raise web.BadRequest
コード例 #29
0
ファイル: project.py プロジェクト: hraban/munca
        dbn="postgres",
        user="******",
        pw="seekrit",
        db="unisca_contact",
    )

_alphanum = set(string.ascii_letters + string.digits + "_")
def check_table_sort(i):
    """Check if values in given web.input are suitable for ordering tables."""
    if (set(i.sort) - _alphanum) or i.order not in ("asc", "desc"):
        raise ValueError, "Can not sort table with given parameters."

def del_contact(id):
    db.delete("contact_base", where="contact_id = $id", vars=locals())
    return "Contact #%s succesfully deleted." % id

def p_name(p):
    """Return given person's full name as a string."""
    return " ".join((n for n in (p.person_firstname, p.person_surnameprefix,
            p.person_lastname) if n))

def nl2br(txt):
    return web.htmlquote(txt).replace("\r\n", "<br>").replace("\n", "<br>")

# Template globals (sorry ^^)
web.template.Template.globals['nl2br'] = nl2br
web.template.Template.globals['p_name'] = p_name
web.template.Template.globals['py'] = web.storify(__builtins__)
web.template.Template.globals['render'] = render
web.template.Template.globals['year'] = g_year
コード例 #30
0
ファイル: config.py プロジェクト: robes/adapt-policy-service
implementation.
"""

import os
import json
import web

__all__ = ['config', 'load_config', 'default_config_filename']

default_config_filename = '~/policyservice.conf'

config = web.Storage()
config.debug = False
config.audit = False
config.ssl = web.storify(
    dict(ssl_enabled=False,
         ssl_certificate="/path/to/ssl_certificate",
         ssl_private_key="/path/to/ssl_private_key"))
config.policy = web.storify(
    dict(policy_class='adapt.greedy.Greedy',
         min_streams=0,
         initial_streams=8,
         update_incr_streams=8,
         max_streams=8,
         per_hosts_max_streams=36))


def load_config(filename=None):
    """Load configuration from file and merge with defaults.
    
       The 'filename' of the configuration file.
    """
コード例 #31
0
        port=1234,  # port has to be integer
        db=1,  # redis database ID, has to be integer
        initialFlush=False,  # when deploying set initialFlush to true
        format='Default'  # choose 'json' if you want to mess around. 
    ),
    initializer={},  # whatever the f**k you want to initialize
)

# these are the default settings. Think you might want to set this up
web.config.session_parameters = web.storify({
    'cookie_name': 'webpy_session_id',  # change this to your application name
    'cookie_domain': None,
    'cookie_path': None,
    'timeout': 86400,  #24 * 60 * 60, # 24 hours in seconds
    'ignore_expiry': True,
    'ignore_change_ip': True,
    'secret_key':
    'fLjUfxqXtfNoIldA0A0J',  # for all that is heavenly and good and sacred, CHANGE THIS
    'expired_message': 'Session expired',
    'httponly': True,
    'secure': False
})

# Declare your database shit. Also, make up your bloody mind, Chewxy.
# Stop switchiing from MySQL to CouchDB to Neo4j for no good reason.

# Render Engine (tenjin rhymes with engine):
render = web.template.render('templates/', globals={},
                             cache=False)  # Templator (slow as hell)
render = tenjin.Engine(path=['templates'])  # tenjin (fast!)
コード例 #32
0
ファイル: user.py プロジェクト: keizo/kulu
def anonymous_user(sid = ''):
    return web.storify({},uid = 0,hostname = web.ctx.env['REMOTE_ADDR'], 
        roles={glbl.constant.anonymous_role_id:'anonymous user'},sid=sid,
        session_in_db=False, remember_me=True)
コード例 #33
0
                            redisSession.RedisStore(ip='xxx.xxx.xxx.xxx',  # if you don't know IP addresses, shame on you
                                                    port=1234,  # port has to be integer
                                                    db=1,  # redis database ID, has to be integer
                                                    initialFlush=False,  # when deploying set initialFlush to true
                                                    format='Default'  # choose 'json' if you want to mess around. 
                                                    ),
                                                    initializer={},  # whatever the f**k you want to initialize
                            )

# these are the default settings. Think you might want to set this up
web.config.session_parameters = web.storify({
    'cookie_name': 'webpy_session_id',  # change this to your application name
    'cookie_domain': None,
    'cookie_path' : None,
    'timeout': 86400, #24 * 60 * 60, # 24 hours in seconds
    'ignore_expiry': True,
    'ignore_change_ip': True,
    'secret_key': 'fLjUfxqXtfNoIldA0A0J',  # for all that is heavenly and good and sacred, CHANGE THIS
    'expired_message': 'Session expired',
    'httponly': True,
    'secure': False
})

# Declare your database shit. Also, make up your bloody mind, Chewxy. 
# Stop switchiing from MySQL to CouchDB to Neo4j for no good reason.


# Render Engine (tenjin rhymes with engine):
render = web.template.render('templates/', globals={},  cache=False)  # Templator (slow as hell)
render = tenjin.Engine(path=['templates'])  # tenjin (fast!)

from views import *
コード例 #34
0
ファイル: config.py プロジェクト: robes/adapt-policy-service
implementation.
"""

import os
import json
import web

__all__ = ['config', 'load_config', 'default_config_filename']

default_config_filename = '~/policyservice.conf'

config = web.Storage()
config.debug = False
config.audit = False
config.ssl = web.storify(dict(
                    ssl_enabled=False,
                    ssl_certificate = "/path/to/ssl_certificate",
                    ssl_private_key = "/path/to/ssl_private_key"))
config.policy = web.storify(dict(
                    policy_class='adapt.greedy.Greedy',
                    min_streams=0, 
                    initial_streams=8, 
                    update_incr_streams=8, 
                    max_streams=8, 
                    per_hosts_max_streams=36))

def load_config(filename=None):
    """Load configuration from file and merge with defaults.
    
       The 'filename' of the configuration file.
    """
    # load config file