Ejemplo n.º 1
0
 def to_json(self):
     return json_object({
         "date": json_value(web.websafe(self.formatted_date())),
         "author": json_value(web.websafe(self.author)),
         "text": json_value(self.marked_down_text()),
         "line_number": json_value(web.websafe(self.line_number))
     })
Ejemplo n.º 2
0
    def POST(self):
        if session.login == False or session.usertype != 'student':
            return '''{"success":0}'''
        pageType = web.websafe(web.input().pageType)
        page = web.websafe(web.input().page)
        #ret = Stu().getIndexPage(pageType,page)
        
        if pageType == 0:
            try:
                conn =  SQL.sacdb_init().getcon()
                cursor=conn.cursor()
                sql = "SELECT * FROM activitylist WHERE state=%s ORDER BY posttime DSC LIMIT %s, %s"
                param=(0, page * 5 - 5, page * 5)
                cursor.execute(sql, param)
                data = cursor.fetchall()
                postdata = {"sucess": 1 , "list": []}
                for i in range(0, postdata["pageCnt"]):
                    postdata["list"].append({"AcId": data[i]["ID"], "imgSrc":data[i]["filepath"], "dateTime": data[i]["starttime"], "AcName": data[i]["name"], "AcOrg": data[i]["authorname"], "AcPlace": data[i]["location"], "AcNum": data[i]["maxnum"], "AcNumRest": data[i]["maxnum"] - data[i]["paticipatenum"], "AcHour": data[i]["ehour"]})

                return str(postdata);
            except MySQLdb.Error,e:
                errorinfo =  "indexpage  Mysql Error %d: %s" % (e.args[0], e.args[1])
                return errorinfo
            except Exception as e:
                return 'indexpage  '+str(e)
Ejemplo n.º 3
0
def get_net_sid_from_id(dataset, id):
    where="dataset=%s AND id=%s" % (websafe(dataset), websafe(id))
    res=list(db.select('network', what='sid', where=where))
    if len(res)==0:
        return None
    else:
        return str(res[0].sid)
Ejemplo n.º 4
0
def link_to(url, caption):
    """Generates a link to the given URL. `caption` is optional and may
    specify the caption of the URL. If `caption` is ``None``, the URL itself
    is used."""
    if caption is None:
        caption = url
    return '<a href="%s">%s</a>' % (websafe(url), websafe(caption))
Ejemplo n.º 5
0
 def POST(self):
     conn =  SQL.sacdb_init().getcon()
     cursor=conn.cursor()
     try:
         ID = web.websafe(web.input().userName)
         pw = web.websafe(web.input().pwd)
         cursor.execute("SELECT * FROM userlist WHERE ID = '%s' and password = '******'"%(ID,pw))
         if cursor.rowcount ==1:
             V = cursor.fetchone()
             session.login = True
             session.ID = ID
             session.ehour = V[5]
             session.usertype = V[3]
             if session.usertype == 'admin':
                 web.seeother('/admin.html')
             elif session.usertype == 'student':
                 web.seeother('/home.html')
             else:
                 return 'sys error'
         else:
             return failed%'not exist'
     except Exception as e:return failed%str(e)
     finally:
         cursor.close()
         conn.close()
Ejemplo n.º 6
0
	def GET(self):
		paras=web.input(opt_id='-1',val='-1')
		optId=web.websafe(paras.opt_id)
		value=web.websafe(paras.val)
		
		#read the db configuration from file
   	 	path = os.getcwd()+"/db_cnf"
   		#print path
    		f= open(path)
    		lines = f.readlines()
    		for line in lines:
			values = line.split()
			if values[0]=="likelihood":
				LIKELIHOOD_TREESHOLD=values[1]
			elif values[0]=="user":
				U=values[1]
			elif values[0]=="password":
				P=values[1]
			elif values[0]=="db_name":
				DATABASE_NAME=values[1]
			elif values[0]=="host":
				HOST=values[1]
	    		else:
				print "error, unreadable line in configuration file"
				break
	    	f.close()

		print "set parameter..."
		db= MySQLdb.connect(HOST,U,P,DATABASE_NAME)
		cur= db.cursor()
		sql = ('UPDATE Accompany.ActionPossibilityOptions SET SelectedValue=\'%s\' WHERE idActionPossibilityOptions=\'%s\''%(value,optId))		
		cur.execute(sql);
		return "ok"
Ejemplo n.º 7
0
def update_filesize(id, format, size):
    try:
        db.insert('filesize', dataset=int(id), format=websafe(format), 
                  size=int(size))
    except:
        db.update('filesize', where='dataset=%s AND format="%s"' %
                  (int(id), websafe(format)), size=size)
    return True
Ejemplo n.º 8
0
 def POST(self):
     if session.login == False or session.usertype != 'admin':
         return '''{"success":0}'''
     pageType = web.websafe(web.input().pageType)
     page = web.websafe(web.input().page)
     ret = admin().getIndexPage(pageType,page)
     
     except Exception as e:
         return "admin_indexpage  "+str(e)
Ejemplo n.º 9
0
    def GET(self):
	web.header('Content-Type', 'text/html')
    	get_vars = web.input()
	response = handler.multiple_update(web.websafe(get_vars.tasks), web.websafe(get_vars.action))
        if response['code'] == '404':
                web.notfound()
        if response['code'] == '410':
                web.gone()
        return response['html']
Ejemplo n.º 10
0
def htmlAnalysisRow(analysis, onMap=False, rowClass="", showFloor=True, ageDisplay=None, mapUrl="/mapa"):
    """ Outputs utf-8 encoded HTML with the home analysis.
    Done inside code because of speed up (3-times faster than templetor).
    """
    model = {
        "rowClass": web.websafe(rowClass),
        "url": web.websafe(analysis["url"]),
        "rooms": web.websafe(analysis["rooms"]),
        "price": web.websafe(formatPrice(analysis["price"])),
        "unitPrice": web.websafe(formatPrice(analysis["unitPrice"])),
        "area": analysis["area"],
        "targetAttr": "",
        "extra": "",
    }

    if showFloor:
        model["extra"] = """<td class="n">%s</td>""" % (analysis.get("floor") or "-")
    if ageDisplay is not None:
        if ageDisplay:
            model["extra"] += "<td>%s</td>" % web.websafe(formatAge(analysis["createdDate"]))
        else:
            model["extra"] += "<td></td>"

    if onMap:
        model["targetAttr"] = ' target="_blank"'
    else:
        model["extra"] += """<td class="address"><a href="%s?byt=%s">%s</a></td>""" % (
            web.websafe(mapUrl),
            web.websafe(urlEncode(analysis["url"])),
            web.websafe(analysis["locality"]))


    return """\
<tr class="%(rowClass)s"><td><a href="%(url)s"%(targetAttr)s>%(rooms)s</a></td><td class="n">%(price)s Kč</td><td class="n"><b>%(unitPrice)s Kč/m²</b></td><td class="n">%(area)s m²</td>%(extra)s</tr>
""" % model
Ejemplo n.º 11
0
def xmlify(obj):
    if isinstance(obj, bool):
        return ' rdf:datatype="http://www.w3.org/2001/XMLSchema#boolean">%s' % web.websafe(obj).lower()
    elif isinstance(obj, int):
        return ' rdf:datatype="http://www.w3.org/2001/XMLSchema#integer">%s' % web.websafe(obj)
    elif isinstance(obj, float):
        return ' rdf:datatype="http://www.w3.org/2001/XMLSchema#double">%s' % web.websafe(obj)
    elif isinstance(obj, URI):
        return ' rdf:resource="%s">' % web.websafe(obj.uri)
    else:
        return '>' + web.websafe(obj)
Ejemplo n.º 12
0
	def GET(self):
		user=web.input(uid='-1',ulang='-1')
		#user_language=web.input(ulang='-1')
		
		#read the db configuration from file
   	 	path = os.getcwd()+"/db_cnf"
   		#print path
    		f= open(path)
    		lines = f.readlines()
    		for line in lines:
			values = line.split()
			if values[0]=="likelihood":
				LIKELIHOOD_TREESHOLD=values[1]
			elif values[0]=="user":
				U=values[1]
			elif values[0]=="password":
				P=values[1]
			elif values[0]=="db_name":
				DATABASE_NAME=values[1]
			elif values[0]=="host":
				HOST=values[1]
	    		else:
				print "error, unreadable line in configuration file"
				break
	    	f.close()

		print "user actions request..."
		userId=web.websafe(user.uid)
		user_lang=web.websafe(user.ulang)
		db= MySQLdb.connect(HOST,U,P,DATABASE_NAME)
		cur= db.cursor()
	 	
		sql=('Select label_text,phrase,type_description,likelihood,apId,precondId from '
		     '(Select (Select message from Messages where messageId=a.ap_text and languageId=\'%s\') as label_text, '
		     'ActionPossibilityType.text as type_description,a.parentId,a.apId as apId,(Select message from Messages where messageId=a.ap_phrase and languageId=1) as phrase, '
		     'a.likelihood, a.precondId from ActionPossibilities a, ActionPossibilityType, Locations where '
		     'a.apTypeId = ActionPossibilityType.apTypeId and parentId is null and Locations.locationId = a.locationId and Locations.locationId=(Select locationId from Users where userId=\'%s\') and a.likelihood >%s ) as pinco order by likelihood desc;'%(user_lang,userId,LIKELIHOOD_TREESHOLD))
		cur.execute(sql)
		a="["
		for record in cur:
			a+="{"
			a+="\"ap_label\":\"%s\","%record[0]
			a+="\"phraseal_feedback\":\"%s\","%record[1]
			a+="\"type_description\":\"%s\","%record[2]
			a+="\"likelihood\":\"%s\","%record[3]
			a+="\"apId\":\"%s\","%record[4]
			a+="\"precond_id\":\"%s\""%record[5]
			a+="}"
		a+="]"	
		a=a.replace('}{','},{')
		return a
Ejemplo n.º 13
0
 def __call__(self, handler):
     i = web.input(_method="GET", _profile="")
     if i._profile.lower() == "true":
         out, result = web.profile(handler)()
         if isinstance(out, web.template.TemplateResult):
             out.__body__ = out.get('__body__', '') + '<pre class="profile">' + web.websafe(result) + '</pre>'
             return out
         elif isinstance(out, basestring):
             return out + '<br/>' + '<pre class="profile">' + web.websafe(result) + '</pre>'
         else:
             # don't know how to handle this.
             return out
     else:
         return handler()
Ejemplo n.º 14
0
 def GET(self,url):
     '''view singel page'''
     page = model.get_page_url(url)
     if not page:
         raise web.seeother('/new?url=%s' % web.websafe(url))
     
     return render.view(page)
Ejemplo n.º 15
0
 def f(*args, **keywords):
     username = None
     password = None
     try:
         b64text = webpy.ctx.env['HTTP_AUTHORIZATION'][6:]
         plaintext = base64.b64decode(b64text)
         colonpos = plaintext.index(':')
         username = plaintext[:colonpos]
         password = plaintext[colonpos + 1:]
     except:
         # TODO: handle absent HTTP_AUTHORIZATION field
         # separately from failed base64 decoding or missing
         # colon in plaintext.
         pass
     if verifier(username, password, realm):
         last_access[username] = datetime.datetime.now()
         # Attach the user's name to the server. The way to
         # find the server depends on whether the function is a
         # bound method.
         if hasattr(func, 'im_self'):
             func.im_self.user = username
         else:
             args[0].user = username
         return func(*args, **keywords)
     else:
         webpy.ctx.status = '401 UNAUTHORIZED'
         webpy.header('WWW-Authenticate',
                      'Basic realm="%s"'  % webpy.websafe(realm))
         return deny(realm, username, password, redirect_url)
Ejemplo n.º 16
0
def do_search_query(tokens, offset=0, limit=10):

    tokens=[ websafe(t) for t in tokens ]

    if len(tokens)==0:
        return range(1, get_totals().count+1)

    install_regexp()

    searchfields=['name', 'shortdescription', 'description']

    recs=[]
    i=0
    while i < len(tokens):
        if tokens[i] == '-' and i+1 < len(tokens) and tokens[i+1][-1] != ':':
            recs.append( (None, tokens[i+1], True) )
            i += 2
        elif tokens[i] == '-' and i+2 < len(tokens) and \
                tokens[i+1][-1] == ':':
            recs.append( (tokens[i+1][:-1], tokens[i+2], True) )
            i += 3
        elif tokens[i] == '-':
            i += 1
        elif tokens[i][-1] == ':' and i+1 < len(tokens):
            if tokens[i][:-1] in searchfields:
                recs.append( (tokens[i][:-1], tokens[i+1]) )
                i += 2
            else:
                recs.append( (None, tokens[i+1]) )
                i += 2
        else:
            recs.append( (None, tokens[i]) )
            i += 1

    clause="%s %s REGEXP '\\b%s\\b'"

    def allfields(rec):
        if len(rec)>=3 and rec[2]:
            n='NOT'
            op=' AND '
        else:
            n=''
            op=' OR '
        return '(' + op.join([ clause % (f,n,rec[1]) 
                               for f in searchfields]) + ')'

    def term(rec):
        if rec[0] is None:
            return allfields(rec)
        else:
            if len(rec)>=3 and rec[2]:
                n='NOT'
            else:
                n=''
            return clause % (rec[0], n, rec[1])

    where=' AND '.join([ term(r) for r in recs ])
    
    res=db.select('dataset', what='id', where=where)
    return [r.id for r in res]
Ejemplo n.º 17
0
	def GET(self):
		paras = web.input(default_speed='0.0')
		value = web.websafe(paras.default_speed)

		#read the db configuration from file
   	 	path = os.getcwd()+"/db_cnf"
   		#print path
    		f= open(path)
    		lines = f.readlines()
    		for line in lines:
			values = line.split()
			if values[0]=="likelihood":
				LIKELIHOOD_TREESHOLD=values[1]
			elif values[0]=="user":
				U=values[1]
			elif values[0]=="password":
				P=values[1]
			elif values[0]=="db_name":
				DATABASE_NAME=values[1]
			elif values[0]=="host":
				HOST=values[1]
	    		else:
				print "error, unreadable line in configuration file"
				break
	    	f.close()

		print "reset emphasis..."
		db= MySQLdb.connect(HOST,U,P,DATABASE_NAME)
		cur= db.cursor()
		sql = ('UPDATE Accompany.Sensors SET value=\'%s\',lastUpdate=NOW() WHERE sensorId=\'1000\';'%value)		
		cur.execute(sql);
		return "ok"
Ejemplo n.º 18
0
	def GET(self):
		
		#read the db configuration from file
   	 	path = os.getcwd()+"/db_cnf"
   		#print path
    		f= open(path)
    		lines = f.readlines()
    		for line in lines:
			values = line.split()
			if values[0]=="likelihood":
				LIKELIHOOD_TREESHOLD=values[1]
			elif values[0]=="user":
				U=values[1]
			elif values[0]=="password":
				P=values[1]
			elif values[0]=="db_name":
				DATABASE_NAME=values[1]
			elif values[0]=="host":
				HOST=values[1]
	    		else:
				print "error, unreadable line in configuration file"
				break
	    	f.close()

		paras=web.input(cmd_id='-1')
		cmd=web.websafe(paras.cmd_id)
		print "command received... (%s)"%(cmd)
		db= MySQLdb.connect(HOST,U,P,DATABASE_NAME)
		cur= db.cursor()
		sql = ('UPDATE Sensors SET value=\'1\' WHERE sensorId=\'%s\''%cmd)		
		cur.execute(sql);
		return "ok"
Ejemplo n.º 19
0
 def GET(self, waypoint, format):
     params = web.input(q = '')
     params = web.input(reference = '');
     waypoint = web.websafe(waypoint)
     
     responseDict = {'waypoints':[]}
     web.header('Content-Type', 'application/json')
     if waypoint is not None:
         waypoint = waypoint.replace("-", " ")
             
         place = getOneWaypoint(waypoint, params.reference)
         if place:
             details = place.details
             node = {}
             
             node['waypoint'] = getAttribute(details, 'name')
             node['number'] = getAttribute(details, 'formatted_phone_number')
             node['location'] = place.vicinity
             node['hours'] = getAttribute(details, 'opening_hours.periods')
             node['rating'] = formatRating(getAttribute(details, 'rating'))
             node['lat_lng'] = getAttribute(details, 'geometry.location')
             node['googleid'] = place.id
             node['googleReference'] = place.reference
             responseDict['waypoints'].append(node) 
     return json.dumps(responseDict) 
Ejemplo n.º 20
0
 def POST(self):
     data = web.input()
     try:
         web.sendmail(websafe(data.email), m.User.by_id(1).email, "Blog About Page Contact from: %s" % websafe(data.name), websafe(data.message))
         flash("error","Thanks for Contacting me!")
     except Exception,e:
         flash("error","Sorry, there was a problem, message not sent")
Ejemplo n.º 21
0
    def POST(self):
        s = getSession()

        i = web.input()

        if i.command == "Evaluate":
            inp = ""
            exp = i.expression.rstrip()
            s.history.append(exp)
            s.history_cursor=len(s.history)

            exp = exp.replace('\n', ' ').replace('\r', '')
            
            if assign_pattern.match(exp):
                try:
                    exec(exp, globals(), s.database.transactions[s.database.transactionId])
                    r=""
                except Exception, e:
                    r=e
                    inp=i.expression
            else:
                try:
                    r=eval(exp, globals(), s.database.transactions[s.database.transactionId])
                    if isinstance(r, Relation):
                        r="""<div id="itsthetable">%s</div>""" % r.renderHTML()
                    else:
                        r=str(web.websafe(r))
                except Exception, e:
                    r=e
                    inp=i.expression
Ejemplo n.º 22
0
def get_id_from_sid(sid):
    res=list(db.select('dataset', what='id', 
                       where="sid='%s'" % websafe(sid)))
    if len(res)==0:
        return None
    else:
        return str(res[0].id)
Ejemplo n.º 23
0
    def _pre(self, *param, **params):
        """<comment-ja>
        HTTP Method別処理を実行する前の処理を行います。
          1. メディアタイプの設定
          2. Content-Typeの設定
        </comment-ja>
        <comment-en>
        TODO: English Comment
        </comment-en>
        """
        multi = {}
        for x in web.input(_unicode=False).keys():
            if x.startswith("multi") is True:
                multi[x] = {}
        self.input = web.input(**multi)

        try:
            if param:
                resource = web.websafe(param[len(param) - 1])
                self.__template__.media = resource[resource.rindex(".") + 1 :]

        except (IndexError, ValueError), ve:
            self.__template__.media = DEFAULT_MEDIA
            self.logger.debug(
                "%s - The media-type has not been specified, or that violate the format, so use a standard format. :Media=%s"
                % (" ".join(ve.args), self.__template__.media)
            )
Ejemplo n.º 24
0
    def GET(self):
        receivedData = web.input(url='')
        url = web.websafe(receivedData.url)
        if url!='':
            GPlusStat = GetGPlusStat(url)
            PinterestStat = GetPinterestStat(url)
            FaceResult = GetFaceResult(url)
            TwitterStat = GetTwitterStat(url)
            LinkedInStat = GetLinkedInStat(url)

            TotalStat = 0
            if GPlusStat != 'Error':
                TotalStat += GPlusStat
            if PinterestStat != 'Error':
                TotalStat += PinterestStat
            if FaceResult != 'Error':
                TotalStat += FaceResult
            if TwitterStat != 'Error':
                TotalStat += TwitterStat
            if LinkedInStat != 'Error':
                TotalStat += LinkedInStat

            result = {'GPlus': GPlusStat, 'Pinterest': PinterestStat, 'Facebook': FaceResult, 'Twitter': TwitterStat,
                      'LinkedIn': LinkedInStat, 'Total': TotalStat}

            return json.dumps(result)
        else:
            f = open('statService.wsdl', 'r')
            return f.read()
Ejemplo n.º 25
0
 def POST(self):
     if session.login == False or session.usertype != 'student':
         return '''{"success":0}'''
     
     page = web.websafe(web.input().page)
     
     try:
         conn =  SQL.sacdb_init().getcon()
         cursor=conn.cursor()
         sql = "SELECT * FROM participate WHERE StudentID=%s ORDER BY participatetime DSC LIMIT page*5-5, page*5"
         
         cursor.execute(sql, param)
         data = cursor.fetchall()
         
         postdata = {"sucess": 1, "list": []}
         for i in range(0, 5):
             sql = "SELECT * FROM activitylist WHERE ID=%s"
             param=(data[i]["StudentID"])
             cursor.execute(sql, param)
             actdata = cursor.fetchone()
             postdata["list"].append({"AcId": data[i]["StudentID"], "AcComState": actdata["status"], "AcAuthenState": data[i]["AuthenticationStatus"], "imgSrc":actdata["filepath"], "dateTime": actdata["starttime"], "AcName": actdata["name"], "AcOrg": actdata["authorname"], "AcPlace": actdata["location"], "AcNum": actdata["maxnum"], "AcNumRest": actdata["maxnum"] - actdata["paticipatenum"], "AcHour": actdata["ehour"]})
     return str(postdata);
     
     except MySQLdb.Error,e:
         errorinfo =  "stu_homepage  Mysql Error %d: %s" % (e.args[0], e.args[1])
         return errorinfo
Ejemplo n.º 26
0
 def GET(self):
     html = '<html><head><title>wall</title></head><body>'
     html += '<br/>'.join(web.websafe(x) for x in wallList)
     html += """<br/><form action="/write" method="post">
                <input name="written"/><input type="submit" />
                <p><a href="/logout">Logout</a></p>
                </body></html>"""
     return html
Ejemplo n.º 27
0
 def show_input(self, name, description):
     retval = """<td>File</td><td><select name="%s">""" % name
     files = file_scanner(config.file_in_path)
     files = files[self.type].values()
     for file in files:
         retval += '<option value="%s">%s</option>' % (websafe(file.path), file.description)
     retval += """</select></td><td>%s</td>""" % description
     return retval
Ejemplo n.º 28
0
 def GET(self, url):
     shortened = web.ctx.homedomain + '/' + url
     query = db.GqlQuery("SELECT * FROM URL WHERE shortened = :1", shortened)
     entry = query.get()
     if not entry:
         return render.notfound(web.websafe(url))
     else:
         web.seeother(entry.actual)
Ejemplo n.º 29
0
 def GET(self):
     root = os.path.join(os.path.dirname(openlibrary.__file__), os.path.pardir)
     root = os.path.normpath(root)
     
     p = subprocess.Popen('cd %s && git pull' % root, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
     out = p.stdout.read()
     p.wait()
     return '<pre>' + web.websafe(out) + '</pre>'
Ejemplo n.º 30
0
def link_to_tag(base, tag, caption=None):
    """Generates a link to the page of the given tag. `caption` is optional
    and may specify the caption of the URL. If `caption` is ``None``, the
    tag itself is used."""
    if caption is None:
        caption = tag.tag
    caption = websafe(caption)
    return link_to(url_for_tag(base, tag), caption)
Ejemplo n.º 31
0
class Integer(Column):
    sql_type = 'int'
    toxml = lambda self, obj: ' rdf:datatype="http://www.w3.org/2001/XMLSchema#integer">%s' % web.websafe(
        obj)
Ejemplo n.º 32
0
class Float(Column):
    sql_type = 'real'
    toxml = lambda self, obj: ' rdf:datatype="http://www.w3.org/2001/XMLSchema#double">%s' % web.websafe(
        obj)
Ejemplo n.º 33
0
class URL(String):
    toxml = lambda self, obj: ' rdf:resource="%s">' % web.websafe(obj)
    ton3 = lambda self, obj, indent: '<%s>' % obj
Ejemplo n.º 34
0
 def GET(self, url):
     page = model.get_page_by_url(url)
     if not page:
         raise web.seeother('/new?url=%s' % web.websafe(url))
     return render.view(page)
Ejemplo n.º 35
0
 def GET(self, account=''):
     account = web.input( saccount = 'web')
     result, hd = ds.accounttrax(ds.ledgerfile ,web.websafe(account.saccount))
     return render.trax(account = result)
Ejemplo n.º 36
0
 def __str__(self):
     attrs = " ".join('%s="%s"' % (web.websafe(k), web.websafe(v)) for k, v in self.attrs.items())
     return "<%s %s />" % (self.tag, attrs)
Ejemplo n.º 37
0
 def GET (self, name):
     return web.websafe('Sorry, I dont understand your request')
Ejemplo n.º 38
0
    def GET(self):
        # Corrupt Cache
        #  * Importing bsddb fails on many 2.7 instances,
        #    python tries to import corrupt cached using bsddb, this fails
        #  * DBPageNotFoundError, since python tried to import corrupt cache
        #    as a bsddb file, and it is not, it will error out

        i = web.input()
        feed = web.websafe(i.feed)

        if feed == 'news':
            try:
                newsCache = shelve.open(newsFile)
            except ImportError:
                os.remove(newsFile)
                newsCache = shelve.open(newsFile)

            try:
                newsFeed = feedcache.Cache(newsCache,
                                           timeToLiveSeconds).fetch(newsRss)
            except:
                newsCache.close()
                newsCache = shelve.open(newsFile)
                os.remove(newsFile)
                newsFeed = feedcache.Cache(newsCache,
                                           timeToLiveSeconds).fetch(newsRss)
            newsCache.close()

            news = [(x.title, x.link) for x in newsFeed.entries][:maxNEWS]
            return render.news(news)
        elif feed == 'i686':
            try:
                x86Cache = shelve.open(x86File)
            except:
                os.remove(x86File)
                x86Cache = shelve.open(x86File)

            try:
                x86Feed = feedcache.Cache(x86Cache,
                                          timeToLiveSeconds).fetch(x86Rss)
            except:
                x86Cache.close()
                os.remove(x86File)
                x86Cache = shelve.open(x86File)
                x86Feed = feedcache.Cache(x86Cache,
                                          timeToLiveSeconds).fetch(x86Rss)
            x86Cache.close()

            x86Pkgs = [(x.title, x.category, x.link, x.summary)
                       for x in x86Feed.entries][:maxPKGS]
            x86 = Arch()
            x86.add_packages(x86Pkgs)

            return render.packages(x86)
        elif feed == 'x86_64':
            try:
                x64Cache = shelve.open(x64File)
            except ImportError:
                os.remove(x64File)
                x64Cache = shelve.open(x64File)

            try:
                x64Feed = feedcache.Cache(x64Cache,
                                          timeToLiveSeconds).fetch(x64Rss)
            except:
                x64Cache.close()
                os.remove(x64File)
                x64Cache = shelve.open(x64File)
                x64Feed = feedcache.Cache(x64Cache,
                                          timeToLiveSeconds).fetch(x64Rss)
            x64Cache.close()

            x64Pkgs = [(x.title, x.category, x.link, x.summary)
                       for x in x64Feed.entries][:maxPKGS]
            x64 = Arch()
            x64.add_packages(x64Pkgs)
        return render.packages(x64)
Ejemplo n.º 39
0
 def __str__(self):
     return " ".join('%s="%s"' % (k, web.websafe(v)) for k, v in self.items())
Ejemplo n.º 40
0
 def toxml(self, obj):
     if hasattr(obj, '_uri_'):
         return ' rdf:resource="%s">' % web.websafe(obj._uri_)
     else:
         return None
Ejemplo n.º 41
0
 def GET(self, url):
     """ View single page """
     page = model.get_page_by_url(url)
     if not page:
         raise web.seeother("/new?url=%s" % web.websafe(url))
     return render.view(page)
Ejemplo n.º 42
0
def spacesafe(text):
    text = web.websafe(text)
    #@@ TODO: should take care of space at the begining of line also
    text = text.replace('  ', ' &nbsp;')
    return text
Ejemplo n.º 43
0
class Boolean(Column):
    sql_type = 'bool'
    display = lambda self, x: {True: 'Yes', False: 'No', None: 'Unknown'}
    toxml = lambda self, obj: ' rdf:datatype="http://www.w3.org/2001/XMLSchema#boolean">%s' % web.websafe(
        obj).lower()
Ejemplo n.º 44
0
 def GET(self, name):
     web.header("content-type", "text/html")
     code = web.websafe(read_file(name))
     html = open("index.html").read()
     return html.replace("<!--CODE-->", code)
Ejemplo n.º 45
0
 def html_encode(self, cnt):
     return web.websafe(cnt)
Ejemplo n.º 46
0
def radio_input(checked=False, **params):
    params['type'] = 'radio'
    if checked:
        params['checked'] = "checked"
    return "<input %s />" % " ".join(['%s="%s"' % (k, web.websafe(v)) for k, v in params.items()])