web2py-template / timetest.py

Diff from to

timetest.py

+# coding: utf-8
 import timeit
 
-code_to_parse = '''{{if something:
-some_code
-other_code
-elif other_condition:
-elif_code
-other_elif_code
-else:
-code_on_else
-other_code_on_else
-pass
-code_outside
-for a in b:
-code_on_for
-other_code
-pass
-some_code_outside
-for c in d:
-code_on_second_for
-other_code_on_second_for
-else:
-code_on_else
-other_code_on_else
-pass
-other_code_outside
-try:
-something
-code_to_try
-except:
-code_on_the_exception
-blablabla
-pass
-code_outside
-try:
-other_try_code
-more_one_line
-except SomeException, e:
-lets_solve_this_exception
-more_code
-except:
-code_to_general_exception
-goes_here
-pass
-more_code_outside_all_blocks}}'''
+
+code_to_parse = '''
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+  <head>
+    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
+    <meta http-equiv="content-language" content="en" />
+    <title>web2py: Enterprise Web Framework</title>
+    {{response.files.append(URL(r=request,c='static',f='styles.css'))}}
+  </head>
+  <body>
+
+    <!--[if lt IE 8]>
+    <div style='border: 1px solid #F7941D; background: #FEEFDA; text-align: center; clear: both; height: 75px; position: relative;'>
+      <div style='position: absolute; right: 3px; top: 3px; font-family: courier new; font-weight: bold;'><a href='#' onclick='javascript:this.parentNode.parentNode.style.display="none"; return false;'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-cornerx.jpg' style='border: none;' alt='Close this notice'/></a></div>
+      <div style='width: 640px; margin: 0 auto; text-align: left; padding: 0; overflow: hidden; color: black;'>
+        <div style='width: 75px; float: left;'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-warning.jpg' alt='Warning!'/></div>
+        <div style='width: 275px; float: left; font-family: Arial, sans-serif;'>
+          <div style='font-size: 14px; font-weight: bold; margin-top: 12px;'>You are using an outdated browser</div>
+          <div style='font-size: 12px; margin-top: 6px; line-height: 12px;'>For a better experience using this site, please upgrade to a modern web browser.</div>
+        </div>
+        <div style='width: 75px; float: left;'><a href='http://www.firefox.com' target='_blank'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-firefox.jpg' style='border: none;' alt='Get Firefox 3.5'/></a></div>
+        <div style='width: 75px; float: left;'><a href='http://www.browserforthebetter.com/download.html' target='_blank'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-ie8.jpg' style='border: none;' alt='Get Internet Explorer 8'/></a></div>
+        <div style='width: 73px; float: left;'><a href='http://www.apple.com/safari/download/' target='_blank'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-safari.jpg' style='border: none;' alt='Get Safari 4'/></a></div>
+        <div style='float: left;'><a href='http://www.google.com/chrome' target='_blank'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-chrome.jpg' style='border: none;' alt='Get Google Chrome'/></a></div>
+      </div>
+    </div>
+    <![endif]-->
+    <div class="header">
+      <div class="menu layout">
+        <ul>
+          <li><a href="{{=URL(r=request,c='default',f='index')}}"><span>Overview of features</span>Home</a></li>
+          <li><a href="{{=URL(r=request,c='default',f='what')}}"><span>Read this first</span>About</a></li>
+          <li><a href="{{=URL(r=request,c='default',f='download')}}"><span>web2py is 100% free</span>Download</a></li>
+          <li><a href="http://web2py.com/book"><span>The full book online</span>Documentation</a></li>
+          <li><a href="{{=URL(r=request,c='default',f='who')}}"><span>Authors and contributors</span>Staff</a></li>
+          <li><a href="{{=URL(r=request,c='default',f='support')}}"><span>Affiliated companies</span>Support</a></li>
+        </ul>
+      </div>
+    </div>
+    <div class="layout">
+      <div class="content">
+        {{if response.flash:}}<div class="flash">{{=response.flash}}</div>{{pass}}
+        {{import os}}
+
+<h1>web2py<sup style="font-size:0.5em;">TM</sup> Database Abstraction Layer (DAL)</h1>
+
+<h2>Examples</h2>
+<h3>define_table, insert, count, delete, update</h3>
+{{=CODE("""
+db = DAL('postgres://user:password@hostname/db', pool_size=10)
+db.define_table('person',Field('name','string'))
+id= db.person.insert(name='max')
+query=(db.person.id==id)
+db(query).count()
+db(query).delete()
+db(query).update(name='Max')
+rows = db(query).select(orderby=db.person.name)
+for row in rows: print row.name
+""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'))}}
+
+<h3>Examples of uri strings for DAL</h3>
+<ul>
+<li>sqlite://test.db</li>
+<li>mysql://user:password@localhost/database</li>
+<li>postgres://user:password@localhost/database</li>
+<li>mssql://user:password@host/database</li>
+<li>firebird://user:password@server:3050/database</li>
+<li>oracle://user/password@database</li>
+</ul>
+
+<h3>Valid field Types</h3>
+<ul>
+<li>Field(name, 'string')</li>
+<li>Field(name, 'text')</li>
+<li>Field(name, 'password')</li>
+<li>Field(name, 'blob')</li>
+<li>Field(name, 'upload')</li>
+<li>Field(name, 'boolean')</li>
+<li>Field(name, 'integer')</li>
+<li>Field(name, 'double')</li>
+<li>Field(name, 'time')</li>
+<li>Field(name, 'date')</li>
+<li>Field(name, 'datetime')</li>
+<li>Field(name, db.referenced_table) # reference field</li>
+</ul>
+
+<h3>Valid Field Attribute</h3>
+<ul>
+<li>length (only for string type, defaults to 32)</li>
+<li>default (defaults to None)</li>
+<li>required (defaults to False)</li>
+<li>notnull (defaults to False)</li>
+<li>unique (defaults to False)</li>
+<li>requires (<a href="{{=URL(r=request,f='api')}}">validator or list of validators</a>,
+for forms)</li>
+<li>comment (for forms)</li>
+<li>widget (for forms)</li>
+<li>represent (for forms)</li>
+<li>readable (for forms)</li>
+<li>writable (for forms)</li>
+<li>update (default value if the record is updated)</li>
+<li>uploadfield (for upload fields)</li>
+<li>authorize (for upload fields, function to be used if data can be downloaded, see authentication)</li>
+<li>autodelete (for upload fields, if set to true linked uploaded images are removed upon deletion of the record)</li><li>label (for forms)</li>
+</ul>
+
+<h3>On Migrations</h3>
+Changing the list of fields or field types in a model, triggers an automatic migration, i.e. web2py generates SQL to alter the table accordingly. If the table does not exist it is created. Migration actions are logged in the file sql.log accessible via the admin/design interface.
+Migration can be turned off on a per-table basis by passing migrate=False to define_table.
+
+<h3>Select Attributes</h3>
+
+{{=CODE("rows = db(query).select(*fields, orderby=..., left=..., groupby=..., having=..., limitby=..., cache=...)")}}
+
+<h3>Shortcuts</h3>
+{{=CODE("""
+db['person']                   ### db.person
+db.person['name']              ### db.person.name
+db['person']['name']           ### db.person.name
+db.person[0]=dict(name='Max')  ### insert
+db.person[id]=dict(name='Max') ### update by db.person.id
+print db.person[id]            ### select by db.person.id
+del db.person[id]              ### delete by db.person.id
+""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'))}}
+
+<h3>Truncate and Drop a table</h3>
+{{=CODE("""
+db.person.truncate()
+db.person.drop()""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'))}}
+
+<h3>Reference Fields Inner joins</h3>
+{{=CODE("""
+db.define_table('dog',Field('name'))
+db.define_table('friendship', Field('person',db.person), Field('dog',db.dog))
+db.friendship.insert(person=id, dog=db.dog.insert(name='Snoopy'))
+friends=(db.person.id==db.friendship.person)&(db.dog.id==db.friendship.dog)
+rows = db(friends).select(db.person.name, db.dog.name)
+for row in rows: print row.person.name, 'is friend of', row.dog.name""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'))}}
+
+<h3>Left Outer Joins</h3>
+{{=CODE("""
+query=(db.person.id>0)
+friends=(db.person.id==db.friendship.person)&(db.dog.id==db.friendship.dog)
+rows = db(query).select(db.person.name, db.dog.name, left=db.dog.on(friends))
+for row in rows: print row.person.name, 'is friend of', row.dog.name or 'nobody'""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'))}}
+
+<h3>Complex queries</h3>
+{{=CODE("""
+query = (db.person.id==1)|((db.person.id==2)&(db.person.name=='Max'))
+query = (db.person.id==db.friendship.person)&(db.dog.id==db.friendship.dog)
+query = db.person.name.lower().like('m%')
+query = db.person.id.belongs(('max','Max','MAX'))
+query = db.person.birth.year()+1==2008
+rows = db(query).select()""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'))}}
+
+<h3>Nested selects</h3>
+{{=CODE("""
+query = db.person.id.belongs(db()._select(db.friendship.person)""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'))}}
+
+<h3>Aggregates</h3>
+{{=CODE("""
+rows=db(friends).select(db.person.name,db.dog.id.count(),groupby=db.dog.id)""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'))}}
+
+Aggregate functions db.table.field.count(), .max(), .min(), sum().
+
+<h3>Aliases</h3>
+
+{{=CODE("""
+person=db.person
+friendship=db.friendship
+puppy=db.dog.with_alias('puppy')
+query=(puppy.id==friendhip.dog)&(friendship.person==person.id)
+rows=db().select(person.name,puppy.name,left=puppy.on(query))
+""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'))}}
+
+
+<h3>Caching</h3>
+{{=CODE("""
+rows=db().select(db.person.ALL,cache=(cache.ram,3600))
+""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'))}}
+
+cache=(model,cache_timeout) where model can be cache.ram, cache.disk, cache.memcache or user defined caching model, cache_timeout is in seconds.
+
+<h3>CSV Input</h3>
+
+{{=CODE("db.person.import_from_csv_file(open(filename,'rb'))")}}
+
+<h3>CSV Output</h3>
+
+{{=CODE("str(rows)")}}
+
+<h3>HTML output</h3>
+
+{{=CODE("print rows.xml()")}}
+
+<h3>Set field validators</h3>
+{{=CODE("""
+db.person.name.requires=IS_NOT_IN_DB(db,db.person.name)
+db.friendship.person.requires=IS_IN_DB(db,db.person.id,'%(name)s')""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'))}}
+
+<h3>Generate and process a form from a model</h3>
+{{=CODE("""
+form = SQLFORM(db.friendship)
+if form.accepts(request.vars, session): response.flash='record inserted'
+elif form.errors: response.flash='form errors'""".strip(),language='web2py',link=URL(r=request,c='global',f='vars'))}}
+The form can then be displayed in a view with: 
+{{=CODE("{"+"{=form}"+"}",language='html')}}
+
+      </div>
+    </div>
+    <div class="footer">Copyright &copy; 2007 - 2009 - powered by <a href="http://web2py.com">web2py</a></div>
+  </body>
+</html>
+
+
+'''
+
+def percent_difference(x1, x2):
+    diff = ((x1 - x2) / 2) * 100
+    
+    if diff < 0:
+        diff = "Is %0.2f%% faster" % abs(diff)
+    elif diff > 0:
+        diff = "Is %0.2f%% slower" % abs(diff)        
+    
+    return diff
 
 if __name__ == '__main__':
-    t1 = timeit.Timer('parse_template(code_to_parse)',
+    import sys
+    iterations = 1000
+    
+    print "Performing", iterations, "iterations"
+
+    t1 = timeit.Timer('parse(code_to_parse)',
+                     '''from template import parse
+from timetest import code_to_parse''').timeit(number=iterations)
+    sys.stdout.write(".")
+    sys.stdout.flush()
+    
+    t2 = timeit.Timer('get_parsed(code_to_parse)',
+                     '''from template_new import get_parsed
+from timetest import code_to_parse''').timeit(number=iterations)
+    sys.stdout.write(".")
+    sys.stdout.flush()
+    
+    t3 = timeit.Timer('parse_template(code_to_parse)',
                      '''from new_template import parse_template
-from timetest import code_to_parse''').timeit(number=1000)
-    print t1
+from timetest import code_to_parse''').timeit(number=iterations)
+    sys.stdout.write(".\n")
+    sys.stdout.flush()
 
-    t2 = timeit.Timer('parse(code_to_parse)',
-                     '''from template import parse
-from timetest import code_to_parse''').timeit(number=1000)
-    print t2
-
-    print t1 / t2
+    print "Gluon\t", t1
+    print percent_difference(t1, t2), "Thadeus"
+    print percent_difference(t1, t3), "Alvaro"
+    print ''
+    print "Thadeus\t", t2
+    print percent_difference(t2, t1), "Gluon"
+    print percent_difference(t2, t3), "Alvaro"
+    print ''    
+    print "Alvaro\t", t3
+    print percent_difference(t3, t1), "Gluon"
+    print percent_difference(t3, t2), "Thadeus"
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.