code
stringlengths
1
1.72M
language
stringclasses
1 value
import glob import os import zipfile import sys import re from BeautifulSoup import BeautifulSoup as BS def head(styles): title = '<title>{{=response.title or request.application}}</title>' items = '\n'.join(["{{response.files.append(URL(request.application,'static','%s'))}}" % (style) for style in styles]) loc="""<style> div.flash { position: absolute; float: right; padding: 10px; top: 0px; right: 0px; opacity: 0.75; margin: 10px 10px 10px 10px; text-align: center; clear: both; color: #fff; font-size: 11pt; text-align: center; vertical-align: middle; cursor: pointer; background: black; border: 2px solid #fff; -moz-border-radius: 5px; -webkit-border-radius: 5px; z-index: 2; } div.error { -moz-border-radius: 5px; -webkit-border-radius: 5px; background-color: red; color: white; padding: 3px; border: 1px solid #666; } </style>""" return "\n%s\n%s\n{{include 'web2py_ajax.html'}}\n%s" % (title,items,loc) def content(): return """<div class="flash">{{=response.flash or ''}}</div>{{include}}""" def process(folder): indexfile = open(os.path.join(folder,'index.html'),'rb') try: soup = BS(indexfile.read()) finally: indexfile.close() styles = [x['href'] for x in soup.findAll('link')] soup.find('head').contents=BS(head(styles)) try: soup.find('h1').contents=BS('{{=response.title or request.application}}') soup.find('h2').contents=BS("{{=response.subtitle or '=response.subtitle'}}") except: pass for match in (soup.find('div',id='menu'), soup.find('div',{'class':'menu'}), soup.find('div',id='nav'), soup.find('div',{'class':'nav'})): if match: match.contents=BS('{{=MENU(response.menu)}}') break done=False for match in (soup.find('div',id='content'), soup.find('div',{'class':'content'}), soup.find('div',id='main'), soup.find('div',{'class':'main'})): if match: match.contents=BS(content()) done=True break if done: page = soup.prettify() page = re.compile("\s*\{\{=response\.flash or ''\}\}\s*",re.MULTILINE)\ .sub("{{=response.flash or ''}}",page) print page else: raise Exception, "Unable to convert" if __name__=='__main__': if len(sys.argv)<2: print """USAGE: 1) start a new web2py application 2) Download a sample free layout from the web into the static/ folder of your web2py application (make sure a sample index.html is there) 3) run this script with python layout_make.py /path/to/web2py/applications/app/static/ > /path/to/web2py/applications/app/views/layout.html """ elif not os.path.exists(sys.argv[1]): print 'Folder %s does not exist' % sys.argv[1] else: process(sys.argv[1])
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ sessions2trash.py Run this script in a web2py environment shell e.g. python web2py.py -S app If models are loaded (-M option) auth.settings.expiration is assumed for sessions without an expiration. If models are not loaded, sessions older than 60 minutes are removed. Use the --expiration option to override these values. Typical usage: # Delete expired sessions every 5 minutes nohup python web2py.py -S app -M -R scripts/sessions2trash.py & # Delete sessions older than 60 minutes regardless of expiration, # with verbose output, then exit. python web2py.py -S app -M -R scripts/sessions2trash.py -A -o -x 3600 -f -v # Delete all sessions regardless of expiry and exit. python web2py.py -S app -M -R scripts/sessions2trash.py -A -o -x 0 """ from gluon.storage import Storage from optparse import OptionParser import cPickle import datetime import os import stat import time EXPIRATION_MINUTES = 60 SLEEP_MINUTES = 5 VERSION = 0.3 def main(): """Main processing.""" usage = '%prog [options]' + '\nVersion: %s' % VERSION parser = OptionParser(usage=usage) parser.add_option('-o', '--once', action='store_true', dest='once', default=False, help='Delete sessions, then exit.', ) parser.add_option('-s', '--sleep', dest='sleep', default=SLEEP_MINUTES * 60, type="int", help='Number of seconds to sleep between executions. Default 300.', ) parser.add_option('-x', '--expiration', dest='expiration', default=None, type="int", help='Expiration value for sessions without expiration (in seconds)', ) parser.add_option('-f', '--force', action='store_true', dest='force', default=False, help=('Ignore session expiration. ' 'Force expiry based on -x option or auth.settings.expiration.') ) parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False, help='Print verbose output.', ) (options, unused_args) = parser.parse_args() expiration = options.expiration if expiration is None: try: expiration = auth.settings.expiration except: expiration = EXPIRATION_MINUTES * 60 while True: trash_session_files(expiration, options.force, options.verbose) if options.once: break else: time.sleep(options.sleep) def trash_session_files(expiration, force=False, verbose=False): """ Trashes expired session files. Arguments:: expiration: integer, expiration value to use for sessions without one. force: If True, ignores session expiration and use value of expiration argument. verbose: If True, print names of sessions trashed. """ now = datetime.datetime.now() path = os.path.join(request.folder, 'sessions') for file in os.listdir(path): filename = os.path.join(path, file) last_visit = datetime.datetime.fromtimestamp( os.stat(filename)[stat.ST_MTIME]) if expiration > 0: try: f = open(filename, 'rb+') try: session = Storage() session.update(cPickle.load(f)) finally: f.close() if session.auth: if session.auth.expiration and not force: expiration = session.auth.expiration if session.auth.last_visit: last_visit = session.auth.last_visit except: pass if expiration == 0 or \ total_seconds(now - last_visit) > expiration: os.unlink(filename) if verbose: print('Session trashed: %s' % file) def total_seconds(delta): """ Adapted from Python 2.7's timedelta.total_seconds() method. Args: delta: datetime.timedelta instance. """ return (delta.microseconds + (delta.seconds + (delta.days * 24 * 3600)) * \ 10 ** 6) / 10 ** 6 main()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # TODO: Comment this code import sys import shutil import os from gluon.languages import findT sys.path.insert(0, '.') file = sys.argv[1] apps = sys.argv[2:] d = {} for app in apps: path = 'applications/%s/' % app findT(path, file) langfile = open(os.path.join(path, 'languages', '%s.py' % file)) try: data = eval(langfile.read()) finally: langfile.close() d.update(data) path = 'applications/%s/' % apps[-1] file1 = os.path.join(path, 'languages', '%s.py' % file) f = open(file1, 'w') try: f.write('{\n') keys = d.keys() keys.sort() for key in keys: f.write('%s:%s,\n' % (repr(key), repr(str(d[key])))) f.write('}\n') finally: f.close() oapps = reversed(apps[:-1]) for app in oapps: path2 = 'applications/%s/' % app file2 = os.path.join(path2, 'languages', '%s.py' % file) shutil.copyfile(file1, file2)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """Create web2py model (python code) to represent PostgreSQL tables. Features: * Uses ANSI Standard INFORMATION_SCHEMA (might work with other RDBMS) * Detects legacy "keyed" tables (not having an "id" PK) * Connects directly to running databases, no need to do a SQL dump * Handles notnull, unique and referential constraints * Detects most common datatypes and default values * Support PostgreSQL columns comments (ie. for documentation) Requeriments: * Needs PostgreSQL pyscopg2 python connector (same as web2py) * If used against other RDBMS, import and use proper connector (remove pg_ code) Created by Mariano Reingart, based on a script to "generate schemas from dbs" (mysql) by Alexandre Andrade """ _author__ = "Mariano Reingart <reingart@gmail.com>" HELP = """ USAGE: extract_pgsql_models db host port user passwd Call with PostgreSQL database connection parameters, web2py model will be printed on standard output. EXAMPLE: python extract_pgsql_models.py mydb localhost 5432 reingart saraza """ # Config options DEBUG = False # print debug messages to STDERR SCHEMA = 'public' # change if not using default PostgreSQL schema # Constant for Field keyword parameter order (and filter): KWARGS = ('type', 'length', 'default', 'required', 'ondelete', 'notnull', 'unique', 'label', 'comment') import sys def query(conn, sql,*args): "Execute a SQL query and return rows as a list of dicts" cur = conn.cursor() ret = [] try: if DEBUG: print >> sys.stderr, "QUERY: ", sql % args cur.execute(sql, args) for row in cur: dic = {} for i, value in enumerate(row): field = cur.description[i][0] dic[field] = value if DEBUG: print >> sys.stderr, "RET: ", dic ret.append(dic) return ret finally: cur.close() def get_tables(conn, schema=SCHEMA): "List table names in a given schema" rows = query(conn, """SELECT table_name FROM information_schema.tables WHERE table_schema = %s ORDER BY table_name""", schema) return [row['table_name'] for row in rows] def get_fields(conn, table): "Retrieve field list for a given table" if DEBUG: print >> sys.stderr, "Processing TABLE", table rows = query(conn, """ SELECT column_name, data_type, is_nullable, character_maximum_length, numeric_precision, numeric_precision_radix, numeric_scale, column_default FROM information_schema.columns WHERE table_name=%s ORDER BY ordinal_position""", table) return rows def define_field(conn, table, field, pks): "Determine field type, default value, references, etc." f={} ref = references(conn, table, field['column_name']) if ref: f.update(ref) elif field['column_default'] and \ field['column_default'].startswith("nextval") and \ field['column_name'] in pks: # postgresql sequence (SERIAL) and primary key! f['type'] = "'id'" elif field['data_type'].startswith('character'): f['type'] = "'string'" if field['character_maximum_length']: f['length'] = field['character_maximum_length'] elif field['data_type'] in ('text', ): f['type'] = "'text'" elif field['data_type'] in ('boolean', 'bit'): f['type'] = "'boolean'" elif field['data_type'] in ('integer', 'smallint', 'bigint'): f['type'] = "'integer'" elif field['data_type'] in ('double precision', 'real' ): f['type'] = "'double'" elif field['data_type'] in ('timestamp', 'timestamp without time zone'): f['type'] = "'datetime'" elif field['data_type'] in ('date', ): f['type'] = "'date'" elif field['data_type'] in ('time', 'time without time zone'): f['type'] = "'time'" elif field['data_type'] in ('numeric', 'currency'): f['type'] = "'decimal'" f['precision'] = field['numeric_precision'] f['scale'] = field['numeric_scale'] or 0 elif field['data_type'] in ('bytea', ): f['type'] = "'blob'" elif field['data_type'] in ('point', 'lseg', 'polygon', 'unknown', 'USER-DEFINED'): f['type'] = "" # unsupported? else: raise RuntimeError("Data Type not supported: %s " % str(field)) try: if field['column_default']: if field['column_default']=="now()": d = "request.now" elif field['column_default']=="true": d = "True" elif field['column_default']=="false": d = "False" else: d = repr(eval(field['column_default'])) f['default'] = str(d) except (ValueError, SyntaxError): pass except Exception, e: raise RuntimeError("Default unsupported '%s'" % field['column_default']) if not field['is_nullable']: f['notnull'] = "True" comment = get_comment(conn, table, field) if comment is not None: f['comment'] = repr(comment) return f def is_unique(conn, table, field): "Find unique columns (incomplete support)" rows = query(conn, """ SELECT information_schema.constraint_column_usage.column_name FROM information_schema.table_constraints NATURAL JOIN information_schema.constraint_column_usage WHERE information_schema.table_constraints.table_name=%s AND information_schema.constraint_column_usage.column_name=%s AND information_schema.table_constraints.constraint_type='UNIQUE' ;""", table, field['column_name']) return rows and True or False def get_comment(conn, table, field): "Find the column comment (postgres specific)" rows = query(conn, """ SELECT d.description AS comment FROM pg_class c JOIN pg_description d ON c.oid=d.objoid JOIN pg_attribute a ON c.oid = a.attrelid WHERE c.relname=%s AND a.attname=%s AND a.attnum = d.objsubid ;""", table, field['column_name']) return rows and rows[0]['comment'] or None def primarykeys(conn, table): "Find primary keys" rows = query(conn, """ SELECT information_schema.constraint_column_usage.column_name FROM information_schema.table_constraints NATURAL JOIN information_schema.constraint_column_usage WHERE information_schema.table_constraints.table_name=%s AND information_schema.table_constraints.constraint_type='PRIMARY KEY' ;""", table) return [row['column_name'] for row in rows] def references(conn, table, field): "Find a FK (fails if multiple)" rows1 = query(conn, """ SELECT table_name, column_name, constraint_name, update_rule, delete_rule, ordinal_position FROM information_schema.key_column_usage NATURAL JOIN information_schema.referential_constraints NATURAL JOIN information_schema.table_constraints WHERE information_schema.key_column_usage.table_name=%s AND information_schema.key_column_usage.column_name=%s AND information_schema.table_constraints.constraint_type='FOREIGN KEY' ;""", table, field) if len(rows1)==1: rows2 = query(conn, """ SELECT table_name, column_name, * FROM information_schema.constraint_column_usage WHERE constraint_name=%s """, rows1[0]['constraint_name']) row = None if len(rows2)>1: row = rows2[int(rows1[0]['ordinal_position'])-1] keyed = True if len(rows2)==1: row = rows2[0] keyed = False if row: if keyed: # THIS IS BAD, DON'T MIX "id" and primarykey!!! ref = {'type': "'reference %s.%s'" % (row['table_name'], row['column_name'])} else: ref = {'type': "'reference %s'" % (row['table_name'],)} if rows1[0]['delete_rule']!="NO ACTION": ref['ondelete'] = repr(rows1[0]['delete_rule']) return ref elif rows2: raise RuntimeError("Unsupported foreign key reference: %s" % str(rows2)) elif rows1: raise RuntimeError("Unsupported referential constraint: %s" % str(rows1)) def define_table(conn, table): "Output single table definition" fields = get_fields(conn, table) pks = primarykeys(conn, table) print "db.define_table('%s'," % (table, ) for field in fields: fname = field['column_name'] fdef = define_field(conn, table, field, pks) if fname not in pks and is_unique(conn, table, field): fdef['unique'] = "True" if fdef['type']=="'id'" and fname in pks: pks.pop(pks.index(fname)) print " Field('%s', %s)," % (fname, ', '.join(["%s=%s" % (k, fdef[k]) for k in KWARGS if k in fdef and fdef[k]])) if pks: print " primarykey=[%s]," % ", ".join(["'%s'" % pk for pk in pks]) print " migrate=migrate)" print def define_db(conn, db, host, port, user, passwd): "Output database definition (model)" dal = 'db = DAL("postgres://%s:%s@%s:%s/%s", pool_size=10)' print dal % (user, passwd, host, port, db) print print "migrate = False" print for table in get_tables(conn): define_table(conn, table) if __name__ == "__main__": if len(sys.argv) < 6: print HELP else: # Parse arguments from command line: db, host, port, user, passwd = sys.argv[1:6] # Make the database connection (change driver if required) import psycopg2 cnn = psycopg2.connect(database=db, host=host, port=port, user=user, password=passwd, ) # Start model code generation: define_db(cnn, db, host, port, user, passwd)
Python
import sys import re def cleancss(text): text=re.compile('\s+').sub(' ', text) text=re.compile('\s*(?P<a>,|:)\s*').sub('\g<a> ', text) text=re.compile('\s*;\s*').sub(';\n ', text) text=re.compile('\s*\{\s*').sub(' {\n ', text) text=re.compile('\s*\}\s*').sub('\n}\n\n', text) return text def cleanhtml(text): text=text.lower() r=re.compile('\<script.+?/script\>', re.DOTALL) scripts=r.findall(text) text=r.sub('<script />', text) r=re.compile('\<style.+?/style\>', re.DOTALL) styles=r.findall(text) text=r.sub('<style />', text) text=re.compile( '<(?P<tag>(input|meta|link|hr|br|img|param))(?P<any>[^\>]*)\s*(?<!/)>')\ .sub('<\g<tag>\g<any> />', text) text=text.replace('\n', ' ') text=text.replace('>', '>\n') text=text.replace('<', '\n<') text=re.compile('\s*\n\s*').sub('\n', text) lines=text.split('\n') (indent, newlines)=(0, []) for line in lines: if line[:2]=='</': indent=indent-1 newlines.append(indent*' '+line) if not line[:2]=='</' and line[-1:]=='>' and \ not line[-2:] in ['/>', '->']: indent=indent+1 text='\n'.join(newlines) text=re.compile('\<div(?P<a>( .+)?)\>\s+\</div\>').sub('<div\g<a>></div>',text) text=re.compile('\<a(?P<a>( .+)?)\>\s+(?P<b>[\w\s\(\)\/]+?)\s+\</a\>').sub('<a\g<a>>\g<b></a>',text) text=re.compile('\<b(?P<a>( .+)?)\>\s+(?P<b>[\w\s\(\)\/]+?)\s+\</b\>').sub('<b\g<a>>\g<b></b>',text) text=re.compile('\<i(?P<a>( .+)?)\>\s+(?P<b>[\w\s\(\)\/]+?)\s+\</i\>').sub('<i\g<a>>\g<b></i>',text) text=re.compile('\<span(?P<a>( .+)?)\>\s+(?P<b>[\w\s\(\)\/]+?)\s+\</span\>').sub('<span\g<a>>\g<b></span>',text) text=re.compile('\s+\<br(?P<a>.*?)\/\>').sub('<br\g<a>/>',text) text=re.compile('\>(?P<a>\s+)(?P<b>[\.\,\:\;])').sub('>\g<b>\g<a>',text) text=re.compile('\n\s*\n').sub('\n',text) for script in scripts: text=text.replace('<script />', script, 1) for style in styles: text=text.replace('<style />', cleancss(style), 1) return text def read_file(filename): f = open(filename, 'r') try: return f.read() finally: f.close() file=sys.argv[1] if file[-4:]=='.css': print cleancss(read_file(file)) if file[-5:]=='.html': print cleanhtml(read_file(file))
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import re filename = sys.argv[1] datafile = open(filename, 'r') try: data = datafile.read() finally: datafile.close() data = re.compile('\s*{\s*').sub(' { ', data) data = re.compile('\s*;\s*').sub('; ', data) data = re.compile('\s*}\s*').sub(' }\n', data) data = re.compile('[ ]+').sub(' ', data) print data
Python
''' Create the web2py code needed to access your mysql legacy db. To make this work all the legacy tables you want to access need to have an "id" field. This plugin needs: mysql mysqldump installed and globally available. Under Windows you will probably need to add the mysql executable directory to the PATH variable, you will also need to modify mysql to mysql.exe and mysqldump to mysqldump.exe below. Just guessing here :) Access your tables with: legacy_db(legacy_db.mytable.id>0).select() If the script crashes this is might be due to that fact that the data_type_map dictionary below is incomplete. Please complete it, improve it and continue. Created by Falko Krause, minor modifications by Massimo Di Pierro and Ron McOuat ''' import subprocess import re import sys data_type_map = dict( varchar = 'string', int = 'integer', integer = 'integer', tinyint = 'integer', smallint = 'integer', mediumint = 'integer', bigint = 'integer', float = 'double', double = 'double', char = 'string', decimal = 'integer', date = 'date', #year = 'date', time = 'time', timestamp = 'datetime', datetime = 'datetime', binary = 'blob', blob = 'blob', tinyblob = 'blob', mediumblob = 'blob', longblob = 'blob', text = 'text', tinytext = 'text', mediumtext = 'text', longtext = 'text', ) def mysql(database_name, username, password): p = subprocess.Popen(['mysql', '--user=%s' % username, '--password=%s'% password, '--execute=show tables;', database_name], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) sql_showtables, stderr = p.communicate() tables = [re.sub('\|\s+([^\|*])\s+.*', '\1', x) for x in sql_showtables.split()[1:]] connection_string = "legacy_db = DAL('mysql://%s:%s@localhost/%s')"%(username, password, database_name) legacy_db_table_web2py_code = [] for table_name in tables: #get the sql create statement p = subprocess.Popen(['mysqldump', '--user=%s' % username, '--password=%s' % password, '--skip-add-drop-table', '--no-data', database_name, table_name], stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE) sql_create_stmnt,stderr = p.communicate() if 'CREATE' in sql_create_stmnt:#check if the table exists #remove garbage lines from sql statement sql_lines = sql_create_stmnt.split('\n') sql_lines = [x for x in sql_lines if not(x.startswith('--') or x.startswith('/*') or x =='')] #generate the web2py code from the create statement web2py_table_code = '' table_name = re.search('CREATE TABLE .(\S+). \(', sql_lines[0]).group(1) fields = [] for line in sql_lines[1:-1]: if re.search('KEY', line) or re.search('PRIMARY', line) or re.search(' ID', line) or line.startswith(')'): continue hit = re.search('(\S+)\s+(\S+)(,| )( .*)?', line) if hit!=None: name, d_type = hit.group(1), hit.group(2) d_type = re.sub(r'(\w+)\(.*',r'\1',d_type) name = re.sub('`','',name) web2py_table_code += "\n Field('%s','%s'),"%(name,data_type_map[d_type]) web2py_table_code = "legacy_db.define_table('%s',%s\n migrate=False)"%(table_name,web2py_table_code) legacy_db_table_web2py_code.append(web2py_table_code) #---------------------------------------- #write the legacy db to file legacy_db_web2py_code = connection_string+"\n\n" legacy_db_web2py_code += "\n\n#--------\n".join(legacy_db_table_web2py_code) return legacy_db_web2py_code regex = re.compile('(.*?):(.*?)@(.*)') if len(sys.argv)<2 or not regex.match(sys.argv[1]): print 'USAGE:\n\n extract_mysql_models.py username:password@data_basename\n\n' else: m = regex.match(sys.argv[1]) print mysql(m.group(3),m.group(1),m.group(2))
Python
#!/usr/bin/python # -*- coding: utf-8 -*- ''' autoroutes writes routes for you based on a simpler routing configuration file called routes.conf. Example: ----- BEGIN routes.conf------- 127.0.0.1 /examples/default domain1.com /app1/default domain2.com /app2/default domain3.com /app3/default ----- END ---------- It maps a domain (the left-hand side) to an app (one app per domain), and shortens the URLs for the app by removing the listed path prefix. That means: http://domain1.com/index is mapped to /app1/default/index http://domain2.com/index is mapped to /app2/default/index It preserves admin, appadmin, static files, favicon.ico and robots.txt: http://domain1.com/favicon.ico /welcome/static/favicon.ico http://domain1.com/robots.txt /welcome/static/robots.txt http://domain1.com/admin/... /admin/... http://domain1.com/appadmin/... /app1/appadmin/... http://domain1.com/static/... /app1/static/... and vice-versa. To use, cp scripts/autoroutes.py routes.py and either edit the config string below, or set config = "" and edit routes.conf ''' config = ''' 127.0.0.1 /examples/default domain1.com /app1/default domain2.com /app2/default domain3.com /app3/defcon3 ''' if not config.strip(): try: config_file = open('routes.conf','r') try: config = config_file.read() finally: config_file.close() except: config='' def auto_in(apps): routes = [ ('/robots.txt','/welcome/static/robots.txt'), ('/favicon.ico','/welcome/static/favicon.ico'), ('/admin$anything','/admin$anything'), ] for domain,path in [x.strip().split() for x in apps.split('\n') if x.strip() and not x.strip().startswith('#')]: if not path.startswith('/'): path = '/'+path if path.endswith('/'): path = path[:-1] app = path.split('/')[1] routes += [ ('.*:https?://(.*\.)?%s:$method /' % domain,'%s' % path), ('.*:https?://(.*\.)?%s:$method /static/$anything' % domain,'/%s/static/$anything' % app), ('.*:https?://(.*\.)?%s:$method /appadmin/$anything' % domain,'/%s/appadmin/$anything' % app), ('.*:https?://(.*\.)?%s:$method /$anything' % domain,'%s/$anything' % path), ] return routes def auto_out(apps): routes = [] for domain,path in [x.strip().split() for x in apps.split('\n') if x.strip() and not x.strip().startswith('#')]: if not path.startswith('/'): path = '/'+path if path.endswith('/'): path = path[:-1] app = path.split('/')[1] routes += [ ('/%s/static/$anything' % app,'/static/$anything'), ('/%s/appadmin/$anything' % app, '/appadmin/$anything'), ('%s/$anything' % path, '/$anything'), ] return routes routes_in = auto_in(config) routes_out = auto_out(config) def __routes_doctest(): ''' Dummy function for doctesting autoroutes.py. Use filter_url() to test incoming or outgoing routes; filter_err() for error redirection. filter_url() accepts overrides for method and remote host: filter_url(url, method='get', remote='0.0.0.0', out=False) filter_err() accepts overrides for application and ticket: filter_err(status, application='app', ticket='tkt') >>> filter_url('http://domain1.com/favicon.ico') 'http://domain1.com/welcome/static/favicon.ico' >>> filter_url('https://domain2.com/robots.txt') 'https://domain2.com/welcome/static/robots.txt' >>> filter_url('http://domain3.com/fcn') 'http://domain3.com/app3/defcon3/fcn' >>> filter_url('http://127.0.0.1/fcn') 'http://127.0.0.1/examples/default/fcn' >>> filter_url('HTTP://DOMAIN.COM/app/ctr/fcn') 'http://domain.com/app/ctr/fcn' >>> filter_url('http://domain.com/app/ctr/fcn?query') 'http://domain.com/app/ctr/fcn?query' >>> filter_url('http://otherdomain.com/fcn') 'http://otherdomain.com/fcn' >>> regex_filter_out('/app/ctr/fcn') '/app/ctr/fcn' >>> regex_filter_out('/app1/ctr/fcn') '/app1/ctr/fcn' >>> filter_url('https://otherdomain.com/app1/default/fcn', out=True) '/fcn' >>> filter_url('http://otherdomain.com/app2/ctr/fcn', out=True) '/app2/ctr/fcn' >>> filter_url('http://domain1.com/app1/default/fcn?query', out=True) '/fcn?query' >>> filter_url('http://domain2.com/app3/defcon3/fcn#anchor', out=True) '/fcn#anchor' ''' pass if __name__ == '__main__': try: import gluon.main except ImportError: import sys, os os.chdir(os.path.dirname(os.path.dirname(__file__))) sys.path.append(os.path.dirname(os.path.dirname(__file__))) import gluon.main from gluon.rewrite import regex_select, load, filter_url, regex_filter_out regex_select() # use base routing parameters load(routes=__file__) # load this file import doctest doctest.testmod()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- import cStringIO import re import sys import tarfile import urllib import xml.parsers.expat as expat """ Update script for contenttype.py module. Usage: python contentupdate.py /path/to/contenttype.py If no path is specified, script will look for contenttype.py in current working directory. Internet connection is required to perform the update. """ OVERRIDE = [ ('.pdb', 'chemical/x-pdb'), ('.xyz', 'chemical/x-pdb') ] class MIMEParser(dict): def __start_element_handler(self, name, attrs): if name == 'mime-type': if self.type: for extension in self.extensions: self[extension] = self.type self.type = attrs['type'].lower() self.extensions = [] elif name == 'glob': pattern = attrs['pattern'] if pattern.startswith('*.'): self.extensions.append(pattern[1:].lower()) def __init__(self, fileobj): dict.__init__(self) self.type = '' self.extensions = '' parser = expat.ParserCreate() parser.StartElementHandler = self.__start_element_handler parser.ParseFile(fileobj) for extension, contenttype in OVERRIDE: self[extension] = contenttype if __name__ == '__main__': try: path = sys.argv[1] except: path = 'contenttype.py' vregex = re.compile('database version (?P<version>.+?)\.?\n') sys.stdout.write('Checking contenttype.py database version:') sys.stdout.flush() try: pathfile = open(path) try: current = pathfile.read() finally: pathfile.close() cversion = re.search(vregex, current).group('version') sys.stdout.write('\t[OK] version %s\n' % cversion) except Exception, e: sys.stdout.write('\t[ERROR] %s\n' % e) exit() sys.stdout.write('Checking freedesktop.org database version:') sys.stdout.flush() try: search = re.search('(?P<url>http://freedesktop.org/.+?/shared-mime-info-(?P<version>.+?)\.tar\.(?P<type>[gb]z2?))', urllib.urlopen('http://www.freedesktop.org/wiki/Software/shared-mime-info').read()) url = search.group('url') assert url != None nversion = search.group('version') assert nversion != None ftype = search.group('type') assert ftype != None sys.stdout.write('\t[OK] version %s\n' % nversion) except: sys.stdout.write('\t[ERROR] unknown version\n') exit() if cversion == nversion: sys.stdout.write('\nContenttype.py database is up to date\n') exit() try: raw_input('\nContenttype.py database updates are available from:\n%s (approx. 0.5MB)\nPress enter to continue or CTRL-C to quit now\nWARNING: this will replace contenttype.py file content IN PLACE' % url) except: exit() sys.stdout.write('\nDownloading new database:') sys.stdout.flush() fregex = re.compile('^.*/freedesktop\.org\.xml$') try: io = cStringIO.StringIO() io.write(urllib.urlopen(url).read()) sys.stdout.write('\t[OK] done\n') except Exception, e: sys.stdout.write('\t[ERROR] %s\n' % e) exit() sys.stdout.write('Installing new database:') sys.stdout.flush() try: tar = tarfile.TarFile.open(fileobj=io, mode='r:%s' % ftype) try: for content in tar.getnames(): if fregex.match(content): xml = tar.extractfile(content) break finally: tar.close() data = MIMEParser(xml) io = cStringIO.StringIO() io.write('CONTENT_TYPE = {\n') for key in sorted(data): io.write(' \'%s\': \'%s\',\n' % (key, data[key])) io.write(' }') io.seek(0) contenttype = open('contenttype.py', 'w') try: contenttype.write(re.sub(vregex, 'database version %s.\n' % nversion, re.sub('CONTENT_TYPE = \{(.|\n)+?\}', io.getvalue(), current))) finally: contenttype.close() if not current.closed: current.close() sys.stdout.write('\t\t\t[OK] done\n') except Exception, e: sys.stdout.write('\t\t\t[ERROR] %s\n' % e)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import time import stat import datetime from gluon.utils import md5_hash from gluon.restricted import RestrictedError from gluon.tools import Mail path = os.path.join(request.folder, 'errors') hashes = {} mail = Mail() ### CONFIGURE HERE SLEEP_MINUTES = 5 ALLOW_DUPLICATES = True mail.settings.server = 'localhost:25' mail.settings.sender = 'you@localhost' administrator_email = 'you@localhost' ### END CONFIGURATION while 1: for file in os.listdir(path): filename = os.path.join(path, file) if not ALLOW_DUPLICATES: fileobj = open(filename, 'r') try: file_data = fileobj.read() finally: fileobj.close() key = md5_hash(file_data) if key in hashes: continue hashes[key] = 1 error = RestrictedError() error.load(request, request.application, filename) mail.send(to=administrator_email, subject='new web2py ticket', message=error.traceback) os.unlink(filename) time.sleep(SLEEP_MINUTES * 60)
Python
import sys, glob def read_fileb(filename, mode='rb'): f = open(filename, mode) try: return f.read() finally: f.close() def write_fileb(filename, value, mode='wb'): f = open(filename, mode) try: f.write(value) finally: f.close() for filename in glob.glob(sys.argv[1]): data1 = read_fileb(filename) write_fileb(filename + '.bak2', data1) data2lines = read_fileb(filename).split('\n') data2 = '\n'.join([line.rstrip() for line in data2lines])+'\n' write_fileb(filename, data2) print filename, len(data1)-len(data2)
Python
import os,sys from collections import deque import string import argparse import cStringIO,operator import cPickle as pickle from collections import deque import math import re import cmd import readline try: from gluon import DAL except ImportError as err: print('gluon path not found') class refTable(object): def __init__(self): self.columns = None self.rows = None def getcolHeader(self,colHeader): return "{0}".format(' | '.join([string.join(string.strip('**{0}**'.format(item)), '') for item in colHeader])) def wrapTable(self,rows, hasHeader=False, headerChar='-', delim=' | ', justify='left', separateRows=False, prefix='', postfix='', wrapfunc=lambda x:x): def rowWrapper(row): '''--- newRows is returned like [['w'], ['x'], ['y'], ['z']] ---''' newRows = [wrapfunc(item).split('\n') for item in row] self.rows = newRows '''--- rowList gives like newRows but formatted like [[w, x, y, z]] ---''' rowList = [[substr or '' for substr in item] for item in map(None,*newRows)] return rowList logicalRows = [rowWrapper(row) for row in rows] columns = map(None,*reduce(operator.add,logicalRows)) self.columns = columns maxWidths = [max(\ [len(str\ (item)) for \ item in column]\ ) for column \ in columns] rowSeparator = headerChar * (len(prefix) + len(postfix) + sum(maxWidths) + \ len(delim)*(len(maxWidths)-1)) justify = {'center'\ :str\ .center, 'right'\ :str\ .rjust, 'left'\ :str.\ ljust\ }[justify\ .lower(\ )] output=cStringIO.StringIO() if separateRows: print >> output, rowSeparator for physicalRows in logicalRows: for row in physicalRows: print >> output,\ prefix + delim.join([\ justify(str(item),width) for (\ item,width) in zip(row,maxWidths)]\ ) + postfix if separateRows or hasHeader: print >> output, rowSeparator; hasHeader=False return output.getvalue() def wrap_onspace(self,text,width): return reduce(lambda line, word, width=width: '{0}{1}{2}'\ .format(line\ ,' \n'[(len(\ line[line.rfind('\n'\ ) + 1:]) + len(\ word.split('\n',1)[0]) >=\ width)],word),text.split(' ')) def wrap_onspace_strict(self,text,width): wordRegex = re.compile(r'\S{'+str(width)+r',}') return self.wrap_onspace(\ wordRegex.sub(\ lambda m: self.\ wrap_always(\ m.group(),width),text\ ),width) def wrap_always(self,text,width): return '\n'.join(\ [ text[width*i:width*(i+1\ )] for i in xrange(\ int(math.ceil(1.*len(\ text)/width))) ]) class tableHelper(): def __init__(self): self.oTable = refTable() def getAsRows(self,data): return [row.strip().split(',') for row in data.splitlines()] def getTable_noWrap(self,data,header=None): rows = self.getAsRows(data) if header is not None:hRows = [header]+rows else:hRows = rows table = self.oTable.wrapTable(hRows, hasHeader=True) return table def getTable_Wrap(self,data,wrapStyle,header=None,width=65): wrapper = None if len(wrapStyle) > 1: rows = self.getAsRows(data) if header is not None:hRows = [header]+rows else:hRows = rows for wrapper in (self.oTable.wrap_always, self.oTable.wrap_onspace, self.oTable.wrap_onspace_strict): return self.oTable.wrapTable(hRows\ ,hasHeader=True\ ,separateRows=True\ ,prefix='| '\ ,postfix=' |'\ ,wrapfunc\ =lambda x:\ wrapper(x,width)) else: return self.getTable_noWrap(data,header) def getAsErrorTable(self,err): return self.getTable_Wrap(err,None) class console: def __init__(self,prompt,banner=None): self.prompt=prompt self.banner=banner self.commands={} self.commandSort=[] self.db=None for i in dir(self): if "cmd_"==i[:4]: cmd=i.split("cmd_")[1].lower() self.commands[cmd]=getattr(self,i) try:self.commandSort.append((int(self\ .commands[cmd].__doc__.split(\ "|")[0]),cmd)) except:pass self.commandSort.sort() self.commandSort=[i[1] for i in self.commandSort] self.var_DEBUG=False self.var_tableStyle='' self.configvars={} for i in dir(self): if "var_"==i[:4]: var=i.split("var_")[1] self.configvars[var]=i def setBanner(self,banner): self.banner=banner def execCmd(self,db): self.db=db print self.banner while True: try: command=raw_input(self.prompt) try: self.execCommand(command) except: self.execute(command) except KeyboardInterrupt:break except EOFError:break except Exception,a:self.printError (a) print ("\r\n\r\nBye!...") sys.exit(0) def printError(self,err): sys.stderr.write("Error: {0}\r\n".format(str(err),)) if self.var_DEBUG:pass def execute(self,cmd): try: if not '-table ' in cmd: exec '{0}'.format(cmd) else: file=None table=None fields=[] items=string.split(cmd,' ') invalidParams=[] table=self.getTable(items[1]) allowedParams=['fields','file'] for i in items: if '=' in i and not string.split(i,'=')[0] in allowedParams: try: invalidParams.append(i) except Exception, err: raise Exception, 'invalid parameter\n{0}'.format(i) else: if 'file=' in i: file=os.path.abspath(string.strip(string.split(i,'=')[1])) if 'fields=' in i: for field in string.split(string.split(i,'=')[1],','): if field in self.db[table].fields: fields.append(string.strip(field)) if len(invalidParams)>0: print('the following parameter(s) is not valid\n{0}'.format(\ string.join(invalidParams,','))) else: try: self.cmd_table(table,file,fields) except Exception, err: print('could not generate table for table {0}\n{1}'\ .format(table,err)) except Exception, err: print('sorry, can not do that!\n{0}'.format(err)) def getTable(self,tbl): for mTbl in db.tables: if tbl in mTbl: if mTbl.startswith(tbl): return mTbl def execCommand(self,cmd): words=cmd.split(" ") words=[i for i in words if i] if not words:return cmd,parameters=words[0].lower(),words[1:] if not cmd in self.commands: raise Exception("Command {0} not found. Try 'help'\r\n".format(cmd)) self.commands[cmd](*parameters) '''--- DEFAULT COMMANDS (begins with cmd_) ---''' def cmd_clear(self,numlines=100): """-5|clear|clear the screen""" if os.name == "posix": '''--- Unix/Linux/MacOS/BSD/etc ---''' os.system('clear') elif os.name in ("nt", "dos", "ce"): '''--- Windows ---''' os.system('CLS') else: '''--- Fallback for other operating systems. ---''' print '\n'*numlines def cmd_table(self,tbl,file=None,fields=[]): """-4|-table [TABLENAME] optional[file=None] [fields=None]|\ the default tableStyle is no_wrap - use the 'set x y' command to change the style\n\ style choices: \twrap_always \twrap_onspace \twrap_onspace_strict \tno_wrap (value '')\n \t the 2nd optional param is a path to a file where the table will be written \t the 3rd optional param is a list of fields you want displayed\n""" table=None for mTbl in db.tables: if tbl in mTbl: if mTbl.startswith(tbl): table=mTbl break oTable=tableHelper() '''--- tablestyle: wrap_always wrap_onspace wrap_onspace_strict or set set to "" for no wrapping ---''' tableStyle=self.var_tableStyle filedNotFound=[] table_fields=None if len(fields)==0: table_fields=self.db[table].fields else: table_fields=fields for field in fields: if not field in self.db[table].fields: filedNotFound.append(field) if len(filedNotFound)==0: rows=self.db(self.db[table].id>0).select() rows_data=[] for row in rows: rowdata=[] for f in table_fields: rowdata.append('{0}'.format(row[f])) rows_data.append(string.join(rowdata,',')) data=string.join(rows_data,'\n') dataTable=oTable.getTable_Wrap(data,tableStyle,table_fields) print('TABLE {0}\n{1}'.format(table,dataTable)) if file!=None: try: tail,head=os.path.split(file) try: os.makedirs(tail) except:'do nothing, folders exist' oFile=open(file,'w') oFile.write('TABLE: {0}\n{1}'.format(table,dataTable)) oFile.close() print('{0} has been created and populated with all available data from table {1}\n'.format(file,table)) except Exception, err: print("EXCEPTION: could not create table {0}\n{1}".format(table,err)) else: print('the following fields are not valid [{0}]'.format(string.join(filedNotFound,','))) def cmd_help(self,*args): '''-3|help|Show's help''' alldata=[] lengths=[] for i in self.commandSort:alldata.append(\ self.commands[i].__doc__.split("|")[1:]) for i in alldata: if len(i) > len(lengths): for j in range(len(i)\ -len(lengths)): lengths.append(0) j=0 while j<len(i): if len(i[j])>lengths[j]: lengths[j]=len(i[j]) j+=1 print ("-"*(lengths[0]+lengths[1]+4)) for i in alldata: print (("%-"+str(lengths[0])+"s - %-"+str(lengths[1])+"s") % (i[0],i[1])) if len(i)>2: for j in i[2:]:print (("%"+str(lengths[0]+9)+"s* %s") % (" ",j)) print def cmd_vars(self,*args): '''-2|vars|Show variables''' print ("variables\r\n"+"-"*79) for i,j in self.configvars.items(): value=self.parfmt(repr(getattr(self,j)),52) print ("| %20s | %52s |" % (i,value[0])) for k in value[1:]:print ("| %20s | %52s |" % ("",k)) if len(value)>1:print("| %20s | %52s |" % ("","")) print ("-"*79) def parfmt(self,txt,width): res=[] pos=0 while True: a=txt[pos:pos+width] if not a:break res.append(a) pos+=width return res def cmd_set(self,*args): '''-1|set [variable_name] [value]|Set configuration variable value|Values are an expressions (100 | string.lower('ABC') | etc.''' value=" ".join(args[1:]) if args[0] not in self.configvars: setattr(self,"var_{0}".format(args[0]),eval(value)) setattr(self,"var_{0}".format(args[0]),eval(value)) def cmd_clearscreen(self,numlines=50): '''---Clear the console. ---''' if os.name == "posix": '''--- Unix/Linux/MacOS/BSD/etc ---''' os.system('clear') elif os.name in ("nt", "dos", "ce"): '''--- Windows ---''' os.system('CLS') else: '''--- Fallback for other operating systems. ---''' print '\n'*numlines class dalShell(console): def __init__(self): pass def shell(self,db): console.__init__(self,prompt=">>> ",banner='dal interactive shell') self.execCmd(db) class setCopyDB(): def __init__(self): '''--- non source or target specific vars ---''' self.strModel=None self.dalPath=None self.db=None '''--- source vars ---''' self.sourceModel=None self.sourceFolder=None self.sourceConnectionString=None self.sourcedbType=None self.sourcedbName=None '''--- target vars ---''' self.targetdbType=None self.targetdbName=None self.targetModel=None self.targetFolder=None self.targetConnectionString=None self.truncate=False def _getDal(self): mDal=None if self.dalPath is not None: global DAL sys.path.append(self.dalPath) mDal=__import__('dal',globals={},locals={},fromlist=['DAL'],level=0) DAL=mDal.DAL return mDal def instDB(self,storageFolder,storageConnectionString,autoImport): self.db=DAL(storageConnectionString,folder=os.path.abspath(storageFolder),auto_import=autoImport) return self.db def delete_DB_tables(self,storageFolder,storageType): print 'delete_DB_tablesn\n\t{0}\n\t{1}'.format(storageFolder,storageType) dataFiles=[storageType,"sql.log"] try: for f in os.listdir(storageFolder): if ".table" in f: fTable="{0}/{1}".format(storageFolder,f) os.remove(fTable) print('deleted {0}'.format(fTable)) for dFile in dataFiles: os.remove("{0}/{1}".format(storageFolder,dFile)) print('deleted {0}'.format("{0}/{1}".format(storageFolder,dFile))) except Exception, errObj: print(str(errObj)) def truncatetables(self,tables=[]): if len(tables)!=0: try: print 'table value: {0}'.format(tables) for tbl in self.db.tables: for mTbl in tables: if mTbl.startswith(tbl): self.db[mTbl].truncate() except Exception, err: print('EXCEPTION: {0}'.format(err)) else: try: for tbl in self.db.tables: self.db[tbl].truncate() except Exception, err: print('EXCEPTION: {0}'.format(err)) def copyDB(self): other_db=DAL("{0}://{1}".format(self.targetdbType,self.targetdbName),folder=self.targetFolder) print 'creating tables...' for table in self.db: other_db.define_table(table._tablename,*[field for field in table]) ''' should there be an option to truncAte target DB? if yes, then change args to allow for choice and set self.trancate to the art value if self.truncate==True: other_db[table._tablename].truncate() ''' print 'exporting data...' self.db.export_to_csv_file(open('tmp.sql','wb')) print 'importing data...' other_db.import_from_csv_file(open('tmp.sql','rb')) other_db.commit() print 'done!' print 'Attention: do not run this program again or you end up with duplicate records' def createfolderPath(self,folder): try: if folder!=None:os.makedirs(folder) except Exception, err: pass if __name__ == '__main__': oCopy=setCopyDB() db=None targetDB=None dbfolder=None clean=False model=None truncate=False parser=argparse.ArgumentParser(description='\ samplecmd line:\n\ -f ./blueLite/db_storage -i -y sqlite://storage.sqlite -Y sqlite://storage2.sqlite -d ./blueLite/pyUtils/sql/blueSQL -t True', epilog = '') reqGroup=parser.add_argument_group('Required arguments') reqGroup.add_argument('-f','--sourceFolder'\ ,required=True\ ,help="path to the 'source' folder of the 'source' DB") reqGroup.add_argument('-F','--targetFolder'\ ,required=False\ ,help="path to the 'target' folder of the 'target' DB") reqGroup.add_argument('-y','--sourceConnectionString'\ ,required=True\ ,help="source db connection string ()\n\ ------------------------------------------------\n\ \ sqlite://storage.db\n\ mysql://username:password@localhost/test\n\ postgres://username:password@localhost/test\n\ mssql://username:password@localhost/test\n\ firebird://username:password@localhost/test\n\ oracle://username/password@test\n\ db2://username:password@test\n\ ingres://username:password@localhost/test\n\ informix://username:password@test\n\ \ ------------------------------------------------") reqGroup.add_argument('-Y','--targetConnectionString'\ ,required=True\ ,help="target db type (sqlite,mySql,etc.)") autoImpGroup=parser.add_argument_group('optional args (auto_import)') autoImpGroup.add_argument('-a','--autoimport'\ ,required=False\ ,help='set to True to bypass loading of the model') """ *** removing -m/-M options for now --> i need a better regex to match db.define('bla')...with optional db.commit() modelGroup=parser.add_argument_group('optional args (create model)') modelGroup.add_argument('-m','--sourcemodel'\ ,required=False\ ,help='to create a model from an existing model, point to the source model') modelGroup.add_argument('-M','--targetmodel'\ ,required=False\ ,help='to create a model from an existing model, point to the target model') """ miscGroup=parser.add_argument_group('optional args/tasks') miscGroup.add_argument('-i','--interactive'\ ,required=False\ ,action='store_true'\ ,help='run in interactive mode') miscGroup.add_argument('-d','--dal'\ ,required=False\ ,help='path to dal.py') miscGroup.add_argument('-t','--truncate'\ ,choices=['True','False']\ ,help='delete the records but *not* the table of the SOURCE DB') miscGroup.add_argument('-b','--tables'\ ,required=False\ ,type=list\ ,help='optional list (comma delimited) of SOURCE tables to truncate, defaults to all') miscGroup.add_argument('-c','--clean'\ ,required=False\ ,help='delete the DB,tables and the log file, WARNING: this is unrecoverable') args=parser.parse_args() db=None mDal=None try: oCopy.sourceFolder=args.sourceFolder oCopy.targetFolder=args.sourceFolder sourceItems=string.split(args.sourceConnectionString,'://') oCopy.sourcedbType=sourceItems[0] oCopy.sourcedbName=sourceItems[1] targetItems=string.split(args.targetConnectionString,'://') oCopy.targetdbType=sourceItems[0] oCopy.targetdbName=sourceItems[1] except Exception, err: print('EXCEPTION: {0}'.format(err)) if args.dal: try: autoImport=True if args.autoimport:autoImport=args.autoimport #sif not DAL in globals: #if not sys.path.__contains__(): oCopy.dalPath=args.dal mDal=oCopy._getDal() db=oCopy.instDB(args.sourceFolder,args.sourceConnectionString,autoImport) except Exception, err: print('EXCEPTION: could not set DAL\n{0}'.format(err)) if args.truncate: try: if args.truncate: if args.tables:tables=string.split(string.strip(args.tables),',') else:oCopy.truncatetables([]) except Exception, err: print('EXCEPTION: could not truncate tables\n{0}'.format(err)) try: if args.clean:oCopy.delete_DB_tables(oCopy.targetFolder,oCopy.targetType) except Exception, err: print('EXCEPTION: could not clean db\n{0}'.format(err)) """ *** goes with -m/-M options... removed for now if args.sourcemodel: try: oCopy.sourceModel=args.sourcemodel oCopy.targetModel=args.sourcemodel oCopy.createModel() except Exception, err: print('EXCEPTION: could not create model\n\ source model: {0}\n\ target model: {1}\n\ {2}'.format(args.sourcemodel,args.targetmodel,err)) """ if args.sourceFolder: try: oCopy.sourceFolder=os.path.abspath(args.sourceFolder) oCopy.createfolderPath(oCopy.sourceFolder) except Exception, err: print('EXCEPTION: could not create folder path\n{0}'.format(err)) else:oCopy.dbStorageFolder=os.path.abspath(os.getcwd()) if args.targetFolder: try: oCopy.targetFolder=os.path.abspath(args.targetFolder) oCopy.createfolderPath(oCopy.targetFolder) except Exception, err: print('EXCEPTION: could not create folder path\n{0}'.format(err)) if not args.interactive: try: oCopy.copyDB() except Exception, err: print('EXCEPTION: could not make a copy of the database\n{0}'.format(err)) else: s=dalShell() s.shell(db)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # routers are dictionaries of URL routing parameters. # # For each request, the effective router is: # the built-in default base router (shown below), # updated by the BASE router in routes.py routers, # updated by the app-specific router in routes.py routers (if any), # updated by the app-specific router from applications/app/routes.py routers (if any) # # # Router members: # # default_application: default application name # applications: list of all recognized applications, or 'ALL' to use all currently installed applications # Names in applications are always treated as an application names when they appear first in an incoming URL. # Set applications=None to disable the removal of application names from outgoing URLs. # domains: optional dict mapping domain names to application names # The domain name can include a port number: domain.com:8080 # The application name can include a controller: appx/ctlrx # Example: # domains = { "domain.com" : "app", # "x.domain.com" : "appx", # }, # path_prefix: a path fragment that is prefixed to all outgoing URLs and stripped from all incoming URLs # # Note: default_application, applications, domains & path_prefix are permitted only in the BASE router, # and domain makes sense only in an application-specific router. # The remaining members can appear in the BASE router (as defaults for all applications) # or in application-specific routers. # # default_controller: name of default controller # default_function: name of default function (in all controllers) # controllers: list of valid controllers in selected app # or "DEFAULT" to use all controllers in the selected app plus 'static' # or None to disable controller-name removal. # Names in controllers are always treated as controller names when they appear in an incoming URL after # the (optional) application and language names. # functions: list of valid functions in the default controller (default None) # If present, the default function name will be omitted when the controller is the default controller # and the first arg does not create an ambiguity. # languages: list of all supported languages # Names in languages are always treated as language names when they appear in an incoming URL after # the (optional) application name. # default_language # The language code (for example: en, it-it) optionally appears in the URL following # the application (which may be omitted). For incoming URLs, the code is copied to # request.language; for outgoing URLs it is taken from request.language. # If languages=None, language support is disabled. # The default_language, if any, is omitted from the URL. # root_static: list of static files accessed from root (by default, favicon.ico & robots.txt) # (mapped to the default application's static/ directory) # Each default (including domain-mapped) application has its own root-static files. # domain: the domain that maps to this application (alternative to using domains in the BASE router) # exclusive_domain: If True (default is False), an exception is raised if an attempt is made to generate # an outgoing URL with a different application without providing an explicit host. # map_hyphen: If True (default is False), hyphens in incoming /a/c/f fields are converted # to underscores, and back to hyphens in outgoing URLs. # Language, args and the query string are not affected. # map_static: By default, the default application is not stripped from static URLs. # Set map_static=True to override this policy. # acfe_match: regex for valid application, controller, function, extension /a/c/f.e # file_match: regex for valid file (used for static file names) # args_match: regex for valid args # This validation provides a measure of security. # If it is changed, the application perform its own validation. # # # The built-in default router supplies default values (undefined members are None): # # default_router = dict( # default_application = 'init', # applications = 'ALL', # default_controller = 'default', # controllers = 'DEFAULT', # default_function = 'index', # functions = None, # default_language = None, # languages = None, # root_static = ['favicon.ico', 'robots.txt'], # domains = None, # map_hyphen = False, # acfe_match = r'\w+$', # legal app/ctlr/fcn/ext # file_match = r'(\w+[-=./]?)+$', # legal file (path) name # args_match = r'([\w@ -]+[=.]?)+$', # legal arg in args # ) # # See rewrite.map_url_in() and rewrite.map_url_out() for implementation details. # This simple router set overrides only the default application name, # but provides full rewrite functionality. routers = dict( # base router BASE = dict( default_application = 'welcome', ), ) # Error-handling redirects all HTTP errors (status codes >= 400) to a specified # path. If you wish to use error-handling redirects, uncomment the tuple # below. You can customize responses by adding a tuple entry with the first # value in 'appName/HTTPstatusCode' format. ( Only HTTP codes >= 400 are # routed. ) and the value as a path to redirect the user to. You may also use # '*' as a wildcard. # # The error handling page is also passed the error code and ticket as # variables. Traceback information will be stored in the ticket. # # routes_onerror = [ # (r'init/400', r'/init/default/login') # ,(r'init/*', r'/init/static/fail.html') # ,(r'*/404', r'/init/static/cantfind.html') # ,(r'*/*', r'/init/error/index') # ] # specify action in charge of error handling # # error_handler = dict(application='error', # controller='default', # function='index') # In the event that the error-handling page itself returns an error, web2py will # fall back to its old static responses. You can customize them here. # ErrorMessageTicket takes a string format dictionary containing (only) the # "ticket" key. # error_message = '<html><body><h1>%s</h1></body></html>' # error_message_ticket = '<html><body><h1>Internal error</h1>Ticket issued: <a href="/admin/default/ticket/%(ticket)s" target="_blank">%(ticket)s</a></body></html>' def __routes_doctest(): ''' Dummy function for doctesting routes.py. Use filter_url() to test incoming or outgoing routes; filter_err() for error redirection. filter_url() accepts overrides for method and remote host: filter_url(url, method='get', remote='0.0.0.0', out=False) filter_err() accepts overrides for application and ticket: filter_err(status, application='app', ticket='tkt') >>> import os >>> import gluon.main >>> from gluon.rewrite import load, filter_url, filter_err, get_effective_router >>> load(routes=os.path.basename(__file__)) >>> filter_url('http://domain.com/abc', app=True) 'welcome' >>> filter_url('http://domain.com/welcome', app=True) 'welcome' >>> os.path.relpath(filter_url('http://domain.com/favicon.ico')) 'applications/welcome/static/favicon.ico' >>> filter_url('http://domain.com/abc') '/welcome/default/abc' >>> filter_url('http://domain.com/index/abc') "/welcome/default/index ['abc']" >>> filter_url('http://domain.com/default/abc.css') '/welcome/default/abc.css' >>> filter_url('http://domain.com/default/index/abc') "/welcome/default/index ['abc']" >>> filter_url('http://domain.com/default/index/a bc') "/welcome/default/index ['a bc']" >>> filter_url('https://domain.com/app/ctr/fcn', out=True) '/app/ctr/fcn' >>> filter_url('https://domain.com/welcome/ctr/fcn', out=True) '/ctr/fcn' >>> filter_url('https://domain.com/welcome/default/fcn', out=True) '/fcn' >>> filter_url('https://domain.com/welcome/default/index', out=True) '/' >>> filter_url('https://domain.com/welcome/appadmin/index', out=True) '/appadmin' >>> filter_url('http://domain.com/welcome/default/fcn?query', out=True) '/fcn?query' >>> filter_url('http://domain.com/welcome/default/fcn#anchor', out=True) '/fcn#anchor' >>> filter_url('http://domain.com/welcome/default/fcn?query#anchor', out=True) '/fcn?query#anchor' >>> filter_err(200) 200 >>> filter_err(399) 399 >>> filter_err(400) 400 ''' pass if __name__ == '__main__': import doctest doctest.testmod()
Python
EXPIRATION_MINUTES=60 DIGITS=('0','1','2','3','4','5','6','7','8','9') import os, time, stat, logging path=os.path.join(request.folder,'sessions') if not os.path.exists(path): os.mkdir(path) now=time.time() for filename in os.listdir(path): fullpath=os.path.join(path,filename) try: if os.path.isfile(fullpath): t=os.stat(fullpath)[stat.ST_MTIME] if now-t>EXPIRATION_MINUTES*60 and filename.startswith(DIGITS): try: os.unlink(fullpath) except Exception,e: logging.warn('failure to unlink %s: %s' % (fullpath,e)) except Exception, e: logging.warn('failure to stat %s: %s' % (fullpath,e))
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"Update" ist ein optionaler Ausdruck wie "Feld1 = \'newvalue". JOIN Ergebnisse können nicht aktualisiert oder gelöscht werden', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s rows deleted': '%s Zeilen gelöscht', '%s rows updated': '%s Zeilen aktualisiert', '(requires internet access)': '(requires internet access)', '(something like "it-it")': '(so etwas wie "it-it")', 'A new version of web2py is available': 'Eine neue Version von web2py ist verfügbar', 'A new version of web2py is available: %s': 'Eine neue Version von web2py ist verfügbar: %s', 'A new version of web2py is available: Version 1.85.3 (2010-09-18 07:07:46)\n': 'Eine neue Version von web2py ist verfügbar: Version 1.85.3 (2010-09-18 07:07:46)\n', 'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.': 'ACHTUNG: Die Einwahl benötigt eine sichere (HTTPS) Verbindung. Es sei denn sie läuft Lokal(localhost).', 'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.': 'ACHTUNG: Testen ist nicht threadsicher. Führen sie also nicht mehrere Tests gleichzeitig aus.', 'ATTENTION: This is an experimental feature and it needs more testing.': 'ACHTUNG: Dies ist eine experimentelle Funktion und benötigt noch weitere Tests.', 'ATTENTION: you cannot edit the running application!': 'ACHTUNG: Eine laufende Anwendung kann nicht editiert werden!', 'About': 'Über', 'About application': 'Über die Anwendung', 'Additional code for your application': 'Additional code for your application', 'Admin is disabled because insecure channel': 'Appadmin ist deaktiviert, wegen der Benutzung eines unsicheren Kanals', 'Admin is disabled because unsecure channel': 'Appadmin ist deaktiviert, wegen der Benutzung eines unsicheren Kanals', 'Admin language': 'Admin language', 'Administrator Password:': 'Administrator Passwort:', 'Application name:': 'Application name:', 'Are you sure you want to delete file "%s"?': 'Sind Sie sich sicher, dass Sie diese Datei löschen wollen "%s"?', 'Are you sure you want to uninstall application "%s"': 'Sind Sie sich sicher, dass Sie diese Anwendung deinstallieren wollen "%s"', 'Are you sure you want to uninstall application "%s"?': 'Sind Sie sich sicher, dass Sie diese Anwendung deinstallieren wollen "%s"?', 'Are you sure you want to upgrade web2py now?': 'Sind Sie sich sicher, dass Sie web2py jetzt upgraden möchten?', 'Authentication': 'Authentifizierung', 'Available databases and tables': 'Verfügbare Datenbanken und Tabellen', 'Cannot be empty': 'Darf nicht leer sein', 'Cannot compile: there are errors in your app. Debug it, correct errors and try again.': 'Nicht Kompilierbar:Es sind Fehler in der Anwendung. Beseitigen Sie die Fehler und versuchen Sie es erneut.', 'Change Password': 'Passwort ändern', 'Check to delete': 'Markiere zum löschen', 'Checking for upgrades...': 'Auf Updates überprüfen...', 'Client IP': 'Client IP', 'Controller': 'Controller', 'Controllers': 'Controller', 'Copyright': 'Urheberrecht', 'Create new simple application': 'Erzeuge neue Anwendung', 'Current request': 'Aktuelle Anfrage (request)', 'Current response': 'Aktuelle Antwort (response)', 'Current session': 'Aktuelle Sitzung (session)', 'DB Model': 'DB Modell', 'DESIGN': 'design', 'Database': 'Datenbank', 'Date and Time': 'Datum und Uhrzeit', 'Delete': 'Löschen', 'Delete:': 'Löschen:', 'Deploy on Google App Engine': 'Auf Google App Engine installieren', 'Description': 'Beschreibung', 'Design for': 'Design für', 'E-mail': 'E-mail', 'EDIT': 'BEARBEITEN', 'Edit': 'Bearbeiten', 'Edit Profile': 'Bearbeite Profil', 'Edit This App': 'Bearbeite diese Anwendung', 'Edit application': 'Bearbeite Anwendung', 'Edit current record': 'Bearbeite aktuellen Datensatz', 'Editing Language file': 'Sprachdatei bearbeiten', 'Editing file': 'Bearbeite Datei', 'Editing file "%s"': 'Bearbeite Datei "%s"', 'Enterprise Web Framework': 'Enterprise Web Framework', 'Error logs for "%(app)s"': 'Fehlerprotokoll für "%(app)s"', 'Exception instance attributes': 'Atribute der Ausnahmeinstanz', 'Expand Abbreviation': 'Kürzel erweitern', 'First name': 'Vorname', 'Functions with no doctests will result in [passed] tests.': 'Funktionen ohne doctests erzeugen [passed] in Tests', 'Go to Matching Pair': 'gehe zum übereinstimmenden Paar', 'Group ID': 'Gruppen ID', 'Hello World': 'Hallo Welt', 'If the report above contains a ticket number it indicates a failure in executing the controller, before any attempt to execute the doctests. This is usually due to an indentation error or an error outside function code.\nA green title indicates that all tests (if defined) passed. In this case test results are not shown.': 'Falls der obere Test eine Fehler-Ticketnummer enthält deutet das auf einen Fehler in der Ausführung des Controllers hin, noch bevor der Doctest ausgeführt werden konnte. Gewöhnlich führen fehlerhafte Einrückungen oder fehlerhafter Code ausserhalb der Funktion zu solchen Fehlern. Ein grüner Titel deutet darauf hin, dass alle Test(wenn sie vorhanden sind) erfolgreich durchlaufen wurden. In diesem Fall werden die Testresultate nicht angezeigt.', 'If you answer "yes", be patient, it may take a while to download': '', 'If you answer yes, be patient, it may take a while to download': 'If you answer yes, be patient, it may take a while to download', 'Import/Export': 'Importieren/Exportieren', 'Index': 'Index', 'Installed applications': 'Installierte Anwendungen', 'Internal State': 'interner Status', 'Invalid Query': 'Ungültige Abfrage', 'Invalid action': 'Ungültige Aktion', 'Invalid email': 'Ungültige Email', 'Key bindings': 'Tastenbelegungen', 'Key bindings for ZenConding Plugin': 'Tastenbelegungen für das ZenConding Plugin', 'Language files (static strings) updated': 'Sprachdatei (statisch Strings) aktualisiert', 'Languages': 'Sprachen', 'Last name': 'Nachname', 'Last saved on:': 'Zuletzt gespeichert am:', 'Layout': 'Layout', 'License for': 'Lizenz für', 'Login': 'Anmelden', 'Login to the Administrative Interface': 'An das Administrations-Interface anmelden', 'Logout': 'Abmeldung', 'Lost Password': 'Passwort vergessen', 'Main Menu': 'Menú principal', 'Match Pair': 'Paare finden', 'Menu Model': 'Menü Modell', 'Merge Lines': 'Zeilen zusammenfügen', 'Models': 'Modelle', 'Modules': 'Module', 'NO': 'NEIN', 'Name': 'Name', 'New Record': 'Neuer Datensatz', 'New application wizard': 'New application wizard', 'New simple application': 'New simple application', 'Next Edit Point': 'nächster Bearbeitungsschritt', 'No databases in this application': 'Keine Datenbank in dieser Anwendung', 'Origin': 'Herkunft', 'Original/Translation': 'Original/Übersetzung', 'Password': 'Passwort', 'Peeking at file': 'Dateiansicht', 'Plugin "%s" in application': 'Plugin "%s" in Anwendung', 'Plugins': 'Plugins', 'Powered by': 'Unterstützt von', 'Previous Edit Point': 'vorheriger Bearbeitungsschritt', 'Query:': 'Abfrage:', 'Record ID': 'Datensatz ID', 'Register': 'registrieren', 'Registration key': 'Registrierungsschlüssel', 'Reset Password key': 'Passwortschlüssel zurücksetzen', 'Resolve Conflict file': 'bereinige Konflikt-Datei', 'Role': 'Rolle', 'Rows in table': 'Zeilen in Tabelle', 'Rows selected': 'Zeilen ausgewählt', 'Save via Ajax': 'via Ajax sichern', 'Saved file hash:': 'Gespeicherter Datei-Hash:', 'Searching:': 'Searching:', 'Static files': 'statische Dateien', 'Stylesheet': 'Stylesheet', 'Sure you want to delete this object?': 'Wollen Sie das Objekt wirklich löschen?', 'TM': 'TM', 'Table name': 'Tabellen Name', 'Testing application': 'Teste die Anwendung', 'Testing controller': 'teste Controller', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'Die "query" ist eine Bedingung wie "db.table1.field1 == \'Wert\'". Etwas wie "db.table1.field1 db.table2.field2 ==" führt zu einem SQL JOIN.', 'The application logic, each URL path is mapped in one exposed function in the controller': 'The application logic, each URL path is mapped in one exposed function in the controller', 'The data representation, define database tables and sets': 'The data representation, define database tables and sets', 'The output of the file is a dictionary that was rendered by the view': 'The output of the file is a dictionary that was rendered by the view', 'The presentations layer, views are also known as templates': 'The presentations layer, views are also known as templates', 'There are no controllers': 'Keine Controller vorhanden', 'There are no models': 'Keine Modelle vorhanden', 'There are no modules': 'Keine Module vorhanden', 'There are no plugins': 'There are no plugins', 'There are no static files': 'Keine statischen Dateien vorhanden', 'There are no translators, only default language is supported': 'Keine Übersetzungen vorhanden, nur die voreingestellte Sprache wird unterstützt', 'There are no views': 'Keine Views vorhanden', 'These files are served without processing, your images go here': 'These files are served without processing, your images go here', 'This is a copy of the scaffolding application': 'Dies ist eine Kopie einer Grundgerüst-Anwendung', 'This is the %(filename)s template': 'Dies ist das Template %(filename)s', 'Ticket': 'Ticket', 'Timestamp': 'Timestamp', 'To create a plugin, name a file/folder plugin_[name]': 'Um ein Plugin zu erstellen benennen Sie eine(n) Datei/Ordner plugin_[Name]', 'Translation strings for the application': 'Translation strings for the application', 'Unable to check for upgrades': 'überprüfen von Upgrades nicht möglich', 'Unable to download': 'herunterladen nicht möglich', 'Unable to download app': 'herunterladen der Anwendung nicht möglich', 'Update:': 'Aktualisiere:', 'Upload & install packed application': 'Verpackte Anwendung hochladen und installieren', 'Upload a package:': 'Upload a package:', 'Upload existing application': 'lade existierende Anwendung hoch', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Benutze (...)&(...) für AND, (...)|(...) für OR, und ~(...) für NOT, um komplexe Abfragen zu erstellen.', 'Use an url:': 'Use an url:', 'User ID': 'Benutzer ID', 'Version': 'Version', 'View': 'View', 'Views': 'Views', 'Welcome %s': 'Willkommen %s', 'Welcome to web2py': 'Willkommen zu web2py', 'Which called the function': 'Which called the function', 'Wrap with Abbreviation': 'mit Kürzel einhüllen', 'YES': 'JA', 'You are successfully running web2py': 'web2by wird erfolgreich ausgeführt', 'You can modify this application and adapt it to your needs': 'Sie können diese Anwendung verändern und Ihren Bedürfnissen anpassen', 'You visited the url': 'Sie besuchten die URL', 'about': 'Über', 'additional code for your application': 'zusätzlicher Code für Ihre Anwendung', 'admin disabled because no admin password': ' admin ist deaktiviert, weil kein Admin-Passwort gesetzt ist', 'admin disabled because not supported on google apps engine': 'admin ist deaktiviert, es existiert dafür keine Unterstützung auf der google apps engine', 'admin disabled because unable to access password file': 'admin ist deaktiviert, weil kein Zugriff auf die Passwortdatei besteht', 'administrative interface': 'administrative interface', 'and rename it (required):': 'und benenne sie um (erforderlich):', 'and rename it:': ' und benenne sie um:', 'appadmin': 'appadmin', 'appadmin is disabled because insecure channel': 'Appadmin ist deaktiviert, wegen der Benutzung eines unsicheren Kanals', 'application "%s" uninstalled': 'Anwendung "%s" deinstalliert', 'application compiled': 'Anwendung kompiliert', 'application is compiled and cannot be designed': 'Die Anwendung ist kompiliert kann deswegen nicht mehr geändert werden', 'arguments': 'arguments', 'back': 'zurück', 'beautify': 'beautify', 'cache': 'Cache', 'cache, errors and sessions cleaned': 'Zwischenspeicher (cache), Fehler und Sitzungen (sessions) gelöscht', 'call': 'call', 'cannot create file': 'Kann Datei nicht erstellen', 'cannot upload file "%(filename)s"': 'Kann Datei nicht Hochladen "%(filename)s"', 'change admin password': 'Administrator-Passwort ändern', 'change password': 'Passwort ändern', 'check all': 'alles auswählen', 'check for upgrades': 'check for upgrades', 'clean': 'löschen', 'click here for online examples': 'hier klicken für online Beispiele', 'click here for the administrative interface': 'hier klicken für die Administrationsoberfläche ', 'click to check for upgrades': 'hier klicken um nach Upgrades zu suchen', 'code': 'code', 'collapse/expand all': 'collapse/expand all', 'compile': 'kompilieren', 'compiled application removed': 'kompilierte Anwendung gelöscht', 'controllers': 'Controllers', 'create': 'erstellen', 'create file with filename:': 'erzeuge Datei mit Dateinamen:', 'create new application:': 'erzeuge neue Anwendung:', 'created by': 'created by', 'crontab': 'crontab', 'currently running': 'currently running', 'currently saved or': 'des derzeit gespeicherten oder', 'customize me!': 'pass mich an!', 'data uploaded': 'Daten hochgeladen', 'database': 'Datenbank', 'database %s select': 'Datenbank %s ausgewählt', 'database administration': 'Datenbankadministration', 'db': 'db', 'defines tables': 'definiere Tabellen', 'delete': 'löschen', 'delete all checked': 'lösche alle markierten', 'delete plugin': 'Plugin löschen', 'deploy': 'deploy', 'design': 'design', 'direction: ltr': 'direction: ltr', 'documentation': 'Dokumentation', 'done!': 'fertig!', 'download layouts': 'download layouts', 'download plugins': 'download plugins', 'edit': 'bearbeiten', 'edit controller': 'Bearbeite Controller', 'edit profile': 'bearbeite Profil', 'edit views:': 'Views bearbeiten:', 'errors': 'Fehler', 'escape': 'escape', 'export as csv file': 'Exportieren als CSV-Datei', 'exposes': 'stellt zur Verfügung', 'extends': 'erweitert', 'failed to reload module': 'neu laden des Moduls fehlgeschlagen', 'file "%(filename)s" created': 'Datei "%(filename)s" erstellt', 'file "%(filename)s" deleted': 'Datei "%(filename)s" gelöscht', 'file "%(filename)s" uploaded': 'Datei "%(filename)s" hochgeladen', 'file "%(filename)s" was not deleted': 'Datei "%(filename)s" wurde nicht gelöscht', 'file "%s" of %s restored': 'Datei "%s" von %s wiederhergestellt', 'file changed on disk': 'Datei auf Festplatte geändert', 'file does not exist': 'Datei existiert nicht', 'file saved on %(time)s': 'Datei gespeichert am %(time)s', 'file saved on %s': 'Datei gespeichert auf %s', 'files': 'files', 'filter': 'filter', 'help': 'Hilfe', 'htmledit': 'htmledit', 'includes': 'Einfügen', 'index': 'index', 'insert new': 'neu einfügen', 'insert new %s': 'neu einfügen %s', 'install': 'installieren', 'internal error': 'interner Fehler', 'invalid password': 'Ungültiges Passwort', 'invalid request': 'ungültige Anfrage', 'invalid ticket': 'ungültiges Ticket', 'language file "%(filename)s" created/updated': 'Sprachdatei "%(filename)s" erstellt/aktualisiert', 'languages': 'Sprachen', 'languages updated': 'Sprachen aktualisiert', 'loading...': 'lade...', 'located in the file': 'located in Datei', 'login': 'anmelden', 'logout': 'abmelden', 'lost password?': 'Passwort vergessen?', 'merge': 'verbinden', 'models': 'Modelle', 'modules': 'Module', 'new application "%s" created': 'neue Anwendung "%s" erzeugt', 'new record inserted': 'neuer Datensatz eingefügt', 'next 100 rows': 'nächsten 100 Zeilen', 'or import from csv file': 'oder importieren von cvs Datei', 'or provide app url:': 'oder geben Sie eine Anwendungs-URL an:', 'or provide application url:': 'oder geben Sie eine Anwendungs-URL an:', 'overwrite installed app': 'installierte Anwendungen überschreiben', 'pack all': 'verpacke alles', 'pack compiled': 'Verpacke kompiliert', 'pack plugin': 'Plugin verpacken', 'please wait!': 'bitte warten!', 'plugins': 'plugins', 'previous 100 rows': 'vorherige 100 zeilen', 'record': 'Datensatz', 'record does not exist': 'Datensatz existiert nicht', 'record id': 'Datensatz id', 'register': 'Registrierung', 'remove compiled': 'kompilat gelöscht', 'restore': 'wiederherstellen', 'revert': 'zurückkehren', 'save': 'sichern', 'selected': 'ausgewählt(e)', 'session expired': 'Sitzung Abgelaufen', 'shell': 'shell', 'site': 'Seite', 'some files could not be removed': 'einige Dateien konnten nicht gelöscht werden', 'start wizard': 'start wizard', 'state': 'Status', 'static': 'statische Dateien', 'submit': 'Absenden', 'table': 'Tabelle', 'test': 'Test', 'test_def': 'test_def', 'test_for': 'test_for', 'test_if': 'test_if', 'test_try': 'test_try', 'the application logic, each URL path is mapped in one exposed function in the controller': 'Die Logik der Anwendung, jeder URL-Pfad wird auf eine Funktion abgebildet die der Controller zur Verfügung stellt', 'the data representation, define database tables and sets': 'Die Datenrepräsentation definiert Mengen von Tabellen und Datenbanken ', 'the presentations layer, views are also known as templates': 'Die Präsentationsschicht, Views sind auch bekannt als Vorlagen/Templates', 'these files are served without processing, your images go here': 'Diese Dateien werden ohne Verarbeitung ausgeliefert. Beispielsweise Bilder kommen hier hin.', 'to previous version.': 'zu einer früheren Version.', 'translation strings for the application': 'Übersetzungs-Strings für die Anwendung', 'try': 'versuche', 'try something like': 'versuche so etwas wie', 'unable to create application "%s"': 'erzeugen von Anwendung "%s" nicht möglich', 'unable to delete file "%(filename)s"': 'löschen von Datein "%(filename)s" nicht möglich', 'unable to parse csv file': 'analysieren der cvs Datei nicht möglich', 'unable to uninstall "%s"': 'deinstallieren von "%s" nicht möglich', 'uncheck all': 'alles demarkieren', 'uninstall': 'deinstallieren', 'update': 'aktualisieren', 'update all languages': 'aktualisiere alle Sprachen', 'upgrade web2py now': 'jetzt web2py upgraden', 'upload': 'upload', 'upload application:': 'lade Anwendung hoch:', 'upload file:': 'lade Datei hoch:', 'upload plugin file:': 'Plugin-Datei hochladen:', 'user': 'user', 'variables': 'variables', 'versioning': 'Versionierung', 'view': 'View', 'views': 'Views', 'web2py Recent Tweets': 'neuste Tweets von web2py', 'web2py is up to date': 'web2py ist auf dem neuesten Stand', 'xml': 'xml', }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"Uaktualnij" jest dodatkowym wyrażeniem postaci "pole1=\'nowawartość\'". Nie możesz uaktualnić lub usunąć wyników z JOIN:', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s rows deleted': 'Wierszy usuniętych: %s', '%s rows updated': 'Wierszy uaktualnionych: %s', '(requires internet access)': '(requires internet access)', '(something like "it-it")': '(coś podobnego do "it-it")', 'A new version of web2py is available': 'Nowa wersja web2py jest dostępna', 'A new version of web2py is available: %s': 'A new version of web2py is available: %s', 'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.': 'UWAGA: Wymagane jest bezpieczne (HTTPS) połączenie lub połączenia z lokalnego adresu.', 'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.': 'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.', 'ATTENTION: you cannot edit the running application!': 'UWAGA: nie można edytować uruchomionych aplikacji!', 'About': 'Informacje o', 'About application': 'Informacje o aplikacji', 'Admin is disabled because insecure channel': 'Admin is disabled because insecure channel', 'Admin is disabled because unsecure channel': 'Panel administracyjny wyłączony z powodu braku bezpiecznego połączenia', 'Admin language': 'Admin language', 'Administrator Password:': 'Hasło administratora:', 'Application name:': 'Application name:', 'Are you sure you want to delete file "%s"?': 'Czy na pewno chcesz usunąć plik "%s"?', 'Are you sure you want to delete plugin "%s"?': 'Are you sure you want to delete plugin "%s"?', 'Are you sure you want to uninstall application "%s"': 'Czy na pewno chcesz usunąć aplikację "%s"', 'Are you sure you want to uninstall application "%s"?': 'Czy na pewno chcesz usunąć aplikację "%s"?', 'Are you sure you want to upgrade web2py now?': 'Are you sure you want to upgrade web2py now?', 'Available databases and tables': 'Dostępne bazy danych i tabele', 'Cannot be empty': 'Nie może być puste', 'Cannot compile: there are errors in your app. Debug it, correct errors and try again.': 'Nie można skompilować: w Twojej aplikacji są błędy . Znajdź je, popraw a następnie spróbój ponownie.', 'Cannot compile: there are errors in your app:': 'Cannot compile: there are errors in your app:', 'Check to delete': 'Zaznacz aby usunąć', 'Checking for upgrades...': 'Checking for upgrades...', 'Controllers': 'Kontrolery', 'Create new simple application': 'Utwórz nową aplikację', 'Current request': 'Aktualne żądanie', 'Current response': 'Aktualna odpowiedź', 'Current session': 'Aktualna sesja', 'DESIGN': 'PROJEKTUJ', 'Date and Time': 'Data i godzina', 'Delete': 'Usuń', 'Delete:': 'Usuń:', 'Deploy on Google App Engine': 'Umieść na Google App Engine', 'Design for': 'Projekt dla', 'EDIT': 'EDYTUJ', 'Edit application': 'Edycja aplikacji', 'Edit current record': 'Edytuj aktualny rekord', 'Editing Language file': 'Editing Language file', 'Editing file': 'Edycja pliku', 'Editing file "%s"': 'Edycja pliku "%s"', 'Enterprise Web Framework': 'Enterprise Web Framework', 'Error logs for "%(app)s"': 'Wpisy błędów dla "%(app)s"', 'Exception instance attributes': 'Exception instance attributes', 'Functions with no doctests will result in [passed] tests.': 'Functions with no doctests will result in [passed] tests.', 'Hello World': 'Witaj Świecie', 'If the report above contains a ticket number it indicates a failure in executing the controller, before any attempt to execute the doctests. This is usually due to an indentation error or an error outside function code.\nA green title indicates that all tests (if defined) passed. In this case test results are not shown.': 'If the report above contains a ticket number it indicates a failure in executing the controller, before any attempt to execute the doctests. This is usually due to an indentation error or an error outside function code.\nA green title indicates that all tests (if defined) passed. In this case test results are not shown.', 'Import/Export': 'Importuj/eksportuj', 'Installed applications': 'Zainstalowane aplikacje', 'Internal State': 'Stan wewnętrzny', 'Invalid Query': 'Błędne zapytanie', 'Invalid action': 'Błędna akcja', 'Language files (static strings) updated': 'Language files (static strings) updated', 'Languages': 'Tłumaczenia', 'Last saved on:': 'Ostatnio zapisany:', 'License for': 'Licencja dla', 'Login': 'Zaloguj', 'Login to the Administrative Interface': 'Logowanie do panelu administracyjnego', 'Models': 'Modele', 'Modules': 'Moduły', 'NO': 'NIE', 'New Record': 'Nowy rekord', 'New application wizard': 'New application wizard', 'New simple application': 'New simple application', 'No databases in this application': 'Brak baz danych w tej aplikacji', 'Original/Translation': 'Oryginał/tłumaczenie', 'PAM authenticated user, cannot change password here': 'PAM authenticated user, cannot change password here', 'Peeking at file': 'Podgląd pliku', 'Plugin "%s" in application': 'Plugin "%s" in application', 'Plugins': 'Plugins', 'Powered by': 'Powered by', 'Query:': 'Zapytanie:', 'Resolve Conflict file': 'Resolve Conflict file', 'Rows in table': 'Wiersze w tabeli', 'Rows selected': 'Wierszy wybranych', 'Saved file hash:': 'Suma kontrolna zapisanego pliku:', 'Static files': 'Pliki statyczne', 'Sure you want to delete this object?': 'Czy na pewno chcesz usunąć ten obiekt?', 'TM': 'TM', 'Testing application': 'Testing application', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': '"Zapytanie" jest warunkiem postaci "db.tabela1.pole1==\'wartość\'". Takie coś jak "db.tabela1.pole1==db.tabela2.pole2" oznacza SQL JOIN.', 'There are no controllers': 'Brak kontrolerów', 'There are no models': 'Brak modeli', 'There are no modules': 'Brak modułów', 'There are no static files': 'Brak plików statycznych', 'There are no translators, only default language is supported': 'Brak plików tłumaczeń, wspierany jest tylko domyślny język', 'There are no views': 'Brak widoków', 'This is the %(filename)s template': 'To jest szablon %(filename)s', 'Ticket': 'Bilet', 'To create a plugin, name a file/folder plugin_[name]': 'To create a plugin, name a file/folder plugin_[name]', 'Unable to check for upgrades': 'Nie można sprawdzić aktualizacji', 'Unable to download': 'Nie można ściągnąć', 'Unable to download app because:': 'Unable to download app because:', 'Unable to download because': 'Unable to download because', 'Update:': 'Uaktualnij:', 'Upload & install packed application': 'Upload & install packed application', 'Upload a package:': 'Upload a package:', 'Upload existing application': 'Wyślij istniejącą aplikację', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Użyj (...)&(...) jako AND, (...)|(...) jako OR oraz ~(...) jako NOT do tworzenia bardziej skomplikowanych zapytań.', 'Use an url:': 'Use an url:', 'Version': 'Version', 'Views': 'Widoki', 'Welcome to web2py': 'Witaj w web2py', 'YES': 'TAK', 'about': 'informacje', 'additional code for your application': 'dodatkowy kod Twojej aplikacji', 'admin disabled because no admin password': 'panel administracyjny wyłączony z powodu braku hasła administracyjnego', 'admin disabled because not supported on google app engine': 'admin disabled because not supported on google apps engine', 'admin disabled because unable to access password file': 'panel administracyjny wyłączony z powodu braku dostępu do pliku z hasłem', 'administrative interface': 'administrative interface', 'and rename it (required):': 'i nadaj jej nową nazwę (wymagane):', 'and rename it:': 'i nadaj mu nową nazwę:', 'appadmin': 'administracja aplikacji', 'appadmin is disabled because insecure channel': 'appadmin is disabled because insecure channel', 'application "%s" uninstalled': 'aplikacja "%s" została odinstalowana', 'application compiled': 'aplikacja została skompilowana', 'application is compiled and cannot be designed': 'aplikacja jest skompilowana i nie może być projektowana', 'arguments': 'arguments', 'back': 'back', 'cache': 'cache', 'cache, errors and sessions cleaned': 'pamięć podręczna, bilety błędów oraz pliki sesji zostały wyczyszczone', 'cannot create file': 'nie można utworzyć pliku', 'cannot upload file "%(filename)s"': 'nie można wysłać pliku "%(filename)s"', 'change admin password': 'change admin password', 'check all': 'zaznacz wszystko', 'check for upgrades': 'check for upgrades', 'clean': 'oczyść', 'click here for online examples': 'kliknij aby przejść do interaktywnych przykładów', 'click here for the administrative interface': 'kliknij aby przejść do panelu administracyjnego', 'click to check for upgrades': 'kliknij aby sprawdzić aktualizacje', 'code': 'code', 'compile': 'skompiluj', 'compiled application removed': 'skompilowana aplikacja została usunięta', 'controllers': 'kontrolery', 'create': 'create', 'create file with filename:': 'utwórz plik o nazwie:', 'create new application:': 'utwórz nową aplikację:', 'created by': 'created by', 'crontab': 'crontab', 'currently running': 'currently running', 'currently saved or': 'aktualnie zapisany lub', 'data uploaded': 'dane wysłane', 'database': 'baza danych', 'database %s select': 'wybór z bazy danych %s', 'database administration': 'administracja bazy danych', 'db': 'baza danych', 'defines tables': 'zdefiniuj tabele', 'delete': 'usuń', 'delete all checked': 'usuń wszystkie zaznaczone', 'delete plugin': 'delete plugin', 'deploy': 'deploy', 'design': 'projektuj', 'direction: ltr': 'direction: ltr', 'done!': 'zrobione!', 'edit': 'edytuj', 'edit controller': 'edytuj kontroler', 'edit views:': 'edit views:', 'errors': 'błędy', 'export as csv file': 'eksportuj jako plik csv', 'exposes': 'eksponuje', 'extends': 'rozszerza', 'failed to reload module': 'nie udało się przeładować modułu', 'failed to reload module because:': 'failed to reload module because:', 'file "%(filename)s" created': 'plik "%(filename)s" został utworzony', 'file "%(filename)s" deleted': 'plik "%(filename)s" został usunięty', 'file "%(filename)s" uploaded': 'plik "%(filename)s" został wysłany', 'file "%(filename)s" was not deleted': 'plik "%(filename)s" nie został usunięty', 'file "%s" of %s restored': 'plik "%s" z %s został odtworzony', 'file changed on disk': 'plik na dysku został zmieniony', 'file does not exist': 'plik nie istnieje', 'file saved on %(time)s': 'plik zapisany o %(time)s', 'file saved on %s': 'plik zapisany o %s', 'help': 'pomoc', 'htmledit': 'edytuj HTML', 'includes': 'zawiera', 'insert new': 'wstaw nowy rekord tabeli', 'insert new %s': 'wstaw nowy rekord do tabeli %s', 'install': 'install', 'internal error': 'wewnętrzny błąd', 'invalid password': 'błędne hasło', 'invalid request': 'błędne zapytanie', 'invalid ticket': 'błędny bilet', 'language file "%(filename)s" created/updated': 'plik tłumaczeń "%(filename)s" został utworzony/uaktualniony', 'languages': 'pliki tłumaczeń', 'languages updated': 'pliki tłumaczeń zostały uaktualnione', 'loading...': 'wczytywanie...', 'login': 'zaloguj', 'logout': 'wyloguj', 'merge': 'merge', 'models': 'modele', 'modules': 'moduły', 'new application "%s" created': 'nowa aplikacja "%s" została utworzona', 'new plugin installed': 'new plugin installed', 'new record inserted': 'nowy rekord został wstawiony', 'next 100 rows': 'następne 100 wierszy', 'no match': 'no match', 'or import from csv file': 'lub zaimportuj z pliku csv', 'or provide app url:': 'or provide app url:', 'or provide application url:': 'lub podaj url aplikacji:', 'overwrite installed app': 'overwrite installed app', 'pack all': 'spakuj wszystko', 'pack compiled': 'spakuj skompilowane', 'pack plugin': 'pack plugin', 'password changed': 'password changed', 'plugin "%(plugin)s" deleted': 'plugin "%(plugin)s" deleted', 'previous 100 rows': 'poprzednie 100 wierszy', 'record': 'record', 'record does not exist': 'rekord nie istnieje', 'record id': 'id rekordu', 'remove compiled': 'usuń skompilowane', 'restore': 'odtwórz', 'revert': 'przywróć', 'save': 'zapisz', 'selected': 'zaznaczone', 'session expired': 'sesja wygasła', 'shell': 'powłoka', 'site': 'strona główna', 'some files could not be removed': 'niektóre pliki nie mogły zostać usunięte', 'start wizard': 'start wizard', 'state': 'stan', 'static': 'pliki statyczne', 'submit': 'submit', 'table': 'tabela', 'test': 'testuj', 'the application logic, each URL path is mapped in one exposed function in the controller': 'logika aplikacji, każda ścieżka URL jest mapowana na jedną z funkcji eksponowanych w kontrolerze', 'the data representation, define database tables and sets': 'reprezentacja danych, definicje zbiorów i tabel bazy danych', 'the presentations layer, views are also known as templates': 'warstwa prezentacji, widoki zwane są również szablonami', 'these files are served without processing, your images go here': 'pliki obsługiwane bez interpretacji, to jest miejsce na Twoje obrazy', 'to previous version.': 'do poprzedniej wersji.', 'translation strings for the application': 'ciągi tłumaczeń dla aplikacji', 'try': 'spróbój', 'try something like': 'spróbój czegos takiego jak', 'unable to create application "%s"': 'nie można utworzyć aplikacji "%s"', 'unable to delete file "%(filename)s"': 'nie można usunąć pliku "%(filename)s"', 'unable to delete file plugin "%(plugin)s"': 'unable to delete file plugin "%(plugin)s"', 'unable to parse csv file': 'nie można sparsować pliku csv', 'unable to uninstall "%s"': 'nie można odinstalować "%s"', 'unable to upgrade because "%s"': 'unable to upgrade because "%s"', 'uncheck all': 'odznacz wszystko', 'uninstall': 'odinstaluj', 'update': 'uaktualnij', 'update all languages': 'uaktualnij wszystkie pliki tłumaczeń', 'upgrade web2py now': 'upgrade web2py now', 'upload application:': 'wyślij plik aplikacji:', 'upload file:': 'wyślij plik:', 'upload plugin file:': 'upload plugin file:', 'variables': 'variables', 'versioning': 'versioning', 'view': 'widok', 'views': 'widoki', 'web2py Recent Tweets': 'najnowsze tweety web2py', 'web2py is up to date': 'web2py jest aktualne', 'web2py upgraded; please restart it': 'web2py upgraded; please restart it', }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"actualice" es una expresión opcional como "campo1=\'nuevo_valor\'". No se puede actualizar o eliminar resultados de un JOIN', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s rows deleted': '%s filas eliminadas', '%s rows updated': '%s filas actualizadas', '(something like "it-it")': '(algo como "it-it")', 'A new version of web2py is available': 'Hay una nueva versión de web2py disponible', 'A new version of web2py is available: %s': 'Hay una nueva versión de web2py disponible: %s', 'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.': 'ATENCION: Inicio de sesión requiere una conexión segura (HTTPS) o localhost.', 'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.': 'ATENCION: NO EJECUTE VARIAS PRUEBAS SIMULTANEAMENTE, NO SON THREAD SAFE.', 'ATTENTION: you cannot edit the running application!': 'ATENCION: no puede modificar la aplicación que se ejecuta!', 'About': 'Acerca de', 'About application': 'Acerca de la aplicación', 'Admin is disabled because insecure channel': 'Admin deshabilitado, el canal no es seguro', 'Admin is disabled because unsecure channel': 'Admin deshabilitado, el canal no es seguro', 'Administrator Password:': 'Contraseña del Administrador:', 'Are you sure you want to delete file "%s"?': '¿Está seguro que desea eliminar el archivo "%s"?', 'Are you sure you want to delete plugin "%s"?': '¿Está seguro que quiere eliminar el plugin "%s"?', 'Are you sure you want to uninstall application "%s"': '¿Está seguro que desea desinstalar la aplicación "%s"', 'Are you sure you want to uninstall application "%s"?': '¿Está seguro que desea desinstalar la aplicación "%s"?', 'Are you sure you want to upgrade web2py now?': '¿Está seguro que desea actualizar web2py ahora?', 'Available databases and tables': 'Bases de datos y tablas disponibles', 'Cannot be empty': 'No puede estar vacío', 'Cannot compile: there are errors in your app. Debug it, correct errors and try again.': 'No se puede compilar: hay errores en su aplicación. Depure, corrija errores y vuelva a intentarlo.', 'Cannot compile: there are errors in your app:': 'No se puede compilar: hay errores en su aplicación:', 'Change Password': 'Cambie Contraseña', 'Check to delete': 'Marque para eliminar', 'Checking for upgrades...': 'Buscando actulizaciones...', 'Click row to expand traceback': 'Click row to expand traceback', 'Client IP': 'IP del Cliente', 'Controllers': 'Controladores', 'Count': 'Count', 'Create new application using the Wizard': 'Create new application using the Wizard', 'Create new simple application': 'Cree una nueva aplicación', 'Current request': 'Solicitud en curso', 'Current response': 'Respuesta en curso', 'Current session': 'Sesión en curso', 'DESIGN': 'DISEÑO', 'Date and Time': 'Fecha y Hora', 'Delete': 'Elimine', 'Delete:': 'Elimine:', 'Deploy on Google App Engine': 'Instale en Google App Engine', 'Description': 'Descripción', 'Design for': 'Diseño para', 'E-mail': 'Correo electrónico', 'EDIT': 'EDITAR', 'Edit Profile': 'Editar Perfil', 'Edit application': 'Editar aplicación', 'Edit current record': 'Edite el registro actual', 'Editing Language file': 'Editando archivo de lenguaje', 'Editing file': 'Editando archivo', 'Editing file "%s"': 'Editando archivo "%s"', 'Enterprise Web Framework': 'Armazón Empresarial para Internet', 'Error': 'Error', 'Error logs for "%(app)s"': 'Bitácora de errores en "%(app)s"', 'Exception instance attributes': 'Atributos de la instancia de Excepción', 'File': 'File', 'First name': 'Nombre', 'Functions with no doctests will result in [passed] tests.': 'Funciones sin doctests equivalen a pruebas [aceptadas].', 'Group ID': 'ID de Grupo', 'Hello World': 'Hola Mundo', 'If the report above contains a ticket number it indicates a failure in executing the controller, before any attempt to execute the doctests. This is usually due to an indentation error or an error outside function code.\nA green title indicates that all tests (if defined) passed. In this case test results are not shown.': 'Si el reporte anterior contiene un número de tiquete este indica un falla en la ejecución del controlador, antes de cualquier intento de ejecutat doctests. Esto generalmente se debe a un error en la indentación o un error por fuera del código de la función.\r\nUn titulo verde indica que todas las pruebas pasaron (si existen). En dicho caso los resultados no se muestran.', 'Import/Export': 'Importar/Exportar', 'Installed applications': 'Aplicaciones instaladas', 'Internal State': 'Estado Interno', 'Invalid Query': 'Consulta inválida', 'Invalid action': 'Acción inválida', 'Invalid email': 'Correo inválido', 'Language files (static strings) updated': 'Archivos de lenguaje (cadenas estáticas) actualizados', 'Languages': 'Lenguajes', 'Last name': 'Apellido', 'Last saved on:': 'Guardado en:', 'License for': 'Licencia para', 'Login': 'Inicio de sesión', 'Login to the Administrative Interface': 'Inicio de sesión para la Interfaz Administrativa', 'Logout': 'Fin de sesión', 'Lost Password': 'Contraseña perdida', 'Models': 'Modelos', 'Modules': 'Módulos', 'NO': 'NO', 'Name': 'Nombre', 'New Record': 'Registro nuevo', 'No databases in this application': 'No hay bases de datos en esta aplicación', 'Origin': 'Origen', 'Original/Translation': 'Original/Traducción', 'PAM authenticated user, cannot change password here': 'usuario autenticado por PAM, no puede cambiar la contraseña aquí', 'Password': 'Contraseña', 'Peeking at file': 'Visualizando archivo', 'Plugin "%s" in application': 'Plugin "%s" en aplicación', 'Plugins': 'Plugins', 'Powered by': 'Este sitio usa', 'Query:': 'Consulta:', 'Record ID': 'ID de Registro', 'Register': 'Registrese', 'Registration key': 'Contraseña de Registro', 'Resolve Conflict file': 'archivo Resolución de Conflicto', 'Role': 'Rol', 'Rows in table': 'Filas en la tabla', 'Rows selected': 'Filas seleccionadas', 'Saved file hash:': 'Hash del archivo guardado:', 'Static files': 'Archivos estáticos', 'Sure you want to delete this object?': '¿Está seguro que desea eliminar este objeto?', 'TM': 'MR', 'Table name': 'Nombre de la tabla', 'Testing application': 'Probando aplicación', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'La "consulta" es una condición como "db.tabla1.campo1==\'valor\'". Algo como "db.tabla1.campo1==db.tabla2.campo2" resulta en un JOIN SQL.', 'There are no controllers': 'No hay controladores', 'There are no models': 'No hay modelos', 'There are no modules': 'No hay módulos', 'There are no static files': 'No hay archivos estáticos', 'There are no translators, only default language is supported': 'No hay traductores, sólo el lenguaje por defecto es soportado', 'There are no views': 'No hay vistas', 'This is the %(filename)s template': 'Esta es la plantilla %(filename)s', 'Ticket': 'Tiquete', 'Timestamp': 'Timestamp', 'To create a plugin, name a file/folder plugin_[name]': 'Para crear un plugin, nombre un archivo/carpeta plugin_[nombre]', 'Unable to check for upgrades': 'No es posible verificar la existencia de actualizaciones', 'Unable to download': 'No es posible la descarga', 'Unable to download app': 'No es posible descargar la aplicación', 'Unable to download app because:': 'No es posible descargar la aplicación porque:', 'Unable to download because': 'No es posible descargar porque', 'Update:': 'Actualice:', 'Upload & install packed application': 'Suba e instale aplicación empaquetada', 'Upload existing application': 'Suba esta aplicación', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Use (...)&(...) para AND, (...)|(...) para OR, y ~(...) para NOT, para crear consultas más complejas.', 'User ID': 'ID de Usuario', 'Version': 'Versión', 'Views': 'Vistas', 'Welcome to web2py': 'Bienvenido a web2py', 'YES': 'SI', 'about': 'acerca de', 'additional code for your application': 'código adicional para su aplicación', 'admin disabled because no admin password': ' por falta de contraseña', 'admin disabled because not supported on google app engine': 'admin deshabilitado, no es soportado en GAE', 'admin disabled because unable to access password file': 'admin deshabilitado, imposible acceder al archivo con la contraseña', 'and rename it (required):': 'y renombrela (requerido):', 'and rename it:': ' y renombrelo:', 'appadmin': 'appadmin', 'appadmin is disabled because insecure channel': 'admin deshabilitado, el canal no es seguro', 'application "%s" uninstalled': 'aplicación "%s" desinstalada', 'application compiled': 'aplicación compilada', 'application is compiled and cannot be designed': 'la aplicación está compilada y no puede ser modificada', 'arguments': 'argumentos', 'back': 'atrás', 'browse': 'buscar', 'cache': 'cache', 'cache, errors and sessions cleaned': 'cache, errores y sesiones eliminados', 'cannot create file': 'no es posible crear archivo', 'cannot upload file "%(filename)s"': 'no es posible subir archivo "%(filename)s"', 'change admin password': 'cambie contraseña admin', 'check all': 'marcar todos', 'clean': 'limpiar', 'click here for online examples': 'haga clic aquí para ver ejemplos en línea', 'click here for the administrative interface': 'haga clic aquí para usar la interfaz administrativa', 'click to check for upgrades': 'haga clic para buscar actualizaciones', 'click to open': 'click to open', 'code': 'código', 'commit (mercurial)': 'commit (mercurial)', 'compile': 'compilar', 'compiled application removed': 'aplicación compilada removida', 'controllers': 'controladores', 'create': 'crear', 'create file with filename:': 'cree archivo con nombre:', 'create new application:': 'nombre de la nueva aplicación:', 'created by': 'creado por', 'crontab': 'crontab', 'currently saved or': 'actualmente guardado o', 'customize me!': 'Adaptame!', 'data uploaded': 'datos subidos', 'database': 'base de datos', 'database %s select': 'selección en base de datos %s', 'database administration': 'administración base de datos', 'db': 'db', 'defines tables': 'define tablas', 'delete': 'eliminar', 'delete all checked': 'eliminar marcados', 'delete plugin': 'eliminar plugin', 'design': 'modificar', 'direction: ltr': 'direction: ltr', 'done!': 'listo!', 'edit': 'editar', 'edit controller': 'editar controlador', 'edit views:': 'editar vistas:', 'errors': 'errores', 'export as csv file': 'exportar como archivo CSV', 'exposes': 'expone', 'extends': 'extiende', 'failed to reload module': 'recarga del módulo ha fallado', 'failed to reload module because:': 'no es posible recargar el módulo por:', 'file "%(filename)s" created': 'archivo "%(filename)s" creado', 'file "%(filename)s" deleted': 'archivo "%(filename)s" eliminado', 'file "%(filename)s" uploaded': 'archivo "%(filename)s" subido', 'file "%(filename)s" was not deleted': 'archivo "%(filename)s" no fué eliminado', 'file "%s" of %s restored': 'archivo "%s" de %s restaurado', 'file changed on disk': 'archivo modificado en el disco', 'file does not exist': 'archivo no existe', 'file saved on %(time)s': 'archivo guardado %(time)s', 'file saved on %s': 'archivo guardado %s', 'help': 'ayuda', 'htmledit': 'htmledit', 'includes': 'incluye', 'insert new': 'inserte nuevo', 'insert new %s': 'inserte nuevo %s', 'install': 'instalar', 'internal error': 'error interno', 'invalid password': 'contraseña inválida', 'invalid request': 'solicitud inválida', 'invalid ticket': 'tiquete inválido', 'language file "%(filename)s" created/updated': 'archivo de lenguaje "%(filename)s" creado/actualizado', 'languages': 'lenguajes', 'languages updated': 'lenguajes actualizados', 'loading...': 'cargando...', 'login': 'inicio de sesión', 'logout': 'fin de sesión', 'manage': 'manage', 'merge': 'combinar', 'models': 'modelos', 'modules': 'módulos', 'new application "%s" created': 'nueva aplicación "%s" creada', 'new plugin installed': 'nuevo plugin instalado', 'new record inserted': 'nuevo registro insertado', 'next 100 rows': '100 filas siguientes', 'no match': 'no encontrado', 'or import from csv file': 'o importar desde archivo CSV', 'or provide app url:': 'o provea URL de la aplicación:', 'or provide application url:': 'o provea URL de la aplicación:', 'overwrite installed app': 'sobreescriba aplicación instalada', 'pack all': 'empaquetar todo', 'pack compiled': 'empaquete compiladas', 'pack plugin': 'empaquetar plugin', 'password changed': 'contraseña cambiada', 'plugin "%(plugin)s" deleted': 'plugin "%(plugin)s" eliminado', 'previous 100 rows': '100 filas anteriores', 'record': 'registro', 'record does not exist': 'el registro no existe', 'record id': 'id de registro', 'remove compiled': 'eliminar compiladas', 'restore': 'restaurar', 'revert': 'revertir', 'save': 'guardar', 'selected': 'seleccionado(s)', 'session expired': 'sesión expirada', 'shell': 'shell', 'site': 'sitio', 'some files could not be removed': 'algunos archivos no pudieron ser removidos', 'state': 'estado', 'static': 'estáticos', 'submit': 'enviar', 'table': 'tabla', 'test': 'probar', 'the application logic, each URL path is mapped in one exposed function in the controller': 'la lógica de la aplicación, cada ruta URL se mapea en una función expuesta en el controlador', 'the data representation, define database tables and sets': 'la representación de datos, define tablas y conjuntos de base de datos', 'the presentations layer, views are also known as templates': 'la capa de presentación, las vistas también son llamadas plantillas', 'these files are served without processing, your images go here': 'estos archivos son servidos sin procesar, sus imágenes van aquí', 'to previous version.': 'a la versión previa.', 'translation strings for the application': 'cadenas de caracteres de traducción para la aplicación', 'try': 'intente', 'try something like': 'intente algo como', 'unable to create application "%s"': 'no es posible crear la aplicación "%s"', 'unable to delete file "%(filename)s"': 'no es posible eliminar el archivo "%(filename)s"', 'unable to delete file plugin "%(plugin)s"': 'no es posible eliminar plugin "%(plugin)s"', 'unable to parse csv file': 'no es posible analizar el archivo CSV', 'unable to uninstall "%s"': 'no es posible instalar "%s"', 'unable to upgrade because "%s"': 'no es posible actualizar porque "%s"', 'uncheck all': 'desmarcar todos', 'uninstall': 'desinstalar', 'update': 'actualizar', 'update all languages': 'actualizar todos los lenguajes', 'upgrade web2py now': 'actualize web2py ahora', 'upload application:': 'subir aplicación:', 'upload file:': 'suba archivo:', 'upload plugin file:': 'suba archivo de plugin:', 'variables': 'variables', 'versioning': 'versiones', 'view': 'vista', 'views': 'vistas', 'web2py Recent Tweets': 'Tweets Recientes de web2py', 'web2py is up to date': 'web2py está actualizado', 'web2py upgraded; please restart it': 'web2py actualizado; favor reiniciar', }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" è un\'espressione opzionale come "campo1=\'nuovo valore\'". Non si può fare "update" o "delete" dei risultati di un JOIN ', '%Y-%m-%d': '%d/%m/%Y', '%Y-%m-%d %H:%M:%S': '%d/%m/%Y %H:%M:%S', '%s rows deleted': '%s righe ("record") cancellate', '%s rows updated': '%s righe ("record") modificate', '(requires internet access)': '(requires internet access)', '(something like "it-it")': '(qualcosa simile a "it-it")', 'A new version of web2py is available: %s': 'È disponibile una nuova versione di web2py: %s', 'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.': "ATTENZIONE: L'accesso richiede una connessione sicura (HTTPS) o l'esecuzione di web2py in locale (connessione su localhost)", 'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.': 'ATTENTZIONE: NON ESEGUIRE PIÙ TEST IN PARALLELO (I TEST NON SONO "THREAD SAFE")', 'ATTENTION: you cannot edit the running application!': "ATTENZIONE: non puoi modificare l'applicazione correntemente in uso ", 'About': 'Informazioni', 'About application': "Informazioni sull'applicazione", 'Admin is disabled because insecure channel': 'amministrazione disabilitata: comunicazione non sicura', 'Admin language': 'Admin language', 'Administrator Password:': 'Password Amministratore:', 'Application name:': 'Application name:', 'Are you sure you want to delete file "%s"?': 'Confermi di voler cancellare il file "%s"?', 'Are you sure you want to delete plugin "%s"?': 'Confermi di voler cancellare il plugin "%s"?', 'Are you sure you want to uninstall application "%s"?': 'Confermi di voler disinstallare l\'applicazione "%s"?', 'Are you sure you want to upgrade web2py now?': 'Confermi di voler aggiornare web2py ora?', 'Available databases and tables': 'Database e tabelle disponibili', 'Cannot be empty': 'Non può essere vuoto', 'Cannot compile: there are errors in your app:': "Compilazione fallita: ci sono errori nell'applicazione.", 'Check to delete': 'Seleziona per cancellare', 'Checking for upgrades...': 'Controllo aggiornamenti in corso...', 'Controller': 'Controller', 'Controllers': 'Controllers', 'Copyright': 'Copyright', 'Create new simple application': 'Crea nuova applicazione', 'Current request': 'Richiesta (request) corrente', 'Current response': 'Risposta (response) corrente', 'Current session': 'Sessione (session) corrente', 'DB Model': 'Modello di DB', 'Database': 'Database', 'Date and Time': 'Data and Ora', 'Delete': 'Cancella', 'Delete:': 'Cancella:', 'Deploy on Google App Engine': 'Installa su Google App Engine', 'EDIT': 'MODIFICA', 'Edit': 'Modifica', 'Edit This App': 'Modifica questa applicazione', 'Edit application': 'Modifica applicazione', 'Edit current record': 'Modifica record corrente', 'Editing Language file': 'Modifica file linguaggio', 'Editing file "%s"': 'Modifica del file "%s"', 'Enterprise Web Framework': 'Enterprise Web Framework', 'Error logs for "%(app)s"': 'Log degli errori per "%(app)s"', 'Exception instance attributes': 'Exception instance attributes', 'Functions with no doctests will result in [passed] tests.': 'I test delle funzioni senza "doctests" risulteranno sempre [passed].', 'Hello World': 'Salve Mondo', 'If the report above contains a ticket number it indicates a failure in executing the controller, before any attempt to execute the doctests. This is usually due to an indentation error or an error outside function code.\nA green title indicates that all tests (if defined) passed. In this case test results are not shown.': 'If the report above contains a ticket number it indicates a failure in executing the controller, before any attempt to execute the doctests. This is usually due to an indentation error or an error outside function code.\nA green title indicates that all tests (if defined) passed. In this case test results are not shown.', 'Import/Export': 'Importa/Esporta', 'Index': 'Indice', 'Installed applications': 'Applicazioni installate', 'Internal State': 'Stato interno', 'Invalid Query': 'Richiesta (query) non valida', 'Invalid action': 'Azione non valida', 'Language files (static strings) updated': 'Linguaggi (documenti con stringhe statiche) aggiornati', 'Languages': 'Linguaggi', 'Last saved on:': 'Ultimo salvataggio:', 'Layout': 'Layout', 'License for': 'Licenza relativa a', 'Login': 'Accesso', 'Login to the Administrative Interface': "Accesso all'interfaccia amministrativa", 'Main Menu': 'Menu principale', 'Menu Model': 'Menu Modelli', 'Models': 'Modelli', 'Modules': 'Moduli', 'NO': 'NO', 'New Record': 'Nuovo elemento (record)', 'New application wizard': 'New application wizard', 'New simple application': 'New simple application', 'No databases in this application': 'Nessun database presente in questa applicazione', 'Original/Translation': 'Originale/Traduzione', 'PAM authenticated user, cannot change password here': 'utente autenticato tramite PAM, impossibile modificare password qui', 'Peeking at file': 'Uno sguardo al file', 'Plugin "%s" in application': 'Plugin "%s" nell\'applicazione', 'Plugins': 'I Plugins', 'Powered by': 'Powered by', 'Query:': 'Richiesta (query):', 'Resolve Conflict file': 'File di risoluzione conflitto', 'Rows in table': 'Righe nella tabella', 'Rows selected': 'Righe selezionate', 'Saved file hash:': 'Hash del file salvato:', 'Static files': 'Files statici', 'Stylesheet': 'Foglio di stile (stylesheet)', 'Sure you want to delete this object?': 'Vuoi veramente cancellare questo oggetto?', 'TM': 'TM', 'Testing application': 'Test applicazione in corsg', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'La richiesta (query) è una condizione come ad esempio "db.tabella1.campo1==\'valore\'". Una condizione come "db.tabella1.campo1==db.tabella2.campo2" produce un "JOIN" SQL.', 'There are no controllers': 'Non ci sono controller', 'There are no models': 'Non ci sono modelli', 'There are no modules': 'Non ci sono moduli', 'There are no static files': 'Non ci sono file statici', 'There are no translators, only default language is supported': 'Non ci sono traduzioni, viene solo supportato il linguaggio di base', 'There are no views': 'Non ci sono viste ("view")', 'This is the %(filename)s template': 'Questo è il template %(filename)s', 'Ticket': 'Ticket', 'To create a plugin, name a file/folder plugin_[name]': 'Per creare un plugin, chiamare un file o cartella plugin_[nome]', 'Unable to check for upgrades': 'Impossibile controllare presenza di aggiornamenti', 'Unable to download app because:': 'Impossibile scaricare applicazione perché', 'Unable to download because': 'Impossibile scaricare perché', 'Unable to download because:': 'Unable to download because:', 'Update:': 'Aggiorna:', 'Upload & install packed application': 'Carica ed installa pacchetto con applicazione', 'Upload a package:': 'Upload a package:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Per costruire richieste (query) più complesse si usano (...)&(...) come "e" (AND), (...)|(...) come "o" (OR), e ~(...) come negazione (NOT).', 'Use an url:': 'Use an url:', 'Version': 'Versione', 'View': 'Vista', 'Views': 'viste', 'Welcome %s': 'Benvenuto %s', 'Welcome to web2py': 'Benvenuto su web2py', 'YES': 'SI', 'about': 'informazioni', 'additional code for your application': 'righe di codice aggiuntive per la tua applicazione', 'admin disabled because no admin password': 'amministrazione disabilitata per mancanza di password amministrativa', 'admin disabled because not supported on google app engine': 'amministrazione non supportata da Google Apps Engine', 'admin disabled because unable to access password file': 'amministrazione disabilitata per impossibilità di leggere il file delle password', 'administrative interface': 'administrative interface', 'and rename it (required):': 'e rinominala (obbligatorio):', 'and rename it:': 'e rinominala:', 'appadmin': 'appadmin ', 'appadmin is disabled because insecure channel': 'amministrazione app (appadmin) disabilitata: comunicazione non sicura', 'application "%s" uninstalled': 'applicazione "%s" disinstallata', 'application compiled': 'applicazione compilata', 'application is compiled and cannot be designed': "l'applicazione è compilata e non si può modificare", 'arguments': 'arguments', 'back': 'indietro', 'cache': 'cache', 'cache, errors and sessions cleaned': 'pulitura cache, errori and sessioni ', 'cannot create file': 'impossibile creare il file', 'cannot upload file "%(filename)s"': 'impossibile caricare il file "%(filename)s"', 'change admin password': 'change admin password', 'change password': 'cambia password', 'check all': 'controlla tutto', 'check for upgrades': 'check for upgrades', 'clean': 'pulisci', 'click here for online examples': 'clicca per vedere gli esempi', 'click here for the administrative interface': "clicca per l'interfaccia amministrativa", 'click to check for upgrades': 'clicca per controllare presenza di aggiornamenti', 'code': 'code', 'compile': 'compila', 'compiled application removed': "rimosso il codice compilato dell'applicazione", 'controllers': 'controllers', 'create': 'crea', 'create file with filename:': 'crea un file col nome:', 'create new application:': 'create new application:', 'created by': 'creato da', 'crontab': 'crontab', 'currently running': 'currently running', 'currently saved or': 'attualmente salvato o', 'customize me!': 'Personalizzami!', 'data uploaded': 'dati caricati', 'database': 'database', 'database %s select': 'database %s select', 'database administration': 'amministrazione database', 'db': 'db', 'defines tables': 'defininisce le tabelle', 'delete': 'Cancella', 'delete all checked': 'cancella tutti i selezionati', 'delete plugin': 'cancella plugin', 'deploy': 'deploy', 'design': 'progetta', 'direction: ltr': 'direction: ltr', 'done!': 'fatto!', 'edit': 'modifica', 'edit controller': 'modifica controller', 'edit profile': 'modifica profilo', 'edit views:': 'modifica viste (view):', 'errors': 'errori', 'export as csv file': 'esporta come file CSV', 'exposes': 'espone', 'extends': 'estende', 'failed to reload module because:': 'ricaricamento modulo fallito perché:', 'file "%(filename)s" created': 'creato il file "%(filename)s"', 'file "%(filename)s" deleted': 'cancellato il file "%(filename)s"', 'file "%(filename)s" uploaded': 'caricato il file "%(filename)s"', 'file "%s" of %s restored': 'ripristinato "%(filename)s"', 'file changed on disk': 'il file ha subito una modifica su disco', 'file does not exist': 'file inesistente', 'file saved on %(time)s': "file salvato nell'istante %(time)s", 'file saved on %s': 'file salvato: %s', 'help': 'aiuto', 'htmledit': 'modifica come html', 'includes': 'include', 'insert new': 'inserisci nuovo', 'insert new %s': 'inserisci nuovo %s', 'install': 'installa', 'internal error': 'errore interno', 'invalid password': 'password non valida', 'invalid request': 'richiesta non valida', 'invalid ticket': 'ticket non valido', 'language file "%(filename)s" created/updated': 'file linguaggio "%(filename)s" creato/aggiornato', 'languages': 'linguaggi', 'loading...': 'caricamento...', 'login': 'accesso', 'logout': 'uscita', 'merge': 'unisci', 'models': 'modelli', 'modules': 'moduli', 'new application "%s" created': 'creata la nuova applicazione "%s"', 'new plugin installed': 'installato nuovo plugin', 'new record inserted': 'nuovo record inserito', 'next 100 rows': 'prossime 100 righe', 'no match': 'nessuna corrispondenza', 'or import from csv file': 'oppure importa da file CSV', 'or provide app url:': "oppure fornisci url dell'applicazione:", 'overwrite installed app': 'sovrascrivi applicazione installata', 'pack all': 'crea pacchetto', 'pack compiled': 'crea pacchetto del codice compilato', 'pack plugin': 'crea pacchetto del plugin', 'password changed': 'password modificata', 'plugin "%(plugin)s" deleted': 'plugin "%(plugin)s" cancellato', 'previous 100 rows': '100 righe precedenti', 'record': 'record', 'record does not exist': 'il record non esiste', 'record id': 'ID del record', 'register': 'registrazione', 'remove compiled': 'rimozione codice compilato', 'restore': 'ripristino', 'revert': 'versione precedente', 'selected': 'selezionato', 'session expired': 'sessions scaduta', 'shell': 'shell', 'site': 'sito', 'some files could not be removed': 'non è stato possibile rimuovere alcuni files', 'start wizard': 'start wizard', 'state': 'stato', 'static': 'statico', 'submit': 'invia', 'table': 'tabella', 'test': 'test', 'the application logic, each URL path is mapped in one exposed function in the controller': 'logica dell\'applicazione, ogni percorso "URL" corrisponde ad una funzione esposta da un controller', 'the data representation, define database tables and sets': 'rappresentazione dei dati, definizione di tabelle di database e di "set" ', 'the presentations layer, views are also known as templates': 'Presentazione dell\'applicazione, viste (views, chiamate anche "templates")', 'these files are served without processing, your images go here': 'questi files vengono serviti così come sono, le immagini vanno qui', 'to previous version.': 'torna a versione precedente', 'translation strings for the application': "stringhe di traduzioni per l'applicazione", 'try': 'prova', 'try something like': 'prova qualcosa come', 'unable to create application "%s"': 'impossibile creare applicazione "%s"', 'unable to delete file "%(filename)s"': 'impossibile rimuovere file "%(plugin)s"', 'unable to delete file plugin "%(plugin)s"': 'impossibile rimuovere file di plugin "%(plugin)s"', 'unable to parse csv file': 'non riesco a decodificare questo file CSV', 'unable to uninstall "%s"': 'impossibile disinstallare "%s"', 'unable to upgrade because "%s"': 'impossibile aggiornare perché "%s"', 'uncheck all': 'smarca tutti', 'uninstall': 'disinstalla', 'update': 'aggiorna', 'update all languages': 'aggiorna tutti i linguaggi', 'upgrade web2py now': 'upgrade web2py now', 'upload application:': 'carica applicazione:', 'upload file:': 'carica file:', 'upload plugin file:': 'carica file di plugin:', 'variables': 'variables', 'versioning': 'sistema di versioni', 'view': 'vista', 'views': 'viste', 'web2py Recent Tweets': 'Tweets recenti per web2py', 'web2py is up to date': 'web2py è aggiornato', 'web2py upgraded; please restart it': 'web2py aggiornato; prego riavviarlo', }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s rows deleted': '%s записите бяха изтрити', '%s rows updated': '%s записите бяха обновени', '(requires internet access)': '(requires internet access)', '(something like "it-it")': '(something like "it-it")', 'A new version of web2py is available': 'A new version of web2py is available', 'A new version of web2py is available: %s': 'A new version of web2py is available: %s', 'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.': 'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.', 'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.': 'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.', 'ATTENTION: you cannot edit the running application!': 'ATTENTION: you cannot edit the running application!', 'About': 'About', 'About application': 'About application', 'Additional code for your application': 'Additional code for your application', 'Admin is disabled because insecure channel': 'Admin is disabled because insecure channel', 'Admin is disabled because unsecure channel': 'Admin is disabled because unsecure channel', 'Admin language': 'Admin language', 'Administrator Password:': 'Administrator Password:', 'Application name:': 'Application name:', 'Are you sure you want to delete file "%s"?': 'Are you sure you want to delete file "%s"?', 'Are you sure you want to delete plugin "%s"?': 'Are you sure you want to delete plugin "%s"?', 'Are you sure you want to uninstall application "%s"': 'Are you sure you want to uninstall application "%s"', 'Are you sure you want to uninstall application "%s"?': 'Are you sure you want to uninstall application "%s"?', 'Are you sure you want to upgrade web2py now?': 'Are you sure you want to upgrade web2py now?', 'Available databases and tables': 'Available databases and tables', 'Cannot be empty': 'Cannot be empty', 'Cannot compile: there are errors in your app. Debug it, correct errors and try again.': 'Cannot compile: there are errors in your app. Debug it, correct errors and try again.', 'Cannot compile: there are errors in your app:': 'Cannot compile: there are errors in your app:', 'Check to delete': 'Check to delete', 'Checking for upgrades...': 'Checking for upgrades...', 'Controllers': 'Controllers', 'Create new simple application': 'Create new simple application', 'Current request': 'Current request', 'Current response': 'Current response', 'Current session': 'Current session', 'DESIGN': 'DESIGN', 'Date and Time': 'Date and Time', 'Delete': 'Delete', 'Delete:': 'Delete:', 'Deploy on Google App Engine': 'Deploy on Google App Engine', 'Design for': 'Design for', 'EDIT': 'EDIT', 'Edit application': 'Edit application', 'Edit current record': 'Edit current record', 'Editing Language file': 'Editing Language file', 'Editing file': 'Editing file', 'Editing file "%s"': 'Editing file "%s"', 'Enterprise Web Framework': 'Enterprise Web Framework', 'Error logs for "%(app)s"': 'Error logs for "%(app)s"', 'Exception instance attributes': 'Exception instance attributes', 'Functions with no doctests will result in [passed] tests.': 'Functions with no doctests will result in [passed] tests.', 'Hello World': 'Здравей, свят', 'If the report above contains a ticket number it indicates a failure in executing the controller, before any attempt to execute the doctests. This is usually due to an indentation error or an error outside function code.\nA green title indicates that all tests (if defined) passed. In this case test results are not shown.': 'If the report above contains a ticket number it indicates a failure in executing the controller, before any attempt to execute the doctests. This is usually due to an indentation error or an error outside function code.\nA green title indicates that all tests (if defined) passed. In this case test results are not shown.', 'Import/Export': 'Import/Export', 'Installed applications': 'Installed applications', 'Internal State': 'Internal State', 'Invalid Query': 'Невалидна заявка', 'Invalid action': 'Invalid action', 'Language files (static strings) updated': 'Language files (static strings) updated', 'Languages': 'Languages', 'Last saved on:': 'Last saved on:', 'License for': 'License for', 'Login': 'Login', 'Login to the Administrative Interface': 'Login to the Administrative Interface', 'Models': 'Models', 'Modules': 'Modules', 'NO': 'NO', 'New Record': 'New Record', 'New application wizard': 'New application wizard', 'New simple application': 'New simple application', 'No databases in this application': 'No databases in this application', 'Original/Translation': 'Original/Translation', 'PAM authenticated user, cannot change password here': 'PAM authenticated user, cannot change password here', 'Peeking at file': 'Peeking at file', 'Plugin "%s" in application': 'Plugin "%s" in application', 'Plugins': 'Plugins', 'Powered by': 'Powered by', 'Query:': 'Query:', 'Resolve Conflict file': 'Resolve Conflict file', 'Rows in table': 'Rows in table', 'Rows selected': 'Rows selected', 'Saved file hash:': 'Saved file hash:', 'Searching:': 'Searching:', 'Static files': 'Static files', 'Sure you want to delete this object?': 'Сигурен ли си, че искаш да изтриеш този обект?', 'TM': 'TM', 'Testing application': 'Testing application', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.', 'The application logic, each URL path is mapped in one exposed function in the controller': 'The application logic, each URL path is mapped in one exposed function in the controller', 'The data representation, define database tables and sets': 'The data representation, define database tables and sets', 'The presentations layer, views are also known as templates': 'The presentations layer, views are also known as templates', 'There are no controllers': 'There are no controllers', 'There are no models': 'There are no models', 'There are no modules': 'There are no modules', 'There are no plugins': 'There are no plugins', 'There are no static files': 'There are no static files', 'There are no translators, only default language is supported': 'There are no translators, only default language is supported', 'There are no views': 'There are no views', 'These files are served without processing, your images go here': 'These files are served without processing, your images go here', 'This is the %(filename)s template': 'This is the %(filename)s template', 'Ticket': 'Ticket', 'To create a plugin, name a file/folder plugin_[name]': 'To create a plugin, name a file/folder plugin_[name]', 'Translation strings for the application': 'Translation strings for the application', 'Unable to check for upgrades': 'Unable to check for upgrades', 'Unable to download': 'Unable to download', 'Unable to download app because:': 'Unable to download app because:', 'Unable to download because': 'Unable to download because', 'Update:': 'Update:', 'Upload & install packed application': 'Upload & install packed application', 'Upload a package:': 'Upload a package:', 'Upload existing application': 'Upload existing application', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.', 'Use an url:': 'Use an url:', 'Version': 'Version', 'Views': 'Views', 'Welcome to web2py': 'Добре дошъл в web2py', 'YES': 'YES', 'about': 'about', 'additional code for your application': 'additional code for your application', 'admin disabled because no admin password': 'admin disabled because no admin password', 'admin disabled because not supported on google app engine': 'admin disabled because not supported on google apps engine', 'admin disabled because unable to access password file': 'admin disabled because unable to access password file', 'administrative interface': 'administrative interface', 'and rename it (required):': 'and rename it (required):', 'and rename it:': 'and rename it:', 'appadmin': 'appadmin', 'appadmin is disabled because insecure channel': 'appadmin is disabled because insecure channel', 'application "%s" uninstalled': 'application "%s" uninstalled', 'application compiled': 'application compiled', 'application is compiled and cannot be designed': 'application is compiled and cannot be designed', 'arguments': 'arguments', 'back': 'back', 'cache': 'cache', 'cache, errors and sessions cleaned': 'cache, errors and sessions cleaned', 'cannot create file': 'cannot create file', 'cannot upload file "%(filename)s"': 'cannot upload file "%(filename)s"', 'change admin password': 'change admin password', 'check all': 'check all', 'check for upgrades': 'check for upgrades', 'clean': 'clean', 'click here for online examples': 'щракни тук за онлайн примери', 'click here for the administrative interface': 'щракни тук за административния интерфейс', 'click to check for upgrades': 'click to check for upgrades', 'code': 'code', 'collapse/expand all': 'collapse/expand all', 'compile': 'compile', 'compiled application removed': 'compiled application removed', 'controllers': 'controllers', 'create': 'create', 'create file with filename:': 'create file with filename:', 'create new application:': 'create new application:', 'created by': 'created by', 'crontab': 'crontab', 'currently running': 'currently running', 'currently saved or': 'currently saved or', 'data uploaded': 'данните бяха качени', 'database': 'database', 'database %s select': 'database %s select', 'database administration': 'database administration', 'db': 'дб', 'defines tables': 'defines tables', 'delete': 'delete', 'delete all checked': 'delete all checked', 'delete plugin': 'delete plugin', 'deploy': 'deploy', 'design': 'дизайн', 'direction: ltr': 'direction: ltr', 'done!': 'готово!', 'download layouts': 'download layouts', 'download plugins': 'download plugins', 'edit': 'edit', 'edit controller': 'edit controller', 'edit views:': 'edit views:', 'errors': 'errors', 'export as csv file': 'export as csv file', 'exposes': 'exposes', 'extends': 'extends', 'failed to reload module': 'failed to reload module', 'failed to reload module because:': 'failed to reload module because:', 'file "%(filename)s" created': 'file "%(filename)s" created', 'file "%(filename)s" deleted': 'file "%(filename)s" deleted', 'file "%(filename)s" uploaded': 'file "%(filename)s" uploaded', 'file "%(filename)s" was not deleted': 'file "%(filename)s" was not deleted', 'file "%s" of %s restored': 'file "%s" of %s restored', 'file changed on disk': 'file changed on disk', 'file does not exist': 'file does not exist', 'file saved on %(time)s': 'file saved on %(time)s', 'file saved on %s': 'file saved on %s', 'files': 'files', 'filter': 'filter', 'help': 'help', 'htmledit': 'htmledit', 'includes': 'includes', 'insert new': 'insert new', 'insert new %s': 'insert new %s', 'install': 'install', 'internal error': 'internal error', 'invalid password': 'invalid password', 'invalid request': 'невалидна заявка', 'invalid ticket': 'invalid ticket', 'language file "%(filename)s" created/updated': 'language file "%(filename)s" created/updated', 'languages': 'languages', 'languages updated': 'languages updated', 'loading...': 'loading...', 'login': 'login', 'logout': 'logout', 'merge': 'merge', 'models': 'models', 'modules': 'modules', 'new application "%s" created': 'new application "%s" created', 'new plugin installed': 'new plugin installed', 'new record inserted': 'новият запис беше добавен', 'next 100 rows': 'next 100 rows', 'no match': 'no match', 'or import from csv file': 'or import from csv file', 'or provide app url:': 'or provide app url:', 'or provide application url:': 'or provide application url:', 'overwrite installed app': 'overwrite installed app', 'pack all': 'pack all', 'pack compiled': 'pack compiled', 'pack plugin': 'pack plugin', 'password changed': 'password changed', 'plugin "%(plugin)s" deleted': 'plugin "%(plugin)s" deleted', 'plugins': 'plugins', 'previous 100 rows': 'previous 100 rows', 'record': 'record', 'record does not exist': 'записът не съществува', 'record id': 'record id', 'remove compiled': 'remove compiled', 'restore': 'restore', 'revert': 'revert', 'save': 'save', 'selected': 'selected', 'session expired': 'session expired', 'shell': 'shell', 'site': 'site', 'some files could not be removed': 'some files could not be removed', 'start wizard': 'start wizard', 'state': 'състояние', 'static': 'static', 'submit': 'submit', 'table': 'table', 'test': 'test', 'the application logic, each URL path is mapped in one exposed function in the controller': 'the application logic, each URL path is mapped in one exposed function in the controller', 'the data representation, define database tables and sets': 'the data representation, define database tables and sets', 'the presentations layer, views are also known as templates': 'the presentations layer, views are also known as templates', 'these files are served without processing, your images go here': 'these files are served without processing, your images go here', 'to previous version.': 'to previous version.', 'translation strings for the application': 'translation strings for the application', 'try': 'try', 'try something like': 'try something like', 'unable to create application "%s"': 'unable to create application "%s"', 'unable to delete file "%(filename)s"': 'unable to delete file "%(filename)s"', 'unable to delete file plugin "%(plugin)s"': 'unable to delete file plugin "%(plugin)s"', 'unable to parse csv file': 'не е възможна обработката на csv файла', 'unable to uninstall "%s"': 'unable to uninstall "%s"', 'unable to upgrade because "%s"': 'unable to upgrade because "%s"', 'uncheck all': 'uncheck all', 'uninstall': 'uninstall', 'update': 'update', 'update all languages': 'update all languages', 'upgrade web2py now': 'upgrade web2py now', 'upload': 'upload', 'upload application:': 'upload application:', 'upload file:': 'upload file:', 'upload plugin file:': 'upload plugin file:', 'variables': 'variables', 'versioning': 'versioning', 'view': 'view', 'views': 'views', 'web2py Recent Tweets': 'web2py Recent Tweets', 'web2py is up to date': 'web2py is up to date', 'web2py upgraded; please restart it': 'web2py upgraded; please restart it', }
Python
# coding: utf8 { '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '(requires internet access)': '(vereis internet toegang)', '(something like "it-it")': '(iets soos "it-it")', 'About': 'Oor', 'About application': 'Oor program', 'Additional code for your application': 'Additionele kode vir u application', 'Admin language': 'Admin taal', 'Application name:': 'Program naam:', 'Controllers': 'Beheerders', 'Deploy on Google App Engine': 'Stuur na Google App Engine toe', 'Edit application': 'Wysig program', 'Installed applications': 'Geinstalleerde apps', 'Languages': 'Tale', 'License for': 'Lisensie vir', 'Models': 'Modelle', 'Modules': 'Modules', 'New application wizard': 'Nuwe app wizard', 'New simple application': 'Nuwe eenvoudige app', 'Plugins': 'Plugins', 'Powered by': 'Aangedryf deur', 'Searching:': 'Soek:', 'Static files': 'Static files', 'Sure you want to delete this object?': 'Is jy seker jy will hierde object verwyder?', 'The application logic, each URL path is mapped in one exposed function in the controller': 'The application logic, each URL path is mapped in one exposed function in the controller', 'The data representation, define database tables and sets': 'The data representation, define database tables and sets', 'The presentations layer, views are also known as templates': 'The presentations layer, views are also known as templates', 'There are no plugins': 'Daar is geen plugins', 'These files are served without processing, your images go here': 'Hierdie lêre is sonder veranderinge geserved, jou images gaan hier', 'To create a plugin, name a file/folder plugin_[name]': 'Om ''n plugin te skep, noem ''n lêer/gids plugin_[name]', 'Translation strings for the application': 'Vertaling woorde vir die program', 'Upload & install packed application': 'Oplaai & install gepakte program', 'Upload a package:': 'Oplaai ''n package:', 'Use an url:': 'Gebruik n url:', 'Views': 'Views', 'about': 'oor', 'administrative interface': 'administrative interface', 'and rename it:': 'en verander die naam:', 'change admin password': 'verander admin wagwoord', 'check for upgrades': 'soek vir upgrades', 'clean': 'maak skoon', 'collapse/expand all': 'collapse/expand all', 'compile': 'kompileer', 'controllers': 'beheerders', 'create': 'skep', 'create file with filename:': 'skep lêer met naam:', 'created by': 'geskep deur', 'crontab': 'crontab', 'currently running': 'loop tans', 'database administration': 'database administration', 'deploy': 'deploy', 'direction: ltr': 'direction: ltr', 'download layouts': 'aflaai layouts', 'download plugins': 'aflaai plugins', 'edit': 'wysig', 'errors': 'foute', 'exposes': 'exposes', 'extends': 'extends', 'files': 'lêre', 'filter': 'filter', 'help': 'hulp', 'includes': 'includes', 'install': 'installeer', 'languages': 'tale', 'loading...': 'laai...', 'logout': 'logout', 'models': 'modelle', 'modules': 'modules', 'overwrite installed app': 'skryf oor geinstalleerde program', 'pack all': 'pack alles', 'plugins': 'plugins', 'shell': 'shell', 'site': 'site', 'start wizard': 'start wizard', 'static': 'static', 'test': 'toets', 'uninstall': 'verwyder', 'update all languages': 'update all languages', 'upload': 'oplaai', 'upload file:': 'oplaai lêer:', 'upload plugin file:': 'upload plugin lêer:', 'versioning': 'versioning', 'views': 'views', 'web2py Recent Tweets': 'web2py Onlangse Tweets', }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"Uaktualnij" jest dodatkowym wyrażeniem postaci "pole1=\'nowawartość\'". Nie możesz uaktualnić lub usunąć wyników z JOIN:', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s rows deleted': 'Wierszy usuniętych: %s', '%s rows updated': 'Wierszy uaktualnionych: %s', '(requires internet access)': '(requires internet access)', '(something like "it-it")': '(coś podobnego do "it-it")', 'A new version of web2py is available': 'Nowa wersja web2py jest dostępna', 'A new version of web2py is available: %s': 'Nowa wersja web2py jest dostępna: %s', 'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.': 'UWAGA: Wymagane jest bezpieczne (HTTPS) połączenie lub połączenie z lokalnego adresu.', 'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.': 'UWAGA: TESTOWANIE NIE JEST BEZPIECZNE W ŚRODOWISKU WIELOWĄTKOWYM, TAK WIĘC NIE URUCHAMIAJ WIELU TESTÓW JEDNOCZEŚNIE.', 'ATTENTION: you cannot edit the running application!': 'UWAGA: nie można edytować uruchomionych aplikacji!', 'About': 'Informacje o', 'About application': 'Informacje o aplikacji', 'Additional code for your application': 'Additional code for your application', 'Admin is disabled because insecure channel': 'Panel administracyjny wyłączony z powodu braku bezpiecznego połączenia', 'Admin is disabled because unsecure channel': 'Panel administracyjny wyłączony z powodu braku bezpiecznego połączenia', 'Administrator Password:': 'Hasło administratora:', 'Application name:': 'Application name:', 'Are you sure you want to delete file "%s"?': 'Czy na pewno chcesz usunąć plik "%s"?', 'Are you sure you want to delete plugin "%s"?': 'Czy na pewno chcesz usunąć wtyczkę "%s"?', 'Are you sure you want to uninstall application "%s"': 'Czy na pewno chcesz usunąć aplikację "%s"', 'Are you sure you want to uninstall application "%s"?': 'Czy na pewno chcesz usunąć aplikację "%s"?', 'Are you sure you want to upgrade web2py now?': 'Are you sure you want to upgrade web2py now?', 'Available databases and tables': 'Dostępne bazy danych i tabele', 'Cannot be empty': 'Nie może być puste', 'Cannot compile: there are errors in your app. Debug it, correct errors and try again.': 'Nie można skompilować: w Twojej aplikacji są błędy . Znajdź je, popraw a następnie spróbój ponownie.', 'Cannot compile: there are errors in your app:': 'Cannot compile: there are errors in your app:', 'Check to delete': 'Zaznacz aby usunąć', 'Checking for upgrades...': 'Sprawdzanie aktualizacji...', 'Controllers': 'Kontrolery', 'Create new simple application': 'Utwórz nową aplikację', 'Current request': 'Aktualne żądanie', 'Current response': 'Aktualna odpowiedź', 'Current session': 'Aktualna sesja', 'DESIGN': 'PROJEKTUJ', 'Date and Time': 'Data i godzina', 'Delete': 'Usuń', 'Delete:': 'Usuń:', 'Deploy on Google App Engine': 'Umieść na Google App Engine', 'Design for': 'Projekt dla', 'EDIT': 'EDYTUJ', 'Edit application': 'Edycja aplikacji', 'Edit current record': 'Edytuj aktualny rekord', 'Editing Language file': 'Edytuj plik tłumaczeń', 'Editing file': 'Edycja pliku', 'Editing file "%s"': 'Edycja pliku "%s"', 'Enterprise Web Framework': 'Enterprise Web Framework', 'Error logs for "%(app)s"': 'Wpisy błędów dla "%(app)s"', 'Exception instance attributes': 'Exception instance attributes', 'Functions with no doctests will result in [passed] tests.': 'Funkcje bez doctestów będą dołączone do [zaliczonych] testów.', 'Hello World': 'Witaj Świecie', 'If the report above contains a ticket number it indicates a failure in executing the controller, before any attempt to execute the doctests. This is usually due to an indentation error or an error outside function code.\nA green title indicates that all tests (if defined) passed. In this case test results are not shown.': 'Jeżeli powyższy raport zawiera numer biletu błędu, oznacza to błąd podczas wykonywania kontrolera przez próbą uruchomienia doctestów. Zazwyczaj jest to spowodowane nieprawidłowymi wcięciami linii kodu lub błędami w module poza ciałem funkcji.\nTytuł w kolorze zielonym oznacza, ze wszystkie (zdefiniowane) testy zakończyły się sukcesem. W tej sytuacji ich wyniki nie są pokazane.', 'Import/Export': 'Importuj/eksportuj', 'Installed applications': 'Zainstalowane aplikacje', 'Internal State': 'Stan wewnętrzny', 'Invalid Query': 'Błędne zapytanie', 'Invalid action': 'Błędna akcja', 'Language files (static strings) updated': 'Pliki tłumaczeń (ciągi statyczne) zostały uaktualnione', 'Languages': 'Tłumaczenia', 'Last saved on:': 'Ostatnio zapisany:', 'License for': 'Licencja dla', 'Login': 'Zaloguj', 'Login to the Administrative Interface': 'Logowanie do panelu administracyjnego', 'Models': 'Modele', 'Modules': 'Moduły', 'NO': 'NIE', 'New Record': 'Nowy rekord', 'New application wizard': 'New application wizard', 'New simple application': 'New simple application', 'No databases in this application': 'Brak baz danych w tej aplikacji', 'Original/Translation': 'Oryginał/tłumaczenie', 'PAM authenticated user, cannot change password here': 'PAM authenticated user, cannot change password here', 'Peeking at file': 'Podgląd pliku', 'Plugin "%s" in application': 'Wtyczka "%s" w aplikacji', 'Plugins': 'Wtyczki', 'Powered by': 'Zasilane przez', 'Query:': 'Zapytanie:', 'Resolve Conflict file': 'Rozwiąż konflikt plików', 'Rows in table': 'Wiersze w tabeli', 'Rows selected': 'Wierszy wybranych', 'Saved file hash:': 'Suma kontrolna zapisanego pliku:', 'Searching:': 'Searching:', 'Static files': 'Pliki statyczne', 'Sure you want to delete this object?': 'Czy na pewno chcesz usunąć ten obiekt?', 'TM': 'TM', 'Testing application': 'Testowanie aplikacji', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': '"Zapytanie" jest warunkiem postaci "db.tabela1.pole1==\'wartość\'". Takie coś jak "db.tabela1.pole1==db.tabela2.pole2" oznacza SQL JOIN.', 'The application logic, each URL path is mapped in one exposed function in the controller': 'The application logic, each URL path is mapped in one exposed function in the controller', 'The data representation, define database tables and sets': 'The data representation, define database tables and sets', 'The presentations layer, views are also known as templates': 'The presentations layer, views are also known as templates', 'There are no controllers': 'Brak kontrolerów', 'There are no models': 'Brak modeli', 'There are no modules': 'Brak modułów', 'There are no plugins': 'There are no plugins', 'There are no static files': 'Brak plików statycznych', 'There are no translators, only default language is supported': 'Brak plików tłumaczeń, wspierany jest tylko domyślny język', 'There are no views': 'Brak widoków', 'These files are served without processing, your images go here': 'These files are served without processing, your images go here', 'This is the %(filename)s template': 'To jest szablon %(filename)s', 'Ticket': 'Bilet', 'To create a plugin, name a file/folder plugin_[name]': 'Aby utworzyć wtyczkę, nazwij plik/katalog plugin_[nazwa]', 'Translation strings for the application': 'Translation strings for the application', 'Unable to check for upgrades': 'Nie można sprawdzić aktualizacji', 'Unable to download': 'Nie można ściągnąć', 'Unable to download app': 'Nie można ściągnąć aplikacji', 'Unable to download app because:': 'Unable to download app because:', 'Unable to download because': 'Unable to download because', 'Update:': 'Uaktualnij:', 'Upload & install packed application': 'Upload & install packed application', 'Upload a package:': 'Upload a package:', 'Upload existing application': 'Wyślij istniejącą aplikację', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Użyj (...)&(...) jako AND, (...)|(...) jako OR oraz ~(...) jako NOT do tworzenia bardziej skomplikowanych zapytań.', 'Use an url:': 'Use an url:', 'Version': 'Wersja', 'Views': 'Widoki', 'Welcome to web2py': 'Witaj w web2py', 'YES': 'TAK', 'about': 'informacje', 'additional code for your application': 'dodatkowy kod Twojej aplikacji', 'admin disabled because no admin password': 'panel administracyjny wyłączony z powodu braku hasła administracyjnego', 'admin disabled because not supported on google app engine': 'panel administracyjny wyłączony z powodu braku wsparcia na google apps engine', 'admin disabled because unable to access password file': 'panel administracyjny wyłączony z powodu braku dostępu do pliku z hasłem', 'administrative interface': 'administrative interface', 'and rename it (required):': 'i nadaj jej nową nazwę (wymagane):', 'and rename it:': 'i nadaj mu nową nazwę:', 'appadmin': 'administracja aplikacji', 'appadmin is disabled because insecure channel': 'administracja aplikacji wyłączona z powodu braku bezpiecznego połączenia', 'application "%s" uninstalled': 'aplikacja "%s" została odinstalowana', 'application compiled': 'aplikacja została skompilowana', 'application is compiled and cannot be designed': 'aplikacja jest skompilowana i nie może być projektowana', 'arguments': 'arguments', 'back': 'wstecz', 'cache': 'cache', 'cache, errors and sessions cleaned': 'pamięć podręczna, bilety błędów oraz pliki sesji zostały wyczyszczone', 'cannot create file': 'nie można utworzyć pliku', 'cannot upload file "%(filename)s"': 'nie można wysłać pliku "%(filename)s"', 'change admin password': 'change admin password', 'check all': 'zaznacz wszystko', 'check for upgrades': 'check for upgrades', 'clean': 'oczyść', 'click here for online examples': 'kliknij aby przejść do interaktywnych przykładów', 'click here for the administrative interface': 'kliknij aby przejść do panelu administracyjnego', 'click to check for upgrades': 'kliknij aby sprawdzić aktualizacje', 'code': 'code', 'collapse/expand all': 'collapse/expand all', 'compile': 'skompiluj', 'compiled application removed': 'skompilowana aplikacja została usunięta', 'controllers': 'kontrolery', 'create': 'create', 'create file with filename:': 'utwórz plik o nazwie:', 'create new application:': 'utwórz nową aplikację:', 'created by': 'utworzone przez', 'crontab': 'crontab', 'currently running': 'currently running', 'currently saved or': 'aktualnie zapisany lub', 'data uploaded': 'dane wysłane', 'database': 'baza danych', 'database %s select': 'wybór z bazy danych %s', 'database administration': 'administracja bazy danych', 'db': 'baza danych', 'defines tables': 'zdefiniuj tabele', 'delete': 'usuń', 'delete all checked': 'usuń wszystkie zaznaczone', 'delete plugin': 'usuń wtyczkę', 'deploy': 'deploy', 'design': 'projektuj', 'direction: ltr': 'direction: ltr', 'done!': 'zrobione!', 'download layouts': 'download layouts', 'download plugins': 'download plugins', 'edit': 'edytuj', 'edit controller': 'edytuj kontroler', 'edit views:': 'edit views:', 'errors': 'błędy', 'export as csv file': 'eksportuj jako plik csv', 'exposes': 'eksponuje', 'extends': 'rozszerza', 'failed to reload module': 'nie udało się przeładować modułu', 'failed to reload module because:': 'failed to reload module because:', 'file "%(filename)s" created': 'plik "%(filename)s" został utworzony', 'file "%(filename)s" deleted': 'plik "%(filename)s" został usunięty', 'file "%(filename)s" uploaded': 'plik "%(filename)s" został wysłany', 'file "%(filename)s" was not deleted': 'plik "%(filename)s" nie został usunięty', 'file "%s" of %s restored': 'plik "%s" z %s został odtworzony', 'file changed on disk': 'plik na dysku został zmieniony', 'file does not exist': 'plik nie istnieje', 'file saved on %(time)s': 'plik zapisany o %(time)s', 'file saved on %s': 'plik zapisany o %s', 'files': 'files', 'filter': 'filter', 'help': 'pomoc', 'htmledit': 'edytuj HTML', 'includes': 'zawiera', 'insert new': 'wstaw nowy rekord tabeli', 'insert new %s': 'wstaw nowy rekord do tabeli %s', 'install': 'install', 'internal error': 'wewnętrzny błąd', 'invalid password': 'błędne hasło', 'invalid request': 'błędne zapytanie', 'invalid ticket': 'błędny bilet', 'language file "%(filename)s" created/updated': 'plik tłumaczeń "%(filename)s" został utworzony/uaktualniony', 'languages': 'pliki tłumaczeń', 'languages updated': 'pliki tłumaczeń zostały uaktualnione', 'loading...': 'wczytywanie...', 'login': 'zaloguj', 'logout': 'wyloguj', 'merge': 'zespól', 'models': 'modele', 'modules': 'moduły', 'new application "%s" created': 'nowa aplikacja "%s" została utworzona', 'new plugin installed': 'nowa wtyczka została zainstalowana', 'new record inserted': 'nowy rekord został wstawiony', 'next 100 rows': 'następne 100 wierszy', 'no match': 'no match', 'or import from csv file': 'lub zaimportuj z pliku csv', 'or provide app url:': 'or provide app url:', 'or provide application url:': 'lub podaj url aplikacji:', 'overwrite installed app': 'overwrite installed app', 'pack all': 'spakuj wszystko', 'pack compiled': 'spakuj skompilowane', 'pack plugin': 'spakuj wtyczkę', 'password changed': 'password changed', 'plugin "%(plugin)s" deleted': 'wtyczka "%(plugin)s" została usunięta', 'plugins': 'plugins', 'previous 100 rows': 'poprzednie 100 wierszy', 'record': 'rekord', 'record does not exist': 'rekord nie istnieje', 'record id': 'ID rekordu', 'remove compiled': 'usuń skompilowane', 'restore': 'odtwórz', 'revert': 'przywróć', 'save': 'zapisz', 'selected': 'zaznaczone', 'session expired': 'sesja wygasła', 'shell': 'powłoka', 'site': 'strona główna', 'some files could not be removed': 'niektóre pliki nie mogły zostać usunięte', 'start wizard': 'start wizard', 'state': 'stan', 'static': 'pliki statyczne', 'submit': 'wyślij', 'table': 'tabela', 'test': 'testuj', 'the application logic, each URL path is mapped in one exposed function in the controller': 'logika aplikacji, każda ścieżka URL jest mapowana na jedną z funkcji eksponowanych w kontrolerze', 'the data representation, define database tables and sets': 'reprezentacja danych, definicje zbiorów i tabel bazy danych', 'the presentations layer, views are also known as templates': 'warstwa prezentacji, widoki zwane są również szablonami', 'these files are served without processing, your images go here': 'pliki obsługiwane bez interpretacji, to jest miejsce na Twoje obrazy', 'to previous version.': 'do poprzedniej wersji.', 'translation strings for the application': 'ciągi tłumaczeń dla aplikacji', 'try': 'spróbój', 'try something like': 'spróbój czegos takiego jak', 'unable to create application "%s"': 'nie można utworzyć aplikacji "%s"', 'unable to delete file "%(filename)s"': 'nie można usunąć pliku "%(filename)s"', 'unable to delete file plugin "%(plugin)s"': 'nie można usunąc pliku wtyczki "%(plugin)s"', 'unable to parse csv file': 'nie można sparsować pliku csv', 'unable to uninstall "%s"': 'nie można odinstalować "%s"', 'unable to upgrade because "%s"': 'unable to upgrade because "%s"', 'uncheck all': 'odznacz wszystko', 'uninstall': 'odinstaluj', 'update': 'uaktualnij', 'update all languages': 'uaktualnij wszystkie pliki tłumaczeń', 'upgrade web2py now': 'upgrade web2py now', 'upload': 'upload', 'upload application:': 'wyślij plik aplikacji:', 'upload file:': 'wyślij plik:', 'upload plugin file:': 'wyślij plik wtyczki:', 'variables': 'variables', 'versioning': 'versioning', 'view': 'widok', 'views': 'widoki', 'web2py Recent Tweets': 'najnowsze tweety web2py', 'web2py is up to date': 'web2py jest aktualne', 'web2py upgraded; please restart it': 'web2py upgraded; please restart it', }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" è un\'espressione opzionale come "campo1=\'nuovo valore\'". Non si può fare "update" o "delete" dei risultati di un JOIN ', '%Y-%m-%d': '%d/%m/%Y', '%Y-%m-%d %H:%M:%S': '%d/%m/%Y %H:%M:%S', '%s rows deleted': '%s righe ("record") cancellate', '%s rows updated': '%s righe ("record") modificate', '(requires internet access)': '(requires internet access)', '(something like "it-it")': '(qualcosa simile a "it-it")', 'A new version of web2py is available: %s': 'È disponibile una nuova versione di web2py: %s', 'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.': "ATTENZIONE: L'accesso richiede una connessione sicura (HTTPS) o l'esecuzione di web2py in locale (connessione su localhost)", 'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.': 'ATTENTZIONE: NON ESEGUIRE PIÙ TEST IN PARALLELO (I TEST NON SONO "THREAD SAFE")', 'ATTENTION: you cannot edit the running application!': "ATTENZIONE: non puoi modificare l'applicazione correntemente in uso ", 'About': 'Informazioni', 'About application': "Informazioni sull'applicazione", 'Admin is disabled because insecure channel': 'amministrazione disabilitata: comunicazione non sicura', 'Administrator Password:': 'Password Amministratore:', 'Application name:': 'Application name:', 'Are you sure you want to delete file "%s"?': 'Confermi di voler cancellare il file "%s"?', 'Are you sure you want to delete plugin "%s"?': 'Confermi di voler cancellare il plugin "%s"?', 'Are you sure you want to uninstall application "%s"?': 'Confermi di voler disinstallare l\'applicazione "%s"?', 'Are you sure you want to upgrade web2py now?': 'Confermi di voler aggiornare web2py ora?', 'Available databases and tables': 'Database e tabelle disponibili', 'Cannot be empty': 'Non può essere vuoto', 'Cannot compile: there are errors in your app:': "Compilazione fallita: ci sono errori nell'applicazione.", 'Check to delete': 'Seleziona per cancellare', 'Checking for upgrades...': 'Controllo aggiornamenti in corso...', 'Controller': 'Controller', 'Controllers': 'Controllers', 'Copyright': 'Copyright', 'Create new simple application': 'Crea nuova applicazione', 'Current request': 'Richiesta (request) corrente', 'Current response': 'Risposta (response) corrente', 'Current session': 'Sessione (session) corrente', 'DB Model': 'Modello di DB', 'Database': 'Database', 'Date and Time': 'Data and Ora', 'Delete': 'Cancella', 'Delete:': 'Cancella:', 'Deploy on Google App Engine': 'Installa su Google App Engine', 'EDIT': 'MODIFICA', 'Edit': 'Modifica', 'Edit This App': 'Modifica questa applicazione', 'Edit application': 'Modifica applicazione', 'Edit current record': 'Modifica record corrente', 'Editing Language file': 'Modifica file linguaggio', 'Editing file "%s"': 'Modifica del file "%s"', 'Enterprise Web Framework': 'Enterprise Web Framework', 'Error logs for "%(app)s"': 'Log degli errori per "%(app)s"', 'Exception instance attributes': 'Exception instance attributes', 'Functions with no doctests will result in [passed] tests.': 'I test delle funzioni senza "doctests" risulteranno sempre [passed].', 'Hello World': 'Salve Mondo', 'If the report above contains a ticket number it indicates a failure in executing the controller, before any attempt to execute the doctests. This is usually due to an indentation error or an error outside function code.\nA green title indicates that all tests (if defined) passed. In this case test results are not shown.': 'If the report above contains a ticket number it indicates a failure in executing the controller, before any attempt to execute the doctests. This is usually due to an indentation error or an error outside function code.\nA green title indicates that all tests (if defined) passed. In this case test results are not shown.', 'Import/Export': 'Importa/Esporta', 'Index': 'Indice', 'Installed applications': 'Applicazioni installate', 'Internal State': 'Stato interno', 'Invalid Query': 'Richiesta (query) non valida', 'Invalid action': 'Azione non valida', 'Language files (static strings) updated': 'Linguaggi (documenti con stringhe statiche) aggiornati', 'Languages': 'Linguaggi', 'Last saved on:': 'Ultimo salvataggio:', 'Layout': 'Layout', 'License for': 'Licenza relativa a', 'Login': 'Accesso', 'Login to the Administrative Interface': "Accesso all'interfaccia amministrativa", 'Main Menu': 'Menu principale', 'Menu Model': 'Menu Modelli', 'Models': 'Modelli', 'Modules': 'Moduli', 'NO': 'NO', 'New Record': 'Nuovo elemento (record)', 'New application wizard': 'New application wizard', 'New simple application': 'New simple application', 'No databases in this application': 'Nessun database presente in questa applicazione', 'Original/Translation': 'Originale/Traduzione', 'PAM authenticated user, cannot change password here': 'utente autenticato tramite PAM, impossibile modificare password qui', 'Peeking at file': 'Uno sguardo al file', 'Plugin "%s" in application': 'Plugin "%s" nell\'applicazione', 'Plugins': 'I Plugins', 'Powered by': 'Powered by', 'Query:': 'Richiesta (query):', 'Resolve Conflict file': 'File di risoluzione conflitto', 'Rows in table': 'Righe nella tabella', 'Rows selected': 'Righe selezionate', 'Saved file hash:': 'Hash del file salvato:', 'Static files': 'Files statici', 'Stylesheet': 'Foglio di stile (stylesheet)', 'Sure you want to delete this object?': 'Vuoi veramente cancellare questo oggetto?', 'TM': 'TM', 'Testing application': 'Test applicazione in corsg', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'La richiesta (query) è una condizione come ad esempio "db.tabella1.campo1==\'valore\'". Una condizione come "db.tabella1.campo1==db.tabella2.campo2" produce un "JOIN" SQL.', 'There are no controllers': 'Non ci sono controller', 'There are no models': 'Non ci sono modelli', 'There are no modules': 'Non ci sono moduli', 'There are no static files': 'Non ci sono file statici', 'There are no translators, only default language is supported': 'Non ci sono traduzioni, viene solo supportato il linguaggio di base', 'There are no views': 'Non ci sono viste ("view")', 'This is the %(filename)s template': 'Questo è il template %(filename)s', 'Ticket': 'Ticket', 'To create a plugin, name a file/folder plugin_[name]': 'Per creare un plugin, chiamare un file o cartella plugin_[nome]', 'Unable to check for upgrades': 'Impossibile controllare presenza di aggiornamenti', 'Unable to download app because:': 'Impossibile scaricare applicazione perché', 'Unable to download because': 'Impossibile scaricare perché', 'Update:': 'Aggiorna:', 'Upload & install packed application': 'Carica ed installa pacchetto con applicazione', 'Upload a package:': 'Upload a package:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Per costruire richieste (query) più complesse si usano (...)&(...) come "e" (AND), (...)|(...) come "o" (OR), e ~(...) come negazione (NOT).', 'Use an url:': 'Use an url:', 'Version': 'Versione', 'View': 'Vista', 'Views': 'viste', 'Welcome %s': 'Benvenuto %s', 'Welcome to web2py': 'Benvenuto su web2py', 'YES': 'SI', 'about': 'informazioni', 'additional code for your application': 'righe di codice aggiuntive per la tua applicazione', 'admin disabled because no admin password': 'amministrazione disabilitata per mancanza di password amministrativa', 'admin disabled because not supported on google app engine': 'amministrazione non supportata da Google Apps Engine', 'admin disabled because unable to access password file': 'amministrazione disabilitata per impossibilità di leggere il file delle password', 'administrative interface': 'administrative interface', 'and rename it (required):': 'e rinominala (obbligatorio):', 'and rename it:': 'e rinominala:', 'appadmin': 'appadmin ', 'appadmin is disabled because insecure channel': 'amministrazione app (appadmin) disabilitata: comunicazione non sicura', 'application "%s" uninstalled': 'applicazione "%s" disinstallata', 'application compiled': 'applicazione compilata', 'application is compiled and cannot be designed': "l'applicazione è compilata e non si può modificare", 'arguments': 'arguments', 'back': 'indietro', 'cache': 'cache', 'cache, errors and sessions cleaned': 'pulitura cache, errori and sessioni ', 'cannot create file': 'impossibile creare il file', 'cannot upload file "%(filename)s"': 'impossibile caricare il file "%(filename)s"', 'change admin password': 'change admin password', 'change password': 'cambia password', 'check all': 'controlla tutto', 'check for upgrades': 'check for upgrades', 'clean': 'pulisci', 'click here for online examples': 'clicca per vedere gli esempi', 'click here for the administrative interface': "clicca per l'interfaccia amministrativa", 'click to check for upgrades': 'clicca per controllare presenza di aggiornamenti', 'code': 'code', 'compile': 'compila', 'compiled application removed': "rimosso il codice compilato dell'applicazione", 'controllers': 'controllers', 'create': 'crea', 'create file with filename:': 'crea un file col nome:', 'create new application:': 'create new application:', 'created by': 'creato da', 'crontab': 'crontab', 'currently running': 'currently running', 'currently saved or': 'attualmente salvato o', 'customize me!': 'Personalizzami!', 'data uploaded': 'dati caricati', 'database': 'database', 'database %s select': 'database %s select', 'database administration': 'amministrazione database', 'db': 'db', 'defines tables': 'defininisce le tabelle', 'delete': 'Cancella', 'delete all checked': 'cancella tutti i selezionati', 'delete plugin': 'cancella plugin', 'deploy': 'deploy', 'design': 'progetta', 'direction: ltr': 'direction: ltr', 'done!': 'fatto!', 'edit': 'modifica', 'edit controller': 'modifica controller', 'edit profile': 'modifica profilo', 'edit views:': 'modifica viste (view):', 'errors': 'errori', 'export as csv file': 'esporta come file CSV', 'exposes': 'espone', 'extends': 'estende', 'failed to reload module because:': 'ricaricamento modulo fallito perché:', 'file "%(filename)s" created': 'creato il file "%(filename)s"', 'file "%(filename)s" deleted': 'cancellato il file "%(filename)s"', 'file "%(filename)s" uploaded': 'caricato il file "%(filename)s"', 'file "%s" of %s restored': 'ripristinato "%(filename)s"', 'file changed on disk': 'il file ha subito una modifica su disco', 'file does not exist': 'file inesistente', 'file saved on %(time)s': "file salvato nell'istante %(time)s", 'file saved on %s': 'file salvato: %s', 'help': 'aiuto', 'htmledit': 'modifica come html', 'includes': 'include', 'insert new': 'inserisci nuovo', 'insert new %s': 'inserisci nuovo %s', 'install': 'installa', 'internal error': 'errore interno', 'invalid password': 'password non valida', 'invalid request': 'richiesta non valida', 'invalid ticket': 'ticket non valido', 'language file "%(filename)s" created/updated': 'file linguaggio "%(filename)s" creato/aggiornato', 'languages': 'linguaggi', 'loading...': 'caricamento...', 'login': 'accesso', 'logout': 'uscita', 'merge': 'unisci', 'models': 'modelli', 'modules': 'moduli', 'new application "%s" created': 'creata la nuova applicazione "%s"', 'new plugin installed': 'installato nuovo plugin', 'new record inserted': 'nuovo record inserito', 'next 100 rows': 'prossime 100 righe', 'no match': 'nessuna corrispondenza', 'or import from csv file': 'oppure importa da file CSV', 'or provide app url:': "oppure fornisci url dell'applicazione:", 'overwrite installed app': 'sovrascrivi applicazione installata', 'pack all': 'crea pacchetto', 'pack compiled': 'crea pacchetto del codice compilato', 'pack plugin': 'crea pacchetto del plugin', 'password changed': 'password modificata', 'plugin "%(plugin)s" deleted': 'plugin "%(plugin)s" cancellato', 'previous 100 rows': '100 righe precedenti', 'record': 'record', 'record does not exist': 'il record non esiste', 'record id': 'ID del record', 'register': 'registrazione', 'remove compiled': 'rimozione codice compilato', 'restore': 'ripristino', 'revert': 'versione precedente', 'selected': 'selezionato', 'session expired': 'sessions scaduta', 'shell': 'shell', 'site': 'sito', 'some files could not be removed': 'non è stato possibile rimuovere alcuni files', 'start wizard': 'start wizard', 'state': 'stato', 'static': 'statico', 'submit': 'invia', 'table': 'tabella', 'test': 'test', 'the application logic, each URL path is mapped in one exposed function in the controller': 'logica dell\'applicazione, ogni percorso "URL" corrisponde ad una funzione esposta da un controller', 'the data representation, define database tables and sets': 'rappresentazione dei dati, definizione di tabelle di database e di "set" ', 'the presentations layer, views are also known as templates': 'Presentazione dell\'applicazione, viste (views, chiamate anche "templates")', 'these files are served without processing, your images go here': 'questi files vengono serviti così come sono, le immagini vanno qui', 'to previous version.': 'torna a versione precedente', 'translation strings for the application': "stringhe di traduzioni per l'applicazione", 'try': 'prova', 'try something like': 'prova qualcosa come', 'unable to create application "%s"': 'impossibile creare applicazione "%s"', 'unable to delete file "%(filename)s"': 'impossibile rimuovere file "%(plugin)s"', 'unable to delete file plugin "%(plugin)s"': 'impossibile rimuovere file di plugin "%(plugin)s"', 'unable to parse csv file': 'non riesco a decodificare questo file CSV', 'unable to uninstall "%s"': 'impossibile disinstallare "%s"', 'unable to upgrade because "%s"': 'impossibile aggiornare perché "%s"', 'uncheck all': 'smarca tutti', 'uninstall': 'disinstalla', 'update': 'aggiorna', 'update all languages': 'aggiorna tutti i linguaggi', 'upgrade web2py now': 'upgrade web2py now', 'upload application:': 'carica applicazione:', 'upload file:': 'carica file:', 'upload plugin file:': 'carica file di plugin:', 'variables': 'variables', 'versioning': 'sistema di versioni', 'view': 'vista', 'views': 'viste', 'web2py Recent Tweets': 'Tweets recenti per web2py', 'web2py is up to date': 'web2py è aggiornato', 'web2py upgraded; please restart it': 'web2py aggiornato; prego riavviarlo', }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" est une expression en option tels que "field1 = \'newvalue\'". Vous ne pouvez pas mettre à jour ou supprimer les résultats d\'une jointure "a JOIN"', '%Y-%m-%d': '%d-%m-%Y', '%Y-%m-%d %H:%M:%S': '%d-%m-%Y %H:%M:%S', '%s rows deleted': 'lignes %s supprimé', '%s rows updated': 'lignes %s mis à jour', '(requires internet access)': '(requires internet access)', '(something like "it-it")': '(quelque chose comme "it-it") ', 'A new version of web2py is available: %s': 'Une nouvelle version de web2py est disponible: %s ', 'A new version of web2py is available: Version 1.68.2 (2009-10-21 09:59:29)\n': 'Une nouvelle version de web2py est disponible: Version 1.68.2 (2009-10-21 09:59:29)\r\n', 'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.': 'ATTENTION: nécessite une connexion sécurisée (HTTPS) ou être en localhost. ', 'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.': 'ATTENTION: les tests ne sont pas thread-safe DONC NE PAS EFFECTUER DES TESTS MULTIPLES SIMULTANÉMENT.', 'ATTENTION: you cannot edit the running application!': "ATTENTION: vous ne pouvez pas modifier l'application qui tourne!", 'About': 'À propos', 'About application': "A propos de l'application", 'Additional code for your application': 'Additional code for your application', 'Admin is disabled because insecure channel': 'Admin est désactivé parce que canal non sécurisé', 'Admin language': 'Admin language', 'Administrator Password:': 'Mot de passe Administrateur:', 'Application name:': 'Application name:', 'Are you sure you want to delete file "%s"?': 'Etes-vous sûr de vouloir supprimer le fichier «%s»?', 'Are you sure you want to delete plugin "%s"?': 'Etes-vous sûr de vouloir effacer le plugin "%s"?', 'Are you sure you want to delete this object?': 'Are you sure you want to delete this object?', 'Are you sure you want to uninstall application "%s"?': "Êtes-vous sûr de vouloir désinstaller l'application «%s»?", 'Are you sure you want to upgrade web2py now?': 'Are you sure you want to upgrade web2py now?', 'Available databases and tables': 'Bases de données et tables disponible', 'Cannot be empty': 'Ne peut pas être vide', 'Cannot compile: there are errors in your app. Debug it, correct errors and try again.': 'Ne peut pas compiler: il y a des erreurs dans votre application. corriger les erreurs et essayez à nouveau.', 'Cannot compile: there are errors in your app:': 'Cannot compile: there are errors in your app:', 'Check to delete': 'Cocher pour supprimer', 'Checking for upgrades...': 'Vérification des mises à jour ... ', 'Controllers': 'Contrôleurs', 'Create new simple application': 'Créer une nouvelle application', 'Current request': 'Requête actuel', 'Current response': 'Réponse actuelle', 'Current session': 'Session en cours', 'Date and Time': 'Date et heure', 'Delete': 'Supprimer', 'Delete this file (you will be asked to confirm deletion)': 'Delete this file (you will be asked to confirm deletion)', 'Delete:': 'Supprimer:', 'Deploy on Google App Engine': 'Déployer sur Google App Engine', 'EDIT': 'MODIFIER', 'Edit application': "Modifier l'application", 'Edit current record': 'Modifier cet entrée', 'Editing Language file': 'Modifier le fichier de langue', 'Editing file': 'Modifier le fichier', 'Editing file "%s"': 'Modifier le fichier "% s" ', 'Enterprise Web Framework': 'Enterprise Web Framework', 'Error logs for "%(app)s"': 'Journal d\'erreurs pour "%(app)s"', 'Exception instance attributes': 'Exception instance attributes', 'Functions with no doctests will result in [passed] tests.': 'Des fonctions sans doctests entraînera tests [passed] .', 'If the report above contains a ticket number it indicates a failure in executing the controller, before any attempt to execute the doctests. This is usually due to an indentation error or an error outside function code.\nA green title indicates that all tests (if defined) passed. In this case test results are not shown.': "Si le rapport ci-dessus contient un numéro de ticket, cela indique une défaillance dans l'exécution du contrôleur, avant toute tentative d'exécuter les doctests. Cela est généralement dû à une erreur d'indentation ou une erreur à l'extérieur du code de la fonction.\r\nUn titre verte indique que tous les tests (si définie) passed. Dans ce cas, les résultats des essais ne sont pas affichées.", 'Import/Export': 'Importer/Exporter', 'Installed applications': 'Les applications installées', 'Internal State': 'État Interne', 'Invalid Query': 'Requête non valide', 'Invalid action': 'Action non valide', 'Language files (static strings) updated': 'Fichiers de langue (static strings) Mise à jour ', 'Languages': 'Langues', 'Last saved on:': 'Dernière sauvegarde le:', 'License for': 'Licence pour', 'Login': 'Connexion', 'Login to the Administrative Interface': "Se connecter à l'interface d'administration", 'Models': 'Modèles', 'Modules': 'Modules', 'NO': 'NON', 'New Record': 'Nouvel Entrée', 'New application wizard': 'New application wizard', 'New simple application': 'New simple application', 'No databases in this application': 'Aucune base de données dans cette application', 'Original/Translation': 'Original / Traduction', 'PAM authenticated user, cannot change password here': 'PAM authenticated user, cannot change password here', 'Peeking at file': 'Jeter un oeil au fichier', 'Plugin "%s" in application': 'Plugin "%s" dans l\'application', 'Plugins': 'Plugins', 'Powered by': 'Propulsé par', 'Query:': 'Requête: ', 'Resolve Conflict file': 'Résoudre les conflits de fichiers', 'Rows in table': 'Lignes de la table', 'Rows selected': 'Lignes sélectionnées', "Run tests in this file (to run all files, you may also use the button labelled 'test')": "Run tests in this file (to run all files, you may also use the button labelled 'test')", 'Save': 'Save', 'Saved file hash:': 'Hash du Fichier enregistré:', 'Searching:': 'Searching:', 'Static files': 'Fichiers statiques', 'Sure you want to delete this object?': 'Vous êtes sûr de vouloir supprimer cet objet? ', 'TM': 'MD', 'Testing application': "Test de l'application", 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'La "requête" est une condition comme "db.table1.field1==\'value\'". Quelque chose comme "db.table1.field1==db.table2.field2" aboutit à un JOIN SQL.', 'The application logic, each URL path is mapped in one exposed function in the controller': 'The application logic, each URL path is mapped in one exposed function in the controller', 'The data representation, define database tables and sets': 'The data representation, define database tables and sets', 'The presentations layer, views are also known as templates': 'The presentations layer, views are also known as templates', 'There are no controllers': "Il n'existe pas de contrôleurs", 'There are no models': "Il n'existe pas de modèles", 'There are no modules': "Il n'existe pas de modules", 'There are no plugins': 'There are no plugins', 'There are no static files': "Il n'existe pas de fichiers statiques", 'There are no translators, only default language is supported': "Il n'y a pas de traducteurs, est prise en charge uniquement la langue par défaut", 'There are no views': "Il n'existe pas de vues", 'These files are served without processing, your images go here': 'These files are served without processing, your images go here', 'This is the %(filename)s template': 'Ceci est le modèle %(filename)s ', 'Ticket': 'Ticket', 'To create a plugin, name a file/folder plugin_[name]': 'Pour créer un plugin, créer un fichier /dossier plugin_[nom]', 'Translation strings for the application': 'Translation strings for the application', 'Unable to check for upgrades': 'Impossible de vérifier les mises à niveau', 'Unable to download': 'Impossible de télécharger', 'Unable to download app': 'Impossible de télécharger app', 'Unable to download app because:': 'Unable to download app because:', 'Unable to download because': 'Unable to download because', 'Update:': 'Mise à jour:', 'Upload & install packed application': 'Upload & install packed application', 'Upload a package:': 'Upload a package:', 'Upload existing application': 'charger une application existante', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Utilisez (...)&(...) pour AND, (...)|(...) pour OR, et ~(...) pour NOT et construire des requêtes plus complexes. ', 'Use an url:': 'Use an url:', 'Version': 'Version', 'Views': 'Vues', 'Web Framework': 'Web Framework', 'YES': 'OUI', 'about': 'à propos', 'additional code for your application': 'code supplémentaire pour votre application', 'admin disabled because no admin password': 'admin désactivé car aucun mot de passe admin', 'admin disabled because not supported on google app engine': 'admin désactivé car non pris en charge sur Google Apps engine', 'admin disabled because unable to access password file': "admin désactivé car incapable d'accéder au fichier mot de passe", 'administrative interface': 'administrative interface', 'and rename it (required):': 'et renommez-la (obligatoire):', 'and rename it:': 'et renommez-le:', 'appadmin': 'appadmin', 'appadmin is disabled because insecure channel': 'appadmin est désactivé parce que canal non sécurisé', 'application "%s" uninstalled': 'application "%s" désinstallé', 'application %(appname)s installed with md5sum: %(digest)s': 'application %(appname)s installed with md5sum: %(digest)s', 'application compiled': 'application compilée', 'application is compiled and cannot be designed': "l'application est compilée et ne peut être désigné", 'arguments': 'arguments', 'back': 'retour', 'cache': 'cache', 'cache, errors and sessions cleaned': 'cache, erreurs et sessions nettoyé', 'cannot create file': 'ne peu pas créer de fichier', 'cannot upload file "%(filename)s"': 'ne peu pas charger le fichier "%(filename)s"', 'change admin password': 'change admin password', 'check all': 'tous vérifier ', 'check for upgrades': 'check for upgrades', 'clean': 'nettoyer', 'click to check for upgrades': 'Cliquez pour vérifier les mises à niveau', 'code': 'code', 'collapse/expand all': 'collapse/expand all', 'compile': 'compiler', 'compiled application removed': 'application compilée enlevé', 'controllers': 'contrôleurs', 'create': 'create', 'create file with filename:': 'créer un fichier avec nom de fichier:', 'create new application:': 'créer une nouvelle application:', 'created by': 'créé par', 'crontab': 'crontab', 'currently running': 'currently running', 'currently saved or': 'actuellement enregistrés ou', 'data uploaded': 'données chargées', 'database': 'base de données', 'database %s select': 'base de données %s sélectionner', 'database administration': 'administration base de données', 'db': 'db', 'defines tables': 'définit les tables', 'delete': 'supprimer', 'delete all checked': 'supprimer tout ce qui est cocher', 'delete plugin': ' supprimer plugin', 'deploy': 'deploy', 'design': 'conception', 'direction: ltr': 'direction: ltr', 'docs': 'docs', 'done!': 'fait!', 'download layouts': 'download layouts', 'download plugins': 'download plugins', 'edit': 'modifier', 'edit controller': 'modifier contrôleur', 'edit views:': 'edit views:', 'errors': 'erreurs', 'export as csv file': 'exportation au format CSV', 'exposes': 'expose', 'exposes:': 'exposes:', 'extends': 'étend', 'failed to reload module': 'impossible de recharger le module', 'failed to reload module because:': 'failed to reload module because:', 'file "%(filename)s" created': 'fichier "%(filename)s" créé', 'file "%(filename)s" deleted': 'fichier "%(filename)s" supprimé', 'file "%(filename)s" uploaded': 'fichier "%(filename)s" chargé', 'file "%s" of %s restored': 'fichier "%s" de %s restauré', 'file changed on disk': 'fichier modifié sur le disque', 'file does not exist': "fichier n'existe pas", 'file saved on %(time)s': 'fichier enregistré le %(time)s', 'file saved on %s': 'fichier enregistré le %s', 'files': 'files', 'filter': 'filter', 'help': 'aide', 'htmledit': 'edition html', 'includes': 'inclus', 'index': 'index', 'insert new': 'insérer nouveau', 'insert new %s': 'insérer nouveau %s', 'install': 'install', 'internal error': 'erreur interne', 'invalid password': 'mot de passe invalide', 'invalid request': 'Demande incorrecte', 'invalid ticket': 'ticket non valide', 'language file "%(filename)s" created/updated': 'fichier de langue "%(filename)s" créé/mis à jour', 'languages': 'langues', 'loading...': 'Chargement ...', 'login': 'connexion', 'logout': 'déconnexion', 'merge': 'fusionner', 'models': 'modèles', 'modules': 'modules', 'new application "%s" created': 'nouvelle application "%s" créée', 'new plugin installed': 'nouveau plugin installé', 'new record inserted': 'nouvelle entrée inséré', 'next 100 rows': '100 lignes suivantes', 'no match': 'no match', 'or import from csv file': 'ou importer depuis un fichier CSV ', 'or provide app url:': 'or provide app url:', 'or provide application url:': "ou fournir l'URL de l'application:", 'overwrite installed app': 'overwrite installed app', 'pack all': 'tout empaqueter', 'pack compiled': 'paquet compilé', 'pack plugin': 'paquet plugin', 'password changed': 'password changed', 'plugin "%(plugin)s" deleted': 'plugin "%(plugin)s" supprimé', 'plugins': 'plugins', 'previous 100 rows': '100 lignes précédentes', 'record': 'entrée', 'record does not exist': "l'entrée n'existe pas", 'record id': 'id entrée', 'remove compiled': 'retirer compilé', 'restore': 'restaurer', 'revert': 'revenir', 'save': 'sauver', 'selected': 'sélectionnés', 'session expired': 'la session a expiré ', 'shell': 'shell', 'site': 'site', 'some files could not be removed': 'certains fichiers ne peuvent pas être supprimés', 'start wizard': 'start wizard', 'state': 'état', 'static': 'statiques', 'submit': 'envoyer', 'table': 'table', 'test': 'tester', 'the application logic, each URL path is mapped in one exposed function in the controller': "la logique de l'application, chaque route URL est mappé dans une fonction exposée dans le contrôleur", 'the data representation, define database tables and sets': 'la représentation des données, défini les tables de bases de données et sets', 'the presentations layer, views are also known as templates': 'la couche des présentations, les vues sont également connus en tant que modèles', 'these files are served without processing, your images go here': 'ces fichiers sont servis sans transformation, vos images vont ici', 'to previous version.': 'à la version précédente.', 'translation strings for the application': "chaînes de traduction de l'application", 'try': 'essayer', 'try something like': 'essayez quelque chose comme', 'unable to create application "%s"': 'impossible de créer l\'application "%s"', 'unable to delete file "%(filename)s"': 'impossible de supprimer le fichier "%(filename)s"', 'unable to delete file plugin "%(plugin)s"': 'impossible de supprimer le plugin "%(plugin)s"', 'unable to parse csv file': "impossible d'analyser les fichiers CSV", 'unable to uninstall "%s"': 'impossible de désinstaller "%s"', 'unable to upgrade because "%s"': 'unable to upgrade because "%s"', 'uncheck all': 'tout décocher', 'uninstall': 'désinstaller', 'update': 'mettre à jour', 'update all languages': 'mettre à jour toutes les langues', 'upgrade now': 'upgrade now', 'upgrade web2py now': 'upgrade web2py now', 'upload': 'upload', 'upload application:': "charger l'application:", 'upload file:': 'charger le fichier:', 'upload plugin file:': 'charger fichier plugin:', 'user': 'user', 'variables': 'variables', 'versioning': 'versioning', 'view': 'vue', 'views': 'vues', 'web2py Recent Tweets': 'web2py Tweets récentes', 'web2py is up to date': 'web2py est à jour', 'web2py upgraded; please restart it': 'web2py upgraded; please restart it', }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"עדכן" הוא ביטוי אופציונאלי, כגון "field1=newvalue". אינך יוכל להשתמש בjoin, בעת שימוש ב"עדכן" או "מחק".', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s rows deleted': '%s רשומות נמחקו', '%s rows updated': '%s רשומות עודכנו', '(requires internet access)': '(requires internet access)', '(something like "it-it")': '(למשל "it-it")', 'A new version of web2py is available: %s': 'גירסא חדשה של web2py זמינה: %s', 'A new version of web2py is available: Version 1.85.3 (2010-09-18 07:07:46)\n': 'A new version of web2py is available: Version 1.85.3 (2010-09-18 07:07:46)\r\n', 'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.': 'לתשומת ליבך: ניתן להתחבר רק בערוץ מאובטח (HTTPS) או מlocalhost', 'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.': 'לתשומת ליבך: אין לערוך מספר בדיקות במקביל, שכן הן עשויות להפריע זו לזו', 'ATTENTION: you cannot edit the running application!': 'לתשומת ליבך: לא ניתן לערוך אפליקציה בזמן הרצתה', 'About': 'אודות', 'About application': 'אודות אפליקציה', 'Additional code for your application': 'Additional code for your application', 'Admin is disabled because insecure channel': 'ממשק האדמין נוטרל בשל גישה לא מאובטחת', 'Admin language': 'Admin language', 'Administrator Password:': 'סיסמת מנהל', 'Application name:': 'Application name:', 'Are you sure you want to delete file "%s"?': 'האם אתה בטוח שברצונך למחוק את הקובץ "%s"?', 'Are you sure you want to delete plugin "%s"?': 'האם אתה בטוח שברצונך למחוק את התוסף "%s"?', 'Are you sure you want to uninstall application "%s"?': 'האם אתה בטוח שברצונך להסיר את האפליקציה "%s"?', 'Are you sure you want to upgrade web2py now?': 'האם אתה בטוח שאתה רוצה לשדרג את web2py עכשיו?', 'Available databases and tables': 'מסדי נתונים וטבלאות זמינים', 'Cannot be empty': 'אינו יכול להישאר ריק', 'Cannot compile: there are errors in your app:': 'לא ניתן לקמפל: ישנן שגיאות באפליקציה שלך:', 'Check to delete': 'סמן כדי למחוק', 'Checking for upgrades...': 'מחפש עדכונים', 'Controllers': 'בקרים', 'Create new simple application': 'צור אפליקציה חדשה', 'Current request': 'בקשה נוכחית', 'Current response': 'מענה נוכחי', 'Current session': 'סשן זה', 'Date and Time': 'תאריך ושעה', 'Delete': 'מחק', 'Delete:': 'מחק:', 'Deploy on Google App Engine': 'העלה ל Google App Engine', 'Detailed traceback description': 'Detailed traceback description', 'EDIT': 'ערוך!', 'Edit application': 'ערוך אפליקציה', 'Edit current record': 'ערוך רשומה נוכחית', 'Editing Language file': 'עורך את קובץ השפה', 'Editing file "%s"': 'עורך את הקובץ "%s"', 'Enterprise Web Framework': 'סביבת הפיתוח לרשת', 'Error logs for "%(app)s"': 'דו"ח שגיאות עבור אפליקציה "%(app)s"', 'Error snapshot': 'Error snapshot', 'Error ticket': 'Error ticket', 'Exception instance attributes': 'נתוני החריגה', 'Frames': 'Frames', 'Functions with no doctests will result in [passed] tests.': 'פונקציות שלא הוגדר להן doctest ירשמו כבדיקות ש[עברו בהצלחה].', 'If the report above contains a ticket number it indicates a failure in executing the controller, before any attempt to execute the doctests. This is usually due to an indentation error or an error outside function code.\nA green title indicates that all tests (if defined) passed. In this case test results are not shown.': 'אם בדו"ח לעיל מופיע מספר דו"ח שגיאה, זה מצביע על שגיאה בבקר, עוד לפני שניתן היה להריץ את הdoctest. לרוב מדובר בשגיאת הזחה, או שגיאה שאינה בקוד של הפונקציה.\r\nכותרת ירוקה מצביע על כך שכל הבדיקות (אם הוגדרו) עברו בהצלחה, במידה ותוצאות הבדיקה אינן מופיעות.', 'Import/Export': 'יבא\יצא', 'Installed applications': 'אפליקציות מותקנות', 'Internal State': 'מצב מובנה', 'Invalid Query': 'שאילתה לא תקינה', 'Invalid action': 'הוראה לא קיימת', 'Language files (static strings) updated': 'קובץ השפה (מחרוזות סטאטיות) עודכן', 'Languages': 'שפות', 'Last saved on:': 'לאחרונה נשמר בתאריך:', 'License for': 'רשיון עבור', 'Login': 'התחבר', 'Login to the Administrative Interface': 'התחבר לממשק המנהל', 'Models': 'מבני נתונים', 'Modules': 'מודולים', 'NO': 'לא', 'New Record': 'רשומה חדשה', 'New application wizard': 'New application wizard', 'New simple application': 'New simple application', 'No databases in this application': 'אין מסדי נתונים לאפליקציה זו', 'Original/Translation': 'מקור\תרגום', 'PAM authenticated user, cannot change password here': 'שינוי סיסמא באמצעות PAM אינו יכול להתבצע כאן', 'Peeking at file': 'מעיין בקובץ', 'Plugin "%s" in application': 'פלאגין "%s" של אפליקציה', 'Plugins': 'תוספים', 'Powered by': 'מופעל ע"י', 'Query:': 'שאילתה:', 'Resolve Conflict file': 'הסר קובץ היוצר קונפליקט', 'Rows in table': 'רשומות בטבלה', 'Rows selected': 'רשומות נבחרו', 'Saved file hash:': 'גיבוב הקובץ השמור:', 'Static files': 'קבצים סטאטיים', 'Sure you want to delete this object?': 'האם אתה בטוח שברצונך למחוק אובייקט זה?', 'TM': 'סימן רשום', 'Testing application': 'בודק את האפליקציה', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': '"שאליתה" היא תנאי כגון "db1.table1.filed1=\'value\'" ביטוי כמו db.table1.field1=db.table2.field1 יחולל join', 'The application logic, each URL path is mapped in one exposed function in the controller': 'The application logic, each URL path is mapped in one exposed function in the controller', 'The data representation, define database tables and sets': 'The data representation, define database tables and sets', 'The presentations layer, views are also known as templates': 'The presentations layer, views are also known as templates', 'There are no controllers': 'אין בקרים', 'There are no models': 'אין מבני נתונים', 'There are no modules': 'אין מודולים', 'There are no plugins': 'There are no plugins', 'There are no static files': 'אין קבצים סטאטיים', 'There are no translators, only default language is supported': 'אין תרגומים. רק שפת ברירת המחדל נתמכת', 'There are no views': 'אין קבצי תצוגה', 'These files are served without processing, your images go here': 'These files are served without processing, your images go here', 'This is the %(filename)s template': 'זוהי תבנית הקובץ %(filename)s ', 'Ticket': 'דו"ח שגיאה', 'Ticket ID': 'Ticket ID', 'To create a plugin, name a file/folder plugin_[name]': 'כדי ליצור תוסף, קרא לקובץ או סיפריה בשם לפי התבנית plugin_[name]', 'Traceback': 'Traceback', 'Translation strings for the application': 'Translation strings for the application', 'Unable to check for upgrades': 'לא ניתן היה לבדוק אם יש שדרוגים', 'Unable to download app because:': 'לא ניתן היה להוריד את האפליקציה כי:', 'Unable to download because': 'לא הצלחתי להוריד כי', 'Update:': 'עדכן:', 'Upload & install packed application': 'העלה והתקן אפליקציה ארוזה', 'Upload a package:': 'Upload a package:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'השתמש ב (...)&(...) עבור תנאי AND, (...)|(...) עבור תנאי OR ו~(...) עבור תנאי NOT ליצירת שאילתות מורכבות', 'Use an url:': 'Use an url:', 'Version': 'גירסא', 'Views': 'מראה', 'YES': 'כן', 'about': 'אודות', 'additional code for your application': 'קוד נוסף עבור האפליקציה שלך', 'admin disabled because no admin password': 'ממשק המנהל מנוטרל כי לא הוגדרה סיסמת מנהל', 'admin disabled because not supported on google app engine': 'ממשק המנהל נוטרל, כי אין תמיכה בGoogle app engine', 'admin disabled because unable to access password file': 'ממשק מנהל נוטרל, כי לא ניתן לגשת לקובץ הסיסמאות', 'administrative interface': 'administrative interface', 'and rename it (required):': 'ושנה את שמו (חובה):', 'and rename it:': 'ושנה את שמו:', 'appadmin': 'מנהל מסד הנתונים', 'appadmin is disabled because insecure channel': 'מנהל מסד הנתונים נוטרל בשל ערוץ לא מאובטח', 'application "%s" uninstalled': 'אפליקציה "%s" הוסרה', 'application compiled': 'אפליקציה קומפלה', 'application is compiled and cannot be designed': 'לא ניתן לערוך אפליקציה מקומפלת', 'arguments': 'פרמטרים', 'back': 'אחורה', 'cache': 'מטמון', 'cache, errors and sessions cleaned': 'מטמון, שגיאות וסשן נוקו', 'cannot create file': 'לא מצליח ליצור קובץ', 'cannot upload file "%(filename)s"': 'לא הצלחתי להעלות את הקובץ "%(filename)s"', 'change admin password': 'סיסמת מנהל שונתה', 'check all': 'סמן הכל', 'check for upgrades': 'check for upgrades', 'clean': 'נקה', 'click to check for upgrades': 'לחץ כדי לחפש עדכונים', 'code': 'קוד', 'collapse/expand all': 'collapse/expand all', 'compile': 'קמפל', 'compiled application removed': 'אפליקציה מקומפלת הוסרה', 'controllers': 'בקרים', 'create': 'צור', 'create file with filename:': 'צור קובץ בשם:', 'create new application:': 'צור אפליקציה חדשה:', 'created by': 'נוצר ע"י', 'crontab': 'משימות מתוזמנות', 'currently running': 'currently running', 'currently saved or': 'נשמר כעת או', 'data uploaded': 'המידע הועלה', 'database': 'מסד נתונים', 'database %s select': 'מסד הנתונים %s נבחר', 'database administration': 'ניהול מסד נתונים', 'db': 'מסד נתונים', 'defines tables': 'הגדר טבלאות', 'delete': 'מחק', 'delete all checked': 'סמן הכל למחיקה', 'delete plugin': 'מחק תוסף', 'deploy': 'deploy', 'design': 'עיצוב', 'direction: ltr': 'direction: rtl', 'done!': 'הסתיים!', 'download layouts': 'download layouts', 'download plugins': 'download plugins', 'edit': 'ערוך', 'edit controller': 'ערוך בקר', 'edit views:': 'ערוך קיבצי תצוגה:', 'errors': 'שגיאות', 'export as csv file': 'יצא לקובץ csv', 'exposes': 'חושף את', 'extends': 'הרחבה של', 'failed to reload module because:': 'נכשל בטעינה חוזרת של מודול בגלל:', 'file "%(filename)s" created': 'הקובץ "%(filename)s" נוצר', 'file "%(filename)s" deleted': 'הקובץ "%(filename)s" נמחק', 'file "%(filename)s" uploaded': 'הקובץ "%(filename)s" הועלה', 'file "%s" of %s restored': 'הקובץ "%s" of %s שוחזר', 'file changed on disk': 'קובץ שונה על גבי הדיסק', 'file does not exist': 'קובץ לא נמצא', 'file saved on %(time)s': 'הקובץ נשמר בשעה %(time)s', 'file saved on %s': 'הקובץ נשמר ב%s', 'filter': 'filter', 'help': 'עזרה', 'htmledit': 'עורך ויזואלי', 'includes': 'מכיל', 'insert new': 'הכנס נוסף', 'insert new %s': 'הכנס %s נוסף', 'inspect attributes': 'inspect attributes', 'install': 'התקן', 'internal error': 'שגיאה מובנית', 'invalid password': 'סיסמא שגויה', 'invalid request': 'בקשה לא תקינה', 'invalid ticket': 'דו"ח שגיאה לא קיים', 'language file "%(filename)s" created/updated': 'קובץ השפה "%(filename)s" נוצר\עודכן', 'languages': 'שפות', 'loading...': 'טוען...', 'locals': 'locals', 'login': 'התחבר', 'logout': 'התנתק', 'merge': 'מזג', 'models': 'מבני נתונים', 'modules': 'מודולים', 'new application "%s" created': 'האפליקציה "%s" נוצרה', 'new plugin installed': 'פלאגין חדש הותקן', 'new record inserted': 'הרשומה נוספה', 'next 100 rows': '100 הרשומות הבאות', 'no match': 'לא נמצאה התאמה', 'or import from csv file': 'או יבא מקובץ csv', 'or provide app url:': 'או ספק כתובת url של אפליקציה', 'overwrite installed app': 'התקן על גבי אפלקציה מותקנת', 'pack all': 'ארוז הכל', 'pack compiled': 'ארוז מקומפל', 'pack plugin': 'ארוז תוסף', 'password changed': 'סיסמא שונתה', 'plugin "%(plugin)s" deleted': 'תוסף "%(plugin)s" נמחק', 'plugins': 'plugins', 'previous 100 rows': '100 הרשומות הקודמות', 'record': 'רשומה', 'record does not exist': 'הרשומה אינה קיימת', 'record id': 'מזהה רשומה', 'remove compiled': 'הסר מקומפל', 'request': 'request', 'response': 'response', 'restore': 'שחזר', 'revert': 'חזור לגירסא קודמת', 'selected': 'נבחרו', 'session': 'session', 'session expired': 'תם הסשן', 'shell': 'שורת פקודה', 'site': 'אתר', 'some files could not be removed': 'לא ניתן היה להסיר חלק מהקבצים', 'start wizard': 'start wizard', 'state': 'מצב', 'static': 'קבצים סטאטיים', 'submit': 'שלח', 'table': 'טבלה', 'test': 'בדיקות', 'the application logic, each URL path is mapped in one exposed function in the controller': 'הלוגיקה של האפליקציה, כל url ממופה לפונקציה חשופה בבקר', 'the data representation, define database tables and sets': 'ייצוג המידע, בו מוגדרים טבלאות ומבנים', 'the presentations layer, views are also known as templates': 'שכבת התצוגה, המכונה גם template', 'these files are served without processing, your images go here': 'אלו הם קבצים הנשלחים מהשרת ללא עיבוד. הכנס את התמונות כאן', 'to previous version.': 'אין גירסא קודמת', 'translation strings for the application': 'מחרוזות תרגום עבור האפליקציה', 'try': 'נסה', 'try something like': 'נסה משהו כמו', 'unable to create application "%s"': 'נכשל ביצירת האפליקציה "%s"', 'unable to delete file "%(filename)s"': 'נכשל במחיקת הקובץ "%(filename)s"', 'unable to delete file plugin "%(plugin)s"': 'נכשל במחיקת התוסף "%(plugin)s"', 'unable to parse csv file': 'לא הצלחתי לנתח את הקלט של קובץ csv', 'unable to uninstall "%s"': 'לא ניתן להסיר את "%s"', 'unable to upgrade because "%s"': 'לא ניתן היה לשדרג כי "%s"', 'uncheck all': 'הסר סימון מהכל', 'uninstall': 'הסר התקנה', 'update': 'עדכן', 'update all languages': 'עדכן את כלל קיבצי השפה', 'upgrade now': 'upgrade now', 'upgrade web2py now': 'שדרג את web2py עכשיו', 'upload': 'upload', 'upload application:': 'העלה אפליקציה:', 'upload file:': 'העלה קובץ:', 'upload plugin file:': 'העלה קובץ תוסף:', 'variables': 'משתנים', 'versioning': 'מנגנון גירסאות', 'view': 'הצג', 'views': 'מראה', 'web2py Recent Tweets': 'ציוצים אחרונים של web2py', 'web2py is up to date': 'web2py מותקנת בגירסתה האחרונה', 'web2py upgraded; please restart it': 'web2py שודרגה; נא אתחל אותה', }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" é uma expressão opcional como "campo1=\'novo_valor\'". Não é permitido atualizar ou apagar resultados de um JOIN', '%Y-%m-%d': '%d/%m/%Y', '%Y-%m-%d %H:%M:%S': '%d/%m/%Y %H:%M:%S', '%s rows deleted': '%s registros apagados', '%s rows updated': '%s registros atualizados', '(requires internet access)': '(requer acesso a internet)', '(something like "it-it")': '(algo como "it-it")', 'A new version of web2py is available': 'Está disponível uma nova versão do web2py', 'A new version of web2py is available: %s': 'Está disponível uma nova versão do web2py: %s', 'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.': 'ATENÇÃO o login requer uma conexão segura (HTTPS) ou executar de localhost.', 'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.': 'ATENÇÃO OS TESTES NÃO THREAD SAFE, NÃO EFETUE MÚLTIPLOS TESTES AO MESMO TEMPO.', 'ATTENTION: you cannot edit the running application!': 'ATENÇÃO: Não pode modificar a aplicação em execução!', 'About': 'Sobre', 'About application': 'Sobre a aplicação', 'Additional code for your application': 'Additional code for your application', 'Admin is disabled because insecure channel': 'Admin desabilitado pois o canal não é seguro', 'Admin is disabled because unsecure channel': 'Admin desabilitado pois o canal não é seguro', 'Admin language': 'Linguagem do Admin', 'Administrator Password:': 'Senha de administrador:', 'Application name:': 'Nome da aplicação:', 'Are you sure you want to delete file "%s"?': 'Tem certeza que deseja apagar o arquivo "%s"?', 'Are you sure you want to delete plugin "%s"?': 'Tem certeza que deseja apagar o plugin "%s"?', 'Are you sure you want to uninstall application "%s"': 'Tem certeza que deseja apagar a aplicação "%s"?', 'Are you sure you want to uninstall application "%s"?': 'Tem certeza que deseja apagar a aplicação "%s"?', 'Are you sure you want to upgrade web2py now?': 'Tem certeza que deseja atualizar o web2py agora?', 'Available databases and tables': 'Bancos de dados e tabelas disponíveis', 'Cannot be empty': 'Não pode ser vazio', 'Cannot compile: there are errors in your app. Debug it, correct errors and try again.': 'Não é possível compilar: Existem erros em sua aplicação. Depure, corrija os errros e tente novamente', 'Cannot compile: there are errors in your app:': 'Não é possível compilar: Existem erros em sua aplicação', 'Change Password': 'Trocar Senha', 'Check to delete': 'Marque para apagar', 'Checking for upgrades...': 'Buscando atualizações...', 'Click row to expand traceback': 'Clique em uma coluna para expandir o log do erro', 'Client IP': 'IP do cliente', 'Controllers': 'Controladores', 'Count': 'Contagem', 'Create new application using the Wizard': 'Criar nova aplicação utilizando o assistente', 'Create new simple application': 'Crie uma nova aplicação', 'Current request': 'Requisição atual', 'Current response': 'Resposta atual', 'Current session': 'Sessão atual', 'DESIGN': 'Projeto', 'Date and Time': 'Data e Hora', 'Delete': 'Apague', 'Delete:': 'Apague:', 'Deploy on Google App Engine': 'Publicar no Google App Engine', 'Description': 'Descrição', 'Design for': 'Projeto de', 'Detailed traceback description': 'Detailed traceback description', 'E-mail': 'E-mail', 'EDIT': 'EDITAR', 'Edit Profile': 'Editar Perfil', 'Edit application': 'Editar aplicação', 'Edit current record': 'Editar o registro atual', 'Editing Language file': 'Editando arquivo de linguagem', 'Editing file': 'Editando arquivo', 'Editing file "%s"': 'Editando arquivo "%s"', 'Enterprise Web Framework': 'Framework web empresarial', 'Error': 'Erro', 'Error logs for "%(app)s"': 'Logs de erro para "%(app)s"', 'Error snapshot': 'Error snapshot', 'Error ticket': 'Error ticket', 'Exception instance attributes': 'Atributos da instancia de excessão', 'File': 'Arquivo', 'First name': 'Nome', 'Frames': 'Frames', 'Functions with no doctests will result in [passed] tests.': 'Funções sem doctests resultarão em testes [aceitos].', 'Group ID': 'ID do Grupo', 'Hello World': 'Olá Mundo', 'If the report above contains a ticket number it indicates a failure in executing the controller, before any attempt to execute the doctests. This is usually due to an indentation error or an error outside function code.\nA green title indicates that all tests (if defined) passed. In this case test results are not shown.': 'Se o relatório acima contém um número de ticket, isso indica uma falha no controlador em execução, antes de tantar executar os doctests. Isto acontece geralmente por erro de endentação ou erro fora do código da função.\nO titulo em verde indica que os testes (se definidos) passaram. Neste caso os testes não são mostrados.', 'Import/Export': 'Importar/Exportar', 'Installed applications': 'Aplicações instaladas', 'Internal State': 'Estado Interno', 'Invalid Query': 'Consulta inválida', 'Invalid action': 'Ação inválida', 'Invalid email': 'E-mail inválido', 'Language files (static strings) updated': 'Arquivos de linguagem (textos estáticos) atualizados', 'Languages': 'Linguagens', 'Last name': 'Sobrenome', 'Last saved on:': 'Salvo em:', 'License for': 'Licença para', 'Login': 'Entrar', 'Login to the Administrative Interface': 'Entrar na interface adminitrativa', 'Logout': 'Sair', 'Lost Password': 'Senha perdida', 'Models': 'Modelos', 'Modules': 'Módulos', 'NO': 'NÃO', 'Name': 'Nome', 'New Record': 'Novo registro', 'New application wizard': 'Assistente para novas aplicações ', 'New simple application': 'Nova aplicação básica', 'No databases in this application': 'Não existem bancos de dados nesta aplicação', 'Origin': 'Origem', 'Original/Translation': 'Original/Tradução', 'PAM authenticated user, cannot change password here': 'usuario autenticado por PAM, não pode alterar a senha por aqui', 'Password': 'Senha', 'Peeking at file': 'Visualizando arquivo', 'Plugin "%s" in application': 'Plugin "%s" na aplicação', 'Plugins': 'Plugins', 'Powered by': 'Este site utiliza', 'Query:': 'Consulta:', 'Record ID': 'ID do Registro', 'Register': 'Registrar-se', 'Registration key': 'Chave de registro', 'Resolve Conflict file': 'Arquivo de resolução de conflito', 'Role': 'Papel', 'Rows in table': 'Registros na tabela', 'Rows selected': 'Registros selecionados', 'Saved file hash:': 'Hash do arquivo salvo:', 'Searching:': 'Searching:', 'Static files': 'Arquivos estáticos', 'Sure you want to delete this object?': 'Tem certeza que deseja apaagr este objeto?', 'TM': 'MR', 'Table name': 'Nome da tabela', 'Testing application': 'Testando a aplicação', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'A "consulta" é uma condição como "db.tabela.campo1==\'valor\'". Algo como "db.tabela1.campo1==db.tabela2.campo2" resulta em um JOIN SQL.', 'The application logic, each URL path is mapped in one exposed function in the controller': 'The application logic, each URL path is mapped in one exposed function in the controller', 'The data representation, define database tables and sets': 'The data representation, define database tables and sets', 'The presentations layer, views are also known as templates': 'The presentations layer, views are also known as templates', 'There are no controllers': 'Não existem controllers', 'There are no models': 'Não existem modelos', 'There are no modules': 'Não existem módulos', 'There are no plugins': 'There are no plugins', 'There are no static files': 'Não existem arquicos estáticos', 'There are no translators, only default language is supported': 'Não há traduções, somente a linguagem padrão é suportada', 'There are no views': 'Não existem visões', 'These files are served without processing, your images go here': 'These files are served without processing, your images go here', 'This is the %(filename)s template': 'Este é o template %(filename)s', 'Ticket': 'Ticket', 'Ticket ID': 'Ticket ID', 'Timestamp': 'Data Atual', 'To create a plugin, name a file/folder plugin_[name]': 'Para criar um plugin, nomeio um arquivo/pasta como plugin_[nome]', 'Traceback': 'Traceback', 'Translation strings for the application': 'Translation strings for the application', 'Unable to check for upgrades': 'Não é possível checar as atualizações', 'Unable to download': 'Não é possível efetuar o download', 'Unable to download app': 'Não é possível baixar a aplicação', 'Unable to download app because:': 'Não é possível baixar a aplicação porque:', 'Unable to download because': 'Não é possível baixar porque', 'Update:': 'Atualizar:', 'Upload & install packed application': 'Faça upload e instale uma aplicação empacotada', 'Upload a package:': 'Faça upload de um pacote:', 'Upload existing application': 'Faça upload de uma aplicação existente', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Use (...)&(...) para AND, (...)|(...) para OR, y ~(...) para NOT, para criar consultas mais complexas.', 'Use an url:': 'Use uma url:', 'User ID': 'ID do Usuario', 'Version': 'Versão', 'Views': 'Visões', 'Welcome to web2py': 'Bem-vindo ao web2py', 'YES': 'SIM', 'about': 'sobre', 'additional code for your application': 'código adicional para sua aplicação', 'admin disabled because no admin password': ' admin desabilitado por falta de senha definida', 'admin disabled because not supported on google app engine': 'admin dehabilitado, não é soportado no GAE', 'admin disabled because unable to access password file': 'admin desabilitado, não foi possível ler o arquivo de senha', 'administrative interface': 'interface administrativa', 'and rename it (required):': 'e renomeie (requerido):', 'and rename it:': ' e renomeie:', 'appadmin': 'appadmin', 'appadmin is disabled because insecure channel': 'admin desabilitado, canal inseguro', 'application "%s" uninstalled': 'aplicação "%s" desinstalada', 'application compiled': 'aplicação compilada', 'application is compiled and cannot be designed': 'A aplicação está compilada e não pode ser modificada', 'arguments': 'argumentos', 'back': 'voltar', 'browse': 'buscar', 'cache': 'cache', 'cache, errors and sessions cleaned': 'cache, erros e sessões eliminadas', 'cannot create file': 'Não é possível criar o arquivo', 'cannot upload file "%(filename)s"': 'não é possível fazer upload do arquivo "%(filename)s"', 'change admin password': 'mudar senha de administrador', 'check all': 'marcar todos', 'check for upgrades': 'checar por atualizações', 'clean': 'limpar', 'click here for online examples': 'clique para ver exemplos online', 'click here for the administrative interface': 'Clique aqui para acessar a interface administrativa', 'click to check for upgrades': 'clique aqui para checar por atualizações', 'click to open': 'clique para abrir', 'code': 'código', 'collapse/expand all': 'collapse/expand all', 'commit (mercurial)': 'commit (mercurial)', 'compile': 'compilar', 'compiled application removed': 'aplicação compilada removida', 'controllers': 'controladores', 'create': 'criar', 'create file with filename:': 'criar um arquivo com o nome:', 'create new application:': 'nome da nova aplicação:', 'created by': 'criado por', 'crontab': 'crontab', 'currently running': 'Executando', 'currently saved or': 'Atualmente salvo ou', 'customize me!': 'Modifique-me', 'data uploaded': 'Dados enviados', 'database': 'banco de dados', 'database %s select': 'Seleção no banco de dados %s', 'database administration': 'administração de banco de dados', 'db': 'db', 'defines tables': 'define as tabelas', 'delete': 'apagar', 'delete all checked': 'apagar marcados', 'delete plugin': 'apagar plugin', 'deploy': 'publicar', 'design': 'modificar', 'direction: ltr': 'direção: ltr', 'done!': 'feito!', 'download layouts': 'download layouts', 'download plugins': 'download plugins', 'edit': 'editar', 'edit controller': 'editar controlador', 'edit views:': 'editar visões:', 'errors': 'erros', 'export as csv file': 'exportar como arquivo CSV', 'exposes': 'expõe', 'extends': 'estende', 'failed to reload module': 'Falha ao recarregar o módulo', 'failed to reload module because:': 'falha ao recarregar o módulo por:', 'file "%(filename)s" created': 'arquivo "%(filename)s" criado', 'file "%(filename)s" deleted': 'arquivo "%(filename)s" apagado', 'file "%(filename)s" uploaded': 'arquivo "%(filename)s" enviado', 'file "%(filename)s" was not deleted': 'arquivo "%(filename)s" não foi apagado', 'file "%s" of %s restored': 'arquivo "%s" de %s restaurado', 'file changed on disk': 'arquivo modificado no disco', 'file does not exist': 'arquivo não existe', 'file saved on %(time)s': 'arquivo salvo em %(time)s', 'file saved on %s': 'arquivo salvo em %s', 'files': 'files', 'filter': 'filter', 'help': 'ajuda', 'htmledit': 'htmledit', 'includes': 'inclui', 'insert new': 'inserir novo', 'insert new %s': 'inserir novo %s', 'inspect attributes': 'inspect attributes', 'install': 'instalar', 'internal error': 'erro interno', 'invalid password': 'senha inválida', 'invalid request': 'solicitação inválida', 'invalid ticket': 'ticket inválido', 'language file "%(filename)s" created/updated': 'arquivo de linguagem "%(filename)s" criado/atualizado', 'languages': 'linguagens', 'languages updated': 'linguagens atualizadas', 'loading...': 'carregando...', 'locals': 'locals', 'login': 'inicio de sessão', 'logout': 'finalizar sessão', 'manage': 'gerenciar', 'merge': 'juntar', 'models': 'modelos', 'modules': 'módulos', 'new application "%s" created': 'nova aplicação "%s" criada', 'new plugin installed': 'novo plugin instalado', 'new record inserted': 'novo registro inserido', 'next 100 rows': 'próximos 100 registros', 'no match': 'não encontrado', 'or import from csv file': 'ou importar de um arquivo CSV', 'or provide app url:': 'ou forneça a url de uma aplicação:', 'or provide application url:': 'ou forneça a url de uma aplicação:', 'overwrite installed app': 'sobrescrever aplicação instalada', 'pack all': 'criar pacote', 'pack compiled': 'criar pacote compilado', 'pack plugin': 'empacotar plugin', 'password changed': 'senha alterada', 'plugin "%(plugin)s" deleted': 'plugin "%(plugin)s" eliminado', 'plugins': 'plugins', 'previous 100 rows': '100 registros anteriores', 'record': 'registro', 'record does not exist': 'o registro não existe', 'record id': 'id do registro', 'remove compiled': 'eliminar compilados', 'request': 'request', 'response': 'response', 'restore': 'restaurar', 'revert': 'reverter', 'save': 'salvar', 'selected': 'selecionado(s)', 'session': 'session', 'session expired': 'sessão expirada', 'shell': 'Terminal', 'site': 'site', 'some files could not be removed': 'alguns arquicos não puderam ser removidos', 'start wizard': 'iniciar assistente', 'state': 'estado', 'static': 'estáticos', 'submit': 'enviar', 'table': 'tabela', 'test': 'testar', 'the application logic, each URL path is mapped in one exposed function in the controller': 'A lógica da aplicação, cada URL é mapeada para uma função exposta pelo controlador', 'the data representation, define database tables and sets': 'A representação dos dadps, define tabelas e estruturas de dados', 'the presentations layer, views are also known as templates': 'A camada de apresentação, As visões também são chamadas de templates', 'these files are served without processing, your images go here': 'Estes arquivos são servidos sem processamento, suas imagens ficam aqui', 'to previous version.': 'para a versão anterior.', 'translation strings for the application': 'textos traduzidos para a aplicação', 'try': 'tente', 'try something like': 'tente algo como', 'unable to create application "%s"': 'não é possível criar a aplicação "%s"', 'unable to delete file "%(filename)s"': 'não é possível criar o arquico "%(filename)s"', 'unable to delete file plugin "%(plugin)s"': 'não é possível criar o plugin "%(plugin)s"', 'unable to parse csv file': 'não é possível analisar o arquivo CSV', 'unable to uninstall "%s"': 'não é possível instalar "%s"', 'unable to upgrade because "%s"': 'não é possível atualizar porque "%s"', 'uncheck all': 'desmarcar todos', 'uninstall': 'desinstalar', 'update': 'atualizar', 'update all languages': 'atualizar todas as linguagens', 'upgrade web2py now': 'atualize o web2py agora', 'upload': 'upload', 'upload application:': 'Fazer upload de uma aplicação:', 'upload file:': 'Enviar arquivo:', 'upload plugin file:': 'Enviar arquivo de plugin:', 'variables': 'variáveis', 'versioning': 'versionamento', 'view': 'visão', 'views': 'visões', 'web2py Recent Tweets': 'Tweets Recentes de @web2py', 'web2py is up to date': 'web2py está atualizado', 'web2py upgraded; please restart it': 'web2py atualizado; favor reiniciar', }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"更新" 是選擇性的條件式, 格式就像 "欄位1=\'值\'". 但是 JOIN 的資料不可以使用 update 或是 delete"', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s rows deleted': '已刪除 %s 筆', '%s rows updated': '已更新 %s 筆', '(something like "it-it")': '(格式類似 "zh-tw")', 'A new version of web2py is available': '新版的 web2py 已發行', 'A new version of web2py is available: %s': '新版的 web2py 已發行: %s', 'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.': '注意: 登入管理帳號需要安全連線(HTTPS)或是在本機連線(localhost).', 'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.': '注意: 因為在測試模式不保證多執行緒安全性,也就是說不可以同時執行多個測試案例', 'ATTENTION: you cannot edit the running application!': '注意:不可編輯正在執行的應用程式!', 'About': '關於', 'About application': '關於本應用程式', 'Admin is disabled because insecure channel': '管理功能(Admin)在不安全連線環境下自動關閉', 'Admin is disabled because unsecure channel': '管理功能(Admin)在不安全連線環境下自動關閉', 'Administrator Password:': '管理員密碼:', 'Are you sure you want to delete file "%s"?': '確定要刪除檔案"%s"?', 'Are you sure you want to delete plugin "%s"?': '確定要刪除插件 "%s"?', 'Are you sure you want to uninstall application "%s"': '確定要移除應用程式 "%s"', 'Are you sure you want to uninstall application "%s"?': '確定要移除應用程式 "%s"', 'Are you sure you want to upgrade web2py now?': '確定現在要升級 web2py?', 'Authentication': '驗證', 'Available databases and tables': '可提供的資料庫和資料表', 'Cannot be empty': '不可空白', 'Cannot compile: there are errors in your app. Debug it, correct errors and try again.': '無法編譯:應用程式中含有錯誤,請除錯後再試一次.', 'Cannot compile: there are errors in your app:': '無法編譯: 在你的應用程式存在錯誤:', 'Change Password': '變更密碼', 'Check to delete': '打勾代表刪除', 'Check to delete:': '打勾代表刪除:', 'Checking for upgrades...': '檢查新版本中...', 'Client IP': '客戶端網址(IP)', 'Controller': '控件', 'Controllers': '控件', 'Copyright': '版權所有', 'Create new simple application': '創建應用程式', 'Current request': '目前網路資料要求(request)', 'Current response': '目前網路資料回應(response)', 'Current session': '目前網路連線資訊(session)', 'DB Model': '資料庫模組', 'DESIGN': '設計', 'Database': '資料庫', 'Date and Time': '日期和時間', 'Delete': '刪除', 'Delete:': '刪除:', 'Deploy on Google App Engine': '配置到 Google App Engine', 'Description': '描述', 'Design for': '設計為了', 'E-mail': '電子郵件', 'EDIT': '編輯', 'Edit': '編輯', 'Edit Profile': '編輯設定檔', 'Edit This App': '編輯本應用程式', 'Edit application': '編輯應用程式', 'Edit current record': '編輯當前紀錄', 'Editing Language file': '編輯語言檔案', 'Editing file': '編輯檔案', 'Editing file "%s"': '編輯檔案"%s"', 'Enterprise Web Framework': '企業網站平台', 'Error logs for "%(app)s"': '"%(app)s"的錯誤紀錄', 'Exception instance attributes': 'Exception instance attributes', 'First name': '名', 'Functions with no doctests will result in [passed] tests.': '沒有 doctests 的函式會顯示 [passed].', 'Group ID': '群組編號', 'Hello World': '嗨! 世界', 'If the report above contains a ticket number it indicates a failure in executing the controller, before any attempt to execute the doctests. This is usually due to an indentation error or an error outside function code.\nA green title indicates that all tests (if defined) passed. In this case test results are not shown.': 'If the report above contains a ticket number it indicates a failure in executing the controller, before any attempt to execute the doctests. This is usually due to an indentation error or an error outside function code.\nA green title indicates that all tests (if defined) passed. In this case test results are not shown.', 'Import/Export': '匯入/匯出', 'Index': '索引', 'Installed applications': '已安裝應用程式', 'Internal State': '內部狀態', 'Invalid Query': '不合法的查詢', 'Invalid action': '不合法的動作(action)', 'Invalid email': '不合法的電子郵件', 'Language files (static strings) updated': '語言檔已更新', 'Languages': '各國語言', 'Last name': '姓', 'Last saved on:': '最後儲存時間:', 'Layout': '網頁配置', 'License for': '許可證', 'Login': '登入', 'Login to the Administrative Interface': '登入到管理員介面', 'Logout': '登出', 'Lost Password': '密碼遺忘', 'Main Menu': '主選單', 'Menu Model': '選單模組(menu)', 'Models': '資料模組', 'Modules': '程式模組', 'NO': '否', 'Name': '名字', 'New Record': '新紀錄', 'No databases in this application': '這應用程式不含資料庫', 'Origin': '原文', 'Original/Translation': '原文/翻譯', 'PAM authenticated user, cannot change password here': 'PAM 授權使用者, 無法在此變更密碼', 'Password': '密碼', "Password fields don't match": '密碼欄不匹配', 'Peeking at file': '選個文件', 'Plugin "%s" in application': '在應用程式的插件 "%s"', 'Plugins': '插件', 'Powered by': '基於以下技術構建:', 'Query:': '查詢:', 'Record ID': '紀錄編號', 'Register': '註冊', 'Registration key': '註冊金鑰', 'Remember me (for 30 days)': '記住帳號(30 天)', 'Reset Password key': '重設密碼', 'Resolve Conflict file': '解決衝突檔案', 'Role': '角色', 'Rows in table': '在資料表裏的資料', 'Rows selected': '筆資料被選擇', 'Saved file hash:': '檔案雜湊值已紀錄:', 'Static files': '靜態檔案', 'Stylesheet': '網頁風格檔', 'Submit': '傳送', 'Sure you want to delete this object?': '確定要刪除此物件?', 'TM': 'TM', 'Table name': '資料表名稱', 'Testing application': '測試中的應用程式', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': '"查詢"是一個像 "db.表1.欄位1==\'值\'" 的條件式. 以"db.表1.欄位1==db.表2.欄位2"方式則相當於執行 JOIN SQL.', 'There are no controllers': '沒有控件(controllers)', 'There are no models': '沒有資料庫模組(models)', 'There are no modules': '沒有程式模組(modules)', 'There are no static files': '沒有靜態檔案', 'There are no translators, only default language is supported': '沒有翻譯檔,只支援原始語言', 'There are no views': '沒有視圖', 'This is the %(filename)s template': '這是%(filename)s檔案的樣板(template)', 'Ticket': '問題單', 'Timestamp': '時間標記', 'To create a plugin, name a file/folder plugin_[name]': '檔案或目錄名稱以 plugin_開頭來創建插件', 'Unable to check for upgrades': '無法做升級檢查', 'Unable to download': '無法下載', 'Unable to download app': '無法下載應用程式', 'Unable to download app because:': '無法下載應用程式因為:', 'Unable to download because': '因為下列原因無法下載:', 'Update:': '更新:', 'Upload & install packed application': '上傳並安裝已打包的應用程式', 'Upload existing application': '更新存在的應用程式', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': '使用下列方式來組合更複雜的條件式, (...)&(...) 代表同時存在的條件, (...)|(...) 代表擇一的條件, ~(...)則代表反向條件.', 'User %(id)s Logged-in': '使用者 %(id)s 已登入', 'User %(id)s Registered': '使用者 %(id)s 已註冊', 'User ID': '使用者編號', 'Verify Password': '驗證密碼', 'Version': '版本', 'View': '視圖', 'Views': '視圖', 'Welcome %s': '歡迎 %s', 'Welcome to web2py': '歡迎使用 web2py', 'YES': '是', 'about': '關於', 'additional code for your application': '應用程式額外的程式碼', 'admin disabled because no admin password': '管理介面關閉原因是沒有設定管理員密碼 ', 'admin disabled because not supported on google app engine': '管理介面關閉原因是不支援在google apps engine環境下運作', 'admin disabled because unable to access password file': '管理介面關閉原因是無法存取密碼檔', 'amy_ajax': 'amy_ajax', 'and rename it (required):': '同時更名為(必要的):', 'and rename it:': '同時更名為:', 'appadmin': '應用程式管理員', 'appadmin is disabled because insecure channel': '管理介面關閉理由是連線方式不安全', 'application "%s" uninstalled': '已移除應用程式 "%s"', 'application compiled': '已編譯應用程式', 'application is compiled and cannot be designed': '應用程式已經編譯無法重新設計', 'arguments': 'arguments', 'back': '回復(back)', 'cache': '快取記憶體', 'cache, errors and sessions cleaned': '快取記憶體,錯誤紀錄,連線紀錄已清除', 'cannot create file': '無法創建檔案', 'cannot upload file "%(filename)s"': '無法上傳檔案 "%(filename)s"', 'change admin password': 'change admin password', 'change_password': '變更密碼', 'check all': '全選', 'clean': '清除', 'click here for online examples': '點此處進入線上範例', 'click here for the administrative interface': '點此處進入管理介面', 'click to check for upgrades': '點擊打勾以便升級', 'code': 'code', 'compile': '編譯', 'compiled application removed': '已移除已編譯的應用程式', 'controllers': '控件', 'create': '創建', 'create file with filename:': '創建檔案:', 'create new application:': '創建新應用程式:', 'created by': '創建自', 'crontab': '定時執行表', 'currently saved or': '現在存檔或', 'customize me!': '請調整我!', 'data uploaded': '資料已上傳', 'database': '資料庫', 'database %s select': '已選擇 %s 資料庫', 'database administration': '資料庫管理', 'db': 'db', 'defines tables': '定義資料表', 'delete': '刪除', 'delete all checked': '刪除所有已選擇項目', 'delete plugin': '刪除插件', 'delete_plugin': '刪除插件', 'design': '設計', 'direction: ltr': 'direction: ltr', 'done!': '完成!', 'edit': '編輯', 'edit controller': '編輯控件', 'edit views:': '編輯視圖', 'edit_language': '編輯語言檔', 'errors': '錯誤紀錄', 'export as csv file': '以逗號分隔檔(csv)格式匯出', 'exposes': '外顯', 'extends': '擴展', 'failed to reload module because:': '因為下列原因無法重新載入程式模組:', 'file "%(filename)s" created': '檔案 "%(filename)s" 已創建', 'file "%(filename)s" deleted': '檔案 "%(filename)s" 已刪除', 'file "%(filename)s" uploaded': '檔案 "%(filename)s" 已上傳', 'file "%s" of %s restored': '檔案 %s 的 "%s" 已回存', 'file changed on disk': '在磁碟上檔案已改變', 'file does not exist': '檔案不存在', 'file saved on %(time)s': '檔案已於 %(time)s 儲存', 'file saved on %s': '檔案在 %s 已儲存', 'help': '說明檔', 'htmledit': 'html編輯', 'includes': '包含', 'index': '索引', 'insert new': '插入新資料', 'insert new %s': '插入新資料 %s', 'install': '安裝', 'internal error': '內部錯誤', 'invalid password': '密碼錯誤', 'invalid request': '不合法的網路要求(request)', 'invalid ticket': '不合法的問題單號', 'language file "%(filename)s" created/updated': '語言檔"%(filename)s"已創建或更新', 'languages': '語言檔', 'loading...': '載入中...', 'login': '登入', 'logout': '登出', 'merge': '合併', 'models': '資料庫模組', 'modules': '程式模組', 'new application "%s" created': '已創建新的應用程式 "%s"', 'new plugin installed': '已安裝新插件', 'new record inserted': '已新增新紀錄', 'next 100 rows': '往後 100 筆', 'no match': '無法匹配', 'or import from csv file': '或是從逗號分隔檔(CSV)匯入', 'or provide app url:': '或是提供應用程式的安裝網址:', 'overwrite installed app': '覆蓋已安裝的應用程式', 'pack all': '全部打包', 'pack compiled': '打包已編譯資料', 'pack plugin': '打包插件', 'password changed': '密碼已變更', 'peek': '選取', 'plugin': '插件', 'plugin "%(plugin)s" deleted': '已刪除插件"%(plugin)s"', 'previous 100 rows': '往前 100 筆', 'record': '紀錄', 'record does not exist': '紀錄不存在', 'record id': '紀錄編號', 'register': '註冊', 'remove compiled': '編譯檔案已移除', 'resolve': '解決', 'restore': '回存', 'revert': '反向恢復', 'save': '儲存', 'selected': '已選擇', 'session expired': '連線(session)已過時', 'shell': '命令列操作介面', 'site': '網站', 'some files could not be removed': '部份檔案無法移除', 'state': '狀態', 'static': '靜態檔案', 'submit': '傳送', 'table': '資料表', 'test': '測試', 'the application logic, each URL path is mapped in one exposed function in the controller': '應用程式邏輯 - 每個網址路徑對應到一個控件的函式', 'the data representation, define database tables and sets': '資料展現層 - 用來定義資料表和集合', 'the presentations layer, views are also known as templates': '外觀展現層 - 視圖有時也被稱為樣板', 'these files are served without processing, your images go here': '這些檔案保留未經處理,你的影像檔在此', 'ticket': '問題單', 'to previous version.': '到前一個版本', 'translation strings for the application': '翻譯此應用程式的字串', 'try': '嘗試', 'try something like': '嘗試如', 'unable to create application "%s"': '無法創建應用程式 "%s"', 'unable to delete file "%(filename)s"': '無法刪除檔案 "%(filename)s"', 'unable to delete file plugin "%(plugin)s"': '無法刪查插件檔 "%(plugin)s"', 'unable to parse csv file': '無法解析逗號分隔檔(csv)', 'unable to uninstall "%s"': '無法移除安裝 "%s"', 'unable to upgrade because "%s"': '無法升級因為 "%s"', 'uncheck all': '全不選', 'uninstall': '解除安裝', 'update': '更新', 'update all languages': '將程式中待翻譯語句更新到所有的語言檔', 'upgrade web2py now': 'upgrade web2py now', 'upgrade_web2py': '升級 web2py', 'upload application:': '上傳應用程式:', 'upload file:': '上傳檔案:', 'upload plugin file:': '上傳插件檔:', 'variables': 'variables', 'versioning': '版本管理', 'view': '視圖', 'views': '視圖', 'web2py Recent Tweets': 'web2py 最近的 Tweets', 'web2py is up to date': 'web2py 已經是最新版', 'web2py upgraded; please restart it': '已升級 web2py ; 請重新啟動', }
Python
# coding: utf8 { '"browse"': '游览', '"save"': '"保存"', '"submit"': '"提交"', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"更新"是可配置项 如 "field1=\'newvalue\'",你无法在JOIN 中更新或删除', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s rows deleted': '%s 行已删', '%s rows updated': '%s 行更新', '(requires internet access)': '(requires internet access)', '(something like "it-it")': '(就酱 "it-it")', 'A new version of web2py is available': '新版本web2py已经可用', 'A new version of web2py is available: %s': '新版本web2py已经可用: %s', 'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.': '', 'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.': '', 'ATTENTION: you cannot edit the running application!': '注意: 不能修改正在运行中的应用!', 'About': '关于', 'About application': '关于这个应用', 'Admin is disabled because insecure channel': '管理因不安全通道而关闭', 'Admin is disabled because unsecure channel': '管理因不稳定通道而关闭', 'Admin language': 'Admin language', 'Administrator Password:': '管理员密码:', 'Application name:': 'Application name:', 'Are you sure you want to delete file "%s"?': '你真想删除文件"%s"?', 'Are you sure you want to delete plugin "%s"?': 'Are you sure you want to delete plugin "%s"?', 'Are you sure you want to uninstall application "%s"': '你真确定要卸载应用 "%s"', 'Are you sure you want to uninstall application "%s"?': '你真确定要卸载应用 "%s" ?', 'Are you sure you want to upgrade web2py now?': 'Are you sure you want to upgrade web2py now?', 'Available databases and tables': '可用数据库/表', 'Cannot be empty': '不能不填', 'Cannot compile: there are errors in your app.        Debug it, correct errors and try again.': '无法编译: 应用中有错误,请修订后再试.', 'Cannot compile: there are errors in your app:': 'Cannot compile: there are errors in your app:', 'Change Password': '修改密码', 'Check to delete': '检验删除', 'Checking for upgrades...': '是否有升级版本检查ing...', 'Client IP': '客户端IP', 'Controllers': '控制器s', 'Create new simple application': '创建一个新应用', 'Current request': '当前请求', 'Current response': '当前返回', 'Current session': '当前会话', 'DESIGN': '设计', 'Date and Time': '时间日期', 'Delete': '删除', 'Delete:': '删除:', 'Deploy on Google App Engine': '部署到GAE', 'Description': '描述', 'Design for': '设计:', 'E-mail': '邮箱:', 'EDIT': '编辑', 'Edit Profile': '修订配置', 'Edit application': '修订应用', 'Edit current record': '修订当前记录', 'Editing Language file': '修订语言文件', 'Editing file': '修订文件', 'Editing file "%s"': '修订文件 %s', 'Enterprise Web Framework': '强悍的网络开发框架', 'Error logs for "%(app)s"': '"%(app)s" 的错误日志', 'Exception instance attributes': 'Exception instance attributes', 'First name': '姓', 'Functions with no doctests will result in [passed] tests.': '', 'Group ID': '组ID', 'Hello World': '道可道,非常道;名可名,非常名', 'If the report above contains a ticket number it indicates a failure in executing the controller, before any attempt to execute the doctests. This is usually due to an indentation error or an error outside function code.\nA green title indicates that all tests (if defined) passed. In this case test results are not shown.': 'If the report above contains a ticket number it indicates a failure in executing the controller, before any attempt to execute the doctests. This is usually due to an indentation error or an error outside function code.\nA green title indicates that all tests (if defined) passed. In this case test results are not shown.', 'Import/Export': '导入/导出', 'Installed applications': '已安装的应用', 'Internal State': '内部状态', 'Invalid Query': '无效查询', 'Invalid action': '无效动作', 'Invalid email': '无效的email', 'Language files (static strings) updated': '语言文件(静态部分)已更新', 'Languages': '语言', 'Last name': '名', 'Last saved on:': '最后保存于:', 'License for': '许可证', 'Login': '登录', 'Login to the Administrative Interface': '登录到管理员界面', 'Logout': '注销', 'Lost Password': '忘记密码', 'Models': '模型s', 'Modules': '模块s', 'NO': '不', 'Name': '姓名', 'New Record': '新记录', 'New application wizard': 'New application wizard', 'New simple application': 'New simple application', 'No databases in this application': '这应用没有数据库', 'Origin': '起源', 'Original/Translation': '原始文件/翻译文件', 'PAM authenticated user, cannot change password here': 'PAM authenticated user, cannot change password here', 'Password': '密码', 'Peeking at file': '选个文件', 'Plugin "%s" in application': 'Plugin "%s" in application', 'Plugins': 'Plugins', 'Powered by': '', 'Query:': '查询', 'Record ID': '记录ID', 'Register': '注册', 'Registration key': '注册密匙', 'Resolve Conflict file': '解决冲突文件', 'Role': '角色', 'Rows in table': '表行', 'Rows selected': '行选择', 'Saved file hash:': '已存文件Hash:', 'Static files': '静态文件', 'Sure you want to delete this object?': '真的要删除这个对象?', 'TM': '', 'Table name': '表名', 'Testing application': '应用测试', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': '', 'There are no controllers': '冇控制器', 'There are no models': '冇模型s', 'There are no modules': '冇模块s', 'There are no static files': '冇静态文件', 'There are no translators, only default language is supported': '没有找到相应翻译,只能使用默认语言', 'There are no views': '冇视图', 'This is the %(filename)s template': '这是 %(filename)s 模板', 'Ticket': '传票', 'Timestamp': '时间戳', 'To create a plugin, name a file/folder plugin_[name]': 'To create a plugin, name a file/folder plugin_[name]', 'Unable to check for upgrades': '无法检查是否需要升级', 'Unable to download': '无法下载', 'Unable to download app': '无法下载应用', 'Unable to download app because:': 'Unable to download app because:', 'Unable to download because': 'Unable to download because', 'Update:': '更新:', 'Upload & install packed application': 'Upload & install packed application', 'Upload a package:': 'Upload a package:', 'Upload existing application': '上传已有应用', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...)  for NOT to build more complex queries.': '', 'Use an url:': 'Use an url:', 'User ID': '用户ID', 'Version': '版本', 'Views': '视图', 'Welcome to web2py': '欢迎使用web2py', 'YES': '是', 'about': '关于', 'additional code for your application': '给你的应用附加代码', 'admin disabled because no admin password': '管理员需要设定密码,否则无法管理', 'admin disabled because not supported on google app engine': '未支持GAE,无法管理', 'admin disabled because unable to access password file': '需要可以操作密码文件,否则无法进行管理', 'administrative interface': 'administrative interface', 'and rename it (required):': '重命名为 (必须):', 'and rename it:': ' 重命名为:', 'appadmin': '应用管理', 'appadmin is disabled because insecure channel': '应用管理因非法通道失效', 'application "%s" uninstalled': '应用"%s" 已被卸载', 'application compiled': '应用已编译完', 'application is compiled and cannot be designed': '应用已编译完无法设计', 'arguments': 'arguments', 'back': 'back', 'cache': 'cache', 'cache, errors and sessions cleaned': '缓存、错误、sesiones已被清空', 'cannot create file': '无法创建文件', 'cannot upload file "%(filename)s"': '无法上传文件 "%(filename)s"', 'change admin password': 'change admin password', 'check all': '检查所有', 'check for upgrades': 'check for upgrades', 'clean': '清除', 'click here for online examples': '猛击此处,查看在线实例', 'click here for the administrative interface': '猛击此处,进入管理界面', 'click to check for upgrades': '猛击查看是否有升级版本', 'code': 'code', 'compile': '编译', 'compiled application removed': '已编译应用已移走', 'controllers': '控制器', 'create': 'create', 'create file with filename:': '创建文件用这名:', 'create new application:': '创建新应用:', 'created by': '创建自', 'crontab': '定期事务', 'currently running': 'currently running', 'currently saved or': '保存当前的或', 'customize me!': '定制俺!', 'data uploaded': '数据已上传', 'database': '数据库', 'database %s select': '数据库 %s 选择', 'database administration': '数据库管理', 'db': '', 'defines tables': '已定义表', 'delete': '删除', 'delete all checked': '删除所有选择的', 'delete plugin': 'delete plugin', 'deploy': 'deploy', 'design': '设计', 'direction: ltr': 'direction: ltr', 'done!': '搞定!', 'edit': '修改', 'edit controller': '修订控制器', 'edit views:': 'edit views:', 'errors': '错误', 'export as csv file': '导出为CSV文件', 'exposes': '暴露', 'extends': '扩展', 'failed to reload module': '重新加载模块失败', 'failed to reload module because:': 'failed to reload module because:', 'file "%(filename)s" created': '文件 "%(filename)s" 已创建', 'file "%(filename)s" deleted': '文件 "%(filename)s" 已删除', 'file "%(filename)s" uploaded': '文件 "%(filename)s" 已上传', 'file "%(filename)s" was not deleted': '文件 "%(filename)s" 没删除', 'file "%s" of %s restored': '文件"%s" 有关 %s 已重存', 'file changed on disk': '硬盘上的文件已经修改', 'file does not exist': '文件并不存在', 'file saved on %(time)s': '文件保存于 %(time)s', 'file saved on %s': '文件保存在 %s', 'help': '帮助', 'htmledit': 'html编辑', 'includes': '包含', 'insert new': '新插入', 'insert new %s': '新插入 %s', 'install': 'install', 'internal error': '内部错误', 'invalid password': '无效密码', 'invalid request': '无效请求', 'invalid ticket': '无效传票', 'language file "%(filename)s" created/updated': '语言文件 "%(filename)s"被创建/更新', 'languages': '语言', 'languages updated': '语言已被刷新', 'loading...': '载入中...', 'login': '登录', 'logout': '注销', 'merge': '合并', 'models': '模型s', 'modules': '模块s', 'new application "%s" created': '新应用 "%s"已被创建', 'new plugin installed': 'new plugin installed', 'new record inserted': '新记录被插入', 'next 100 rows': '后100行', 'no match': 'no match', 'or import from csv file': '或者,从csv文件导入', 'or provide app url:': 'or provide app url:', 'or provide application url:': '或者,提供应用所在地址链接:', 'overwrite installed app': 'overwrite installed app', 'pack all': '全部打包', 'pack compiled': '包编译完', 'pack plugin': 'pack plugin', 'password changed': 'password changed', 'plugin "%(plugin)s" deleted': 'plugin "%(plugin)s" deleted', 'previous 100 rows': '前100行', 'record': 'record', 'record does not exist': '记录并不存在', 'record id': '记录ID', 'remove compiled': '已移除', 'restore': '重存', 'revert': '恢复', 'save': '保存', 'selected': '已选', 'session expired': '会话过期', 'shell': '', 'site': '总站', 'some files could not be removed': '有些文件无法被移除', 'start wizard': 'start wizard', 'state': '状态', 'static': '静态文件', 'submit': '提交', 'table': '表', 'test': '测试', 'the application logic, each URL path is mapped in one exposed function in the controller': '应用逻辑:每个URL由控制器暴露的函式完成映射', 'the data representation, define database tables and sets': '数据表达式,定义数据库/表', 'the presentations layer, views are also known as templates': '提交层/视图都在模板中可知', 'these files are served without processing, your images go here': '', 'to previous version.': 'to previous version.', 'to  previous version.': '退回前一版本', 'translation strings for the application': '应用的翻译字串', 'try': '尝试', 'try something like': '尝试', 'unable to create application "%s"': '无法创建应用 "%s"', 'unable to delete file "%(filename)s"': '无法删除文件 "%(filename)s"', 'unable to delete file plugin "%(plugin)s"': 'unable to delete file plugin "%(plugin)s"', 'unable to parse csv file': '无法生成 cvs', 'unable to uninstall "%s"': '无法卸载 "%s"', 'unable to upgrade because "%s"': 'unable to upgrade because "%s"', 'uncheck all': '反选全部', 'uninstall': '卸载', 'update': '更新', 'update all languages': '更新所有语言', 'upgrade web2py now': 'upgrade web2py now', 'upload application:': '提交已有的应用:', 'upload file:': '提交文件:', 'upload plugin file:': 'upload plugin file:', 'variables': 'variables', 'versioning': '版本', 'view': '视图', 'views': '视图s', 'web2py Recent Tweets': 'twitter上的web2py进展实播', 'web2py is up to date': 'web2py现在已经是最新的版本了', 'web2py upgraded; please restart it': 'web2py upgraded; please restart it', }
Python
# ########################################################### # ## generate menu # ########################################################### _a = request.application _c = request.controller _f = request.function response.title = '%s %s' % (_f, '/'.join(request.args)) response.subtitle = 'admin' response.menu = [(T('site'), _f == 'site', URL(_a,'default','site'))] if request.args: _t = request.args[0] response.menu.append((T('edit'), _c == 'default' and _f == 'design', URL(_a,'default','design',args=_t))) response.menu.append((T('about'), _c == 'default' and _f == 'about', URL(_a,'default','about',args=_t))) response.menu.append((T('errors'), _c == 'default' and _f == 'errors', URL(_a,'default','errors',args=_t))) response.menu.append((T('versioning'), _c == 'mercurial' and _f == 'commit', URL(_a,'mercurial','commit',args=_t))) if not session.authorized: response.menu = [(T('login'), True, '')] else: response.menu.append((T('logout'), False, URL(_a,'default',f='logout'))) response.menu.append((T('help'), False, URL('examples','default','index')))
Python
response.files.append(URL('static','plugin_multiselect/jquery.dimensions.js')) response.files.append(URL('static','plugin_multiselect/jquery.multiselect.js')) response.files.append(URL('static','plugin_multiselect/jquery.multiselect.css')) response.files.append(URL('static','plugin_multiselect/start.js'))
Python
EXPIRATION = 60 * 60 # logout after 60 minutes of inactivity CHECK_VERSION = True WEB2PY_URL = 'http://web2py.com' WEB2PY_VERSION_URL = WEB2PY_URL+'/examples/default/version' ########################################################################### # Preferences for EditArea # the user-interface feature that allows you to edit files in your web # browser. ## Default editor TEXT_EDITOR = 'edit_area' or 'amy' ### edit_area # The default font size, measured in 'points'. The value must be an integer > 0 FONT_SIZE = 10 # Displays the editor in full screen mode. The value must be 'true' or 'false' FULL_SCREEN = 'false' # Display a check box under the editor to allow the user to switch # between the editor and a simple # HTML text area. The value must be 'true' or 'false' ALLOW_TOGGLE = 'true' # Replaces tab characters with space characters. # The value can be 'false' (meaning that tabs are not replaced), # or an integer > 0 that specifies the number of spaces to replace a tab with. REPLACE_TAB_BY_SPACES = 4 # Toggle on/off the code editor instead of textarea on startup DISPLAY = "onload" or "later" # if demo mode is True then admin works readonly and does not require login DEMO_MODE = False # if visible_apps is not empty only listed apps will be accessible FILTER_APPS = [] # To upload on google app engine this has to point to the proper appengine # config file import os # extract google_appengine_x.x.x.zip to web2py root directory #GAE_APPCFG = os.path.abspath(os.path.join('appcfg.py')) # extract google_appengine_x.x.x.zip to applications/admin/private/ GAE_APPCFG = os.path.abspath(os.path.join('/usr/local/bin/appcfg.py')) # To use web2py as a teaching tool, set MULTI_USER_MODE to True MULTI_USER_MODE = False # configurable twitterbox, set to None/False to suppress TWITTER_HASH = "web2py" # parameter for downloading LAYOUTS LAYOUTS_APP = 'http://web2py.com/layouts' #LAYOUTS_APP = 'http://127.0.0.1:8000/layouts' # parameter for downloading PLUGINS PLUGINS_APP = 'http://web2py.com/plugins' #PLUGINS_APP = 'http://127.0.0.1:8000/plugins' # set the language if 'adminLanguage' in request.cookies and not (request.cookies['adminLanguage'] is None): T.force(request.cookies['adminLanguage'].value)
Python
import os, time from gluon import portalocker from gluon.admin import apath from gluon.fileutils import read_file # ########################################################### # ## make sure administrator is on localhost or https # ########################################################### http_host = request.env.http_host.split(':')[0] if request.env.web2py_runtime_gae: session_db = DAL('gae') session.connect(request, response, db=session_db) hosts = (http_host, ) if request.env.http_x_forwarded_for or request.is_https: session.secure() elif not request.is_local and not DEMO_MODE: raise HTTP(200, T('Admin is disabled because insecure channel')) try: _config = {} port = int(request.env.server_port or 0) restricted(read_file(apath('../parameters_%i.py' % port, request)), _config) if not 'password' in _config or not _config['password']: raise HTTP(200, T('admin disabled because no admin password')) except IOError: import gluon.fileutils if request.env.web2py_runtime_gae: if gluon.fileutils.check_credentials(request): session.authorized = True session.last_time = time.time() else: raise HTTP(200, T('admin disabled because not supported on google app engine')) else: raise HTTP(200, T('admin disabled because unable to access password file')) def verify_password(password): session.pam_user = None if DEMO_MODE: return True elif not 'password' in _config: return False elif _config['password'].startswith('pam_user:'): session.pam_user = _config['password'][9:].strip() import gluon.contrib.pam return gluon.contrib.pam.authenticate(session.pam_user,password) else: return _config['password'] == CRYPT()(password)[0] # ########################################################### # ## handle brute-force login attacks # ########################################################### deny_file = os.path.join(request.folder, 'private', 'hosts.deny') allowed_number_of_attempts = 5 expiration_failed_logins = 3600 def read_hosts_deny(): import datetime hosts = {} if os.path.exists(deny_file): hosts = {} f = open(deny_file, 'r') portalocker.lock(f, portalocker.LOCK_SH) for line in f.readlines(): if not line.strip() or line.startswith('#'): continue fields = line.strip().split() if len(fields) > 2: hosts[fields[0].strip()] = ( # ip int(fields[1].strip()), # n attemps int(fields[2].strip()) # last attempts ) portalocker.unlock(f) f.close() return hosts def write_hosts_deny(denied_hosts): f = open(deny_file, 'w') portalocker.lock(f, portalocker.LOCK_EX) for key, val in denied_hosts.items(): if time.time()-val[1] < expiration_failed_logins: line = '%s %s %s\n' % (key, val[0], val[1]) f.write(line) portalocker.unlock(f) f.close() def login_record(success=True): denied_hosts = read_hosts_deny() val = (0,0) if success and request.client in denied_hosts: del denied_hosts[request.client] elif not success and not request.is_local: val = denied_hosts.get(request.client,(0,0)) if time.time()-val[1]<expiration_failed_logins \ and val[0] >= allowed_number_of_attempts: return val[0] # locked out time.sleep(2**val[0]) val = (val[0]+1,int(time.time())) denied_hosts[request.client] = val write_hosts_deny(denied_hosts) return val[0] # ########################################################### # ## session expiration # ########################################################### t0 = time.time() if session.authorized: if session.last_time and session.last_time < t0 - EXPIRATION: session.flash = T('session expired') session.authorized = False else: session.last_time = t0 if not session.authorized and not \ (request.controller == 'default' and \ request.function in ('index','user')): if request.env.query_string: query_string = '?' + request.env.query_string else: query_string = '' if request.env.web2py_original_uri: url = request.env.web2py_original_uri else: url = request.env.path_info + query_string redirect(URL(request.application, 'default', 'index', vars=dict(send=url))) elif session.authorized and \ request.controller == 'default' and \ request.function == 'index': redirect(URL(request.application, 'default', 'site')) if request.controller=='appadmin' and DEMO_MODE: session.flash = 'Appadmin disabled in demo mode' redirect(URL('default','sites'))
Python
# Template helpers import os def button(href, label): return A(SPAN(label),_class='button',_href=href) def sp_button(href, label): return A(SPAN(label),_class='button special',_href=href) def helpicon(): return IMG(_src=URL('static', 'images/help.png'), _alt='help') def searchbox(elementid): return TAG[''](LABEL(IMG(_src=URL('static', 'images/search.png'), _alt=T('filter')), _class='icon', _for=elementid), ' ', INPUT(_id=elementid, _type='text', _size=12))
Python
# -*- coding: utf-8 -*- # this file is released under public domain and you can use without limitations if MULTI_USER_MODE: db = DAL('sqlite://storage.sqlite') # if not, use SQLite or other DB from gluon.tools import * mail = Mail() # mailer auth = Auth(globals(),db) # authentication/authorization crud = Crud(globals(),db) # for CRUD helpers using auth service = Service(globals()) # for json, xml, jsonrpc, xmlrpc, amfrpc plugins = PluginManager() mail.settings.server = 'logging' or 'smtp.gmail.com:587' # your SMTP server mail.settings.sender = 'you@gmail.com' # your email mail.settings.login = 'username:password' # your credentials or None auth.settings.hmac_key = '<your secret key>' # before define_tables() auth.define_tables() # creates all needed tables auth.settings.mailer = mail # for user email verification auth.settings.registration_requires_verification = False auth.settings.registration_requires_approval = True auth.messages.verify_email = 'Click on the link http://'+request.env.http_host+URL('default','user',args=['verify_email'])+'/%(key)s to verify your email' auth.settings.reset_password_requires_verification = True auth.messages.reset_password = 'Click on the link http://'+request.env.http_host+URL('default','user',args=['reset_password'])+'/%(key)s to reset your password' db.define_table('app',Field('name'),Field('owner',db.auth_user)) if not session.authorized and MULTI_USER_MODE: if auth.user and not request.function=='user': session.authorized = True elif not request.function=='user': redirect(URL('default','user/login')) def is_manager(): if not MULTI_USER_MODE: return True elif auth.user and auth.user.id==1: return True else: return False
Python
import time import os import sys import re import urllib import cgi import difflib import shutil import stat import socket from textwrap import dedent try: from mercurial import ui, hg, cmdutil have_mercurial = True except ImportError: have_mercurial = False from gluon.utils import md5_hash from gluon.fileutils import listdir, cleanpath, up from gluon.fileutils import tar, tar_compiled, untar, fix_newlines from gluon.languages import findT, update_all_languages from gluon.myregex import * from gluon.restricted import * from gluon.compileapp import compile_application, remove_compiled_application
Python
from gluon.fileutils import read_file, write_file if DEMO_MODE or MULTI_USER_MODE: session.flash = T('disabled in demo mode') redirect(URL('default','site')) if not have_mercurial: session.flash=T("Sorry, could not find mercurial installed") redirect(URL('default','design',args=request.args(0))) _hgignore_content = """\ syntax: glob *~ *.pyc *.pyo *.bak *.bak2 cache/* private/* uploads/* databases/* sessions/* errors/* """ def hg_repo(path): import os uio = ui.ui() uio.quiet = True if not os.environ.get('HGUSER') and not uio.config("ui", "username"): os.environ['HGUSER'] = 'web2py@localhost' try: repo = hg.repository(ui=uio, path=path) except: repo = hg.repository(ui=uio, path=path, create=True) hgignore = os.path.join(path, '.hgignore') if not os.path.exists(hgignore): write_file(hgignore, _hgignore_content) return repo def commit(): app = request.args(0) path = apath(app, r=request) repo = hg_repo(path) form = FORM('Comment:',INPUT(_name='comment',requires=IS_NOT_EMPTY()), INPUT(_type='submit',_value='Commit')) if form.accepts(request.vars,session): oldid = repo[repo.lookup('.')] cmdutil.addremove(repo) repo.commit(text=form.vars.comment) if repo[repo.lookup('.')] == oldid: response.flash = 'no changes' try: files = TABLE(*[TR(file) for file in repo[repo.lookup('.')].files()]) changes = TABLE(TR(TH('revision'),TH('description'))) for change in repo.changelog: ctx=repo.changectx(change) revision, description = ctx.rev(), ctx.description() changes.append(TR(A(revision,_href=URL('revision', args=(app,revision))), description)) except: files = [] changes = [] return dict(form=form,files=files,changes=changes,repo=repo) def revision(): app = request.args(0) path = apath(app, r=request) repo = hg_repo(path) revision = request.args(1) ctx=repo.changectx(revision) form=FORM(INPUT(_type='submit',_value='revert')) if form.accepts(request.vars): hg.update(repo, revision) session.flash = "reverted to revision %s" % ctx.rev() redirect(URL('default','design',args=app)) return dict( files=ctx.files(), rev=str(ctx.rev()), desc=ctx.description(), form=form )
Python
# -*- coding: utf-8 -*- # ########################################################## # ## make sure administrator is on localhost # ########################################################### import os import socket import datetime import copy import gluon.contenttype import gluon.fileutils # ## critical --- make a copy of the environment global_env = copy.copy(globals()) global_env['datetime'] = datetime http_host = request.env.http_host.split(':')[0] remote_addr = request.env.remote_addr try: hosts = (http_host, socket.gethostname(), socket.gethostbyname(http_host), '::1','127.0.0.1','::ffff:127.0.0.1') except: hosts = (http_host, ) if request.env.http_x_forwarded_for or request.env.wsgi_url_scheme\ in ['https', 'HTTPS']: session.secure() elif (remote_addr not in hosts) and (remote_addr != "127.0.0.1"): raise HTTP(200, T('appadmin is disabled because insecure channel')) if (request.application=='admin' and not session.authorized) or \ (request.application!='admin' and not gluon.fileutils.check_credentials(request)): redirect(URL('admin', 'default', 'index')) ignore_rw = True response.view = 'appadmin.html' response.menu = [[T('design'), False, URL('admin', 'default', 'design', args=[request.application])], [T('db'), False, URL('index')], [T('state'), False, URL('state')], [T('cache'), False, URL('ccache')]] # ########################################################## # ## auxiliary functions # ########################################################### def get_databases(request): dbs = {} for (key, value) in global_env.items(): cond = False try: cond = isinstance(value, GQLDB) except: cond = isinstance(value, SQLDB) if cond: dbs[key] = value return dbs databases = get_databases(None) def eval_in_global_env(text): exec ('_ret=%s' % text, {}, global_env) return global_env['_ret'] def get_database(request): if request.args and request.args[0] in databases: return eval_in_global_env(request.args[0]) else: session.flash = T('invalid request') redirect(URL('index')) def get_table(request): db = get_database(request) if len(request.args) > 1 and request.args[1] in db.tables: return (db, request.args[1]) else: session.flash = T('invalid request') redirect(URL('index')) def get_query(request): try: return eval_in_global_env(request.vars.query) except Exception: return None def query_by_table_type(tablename,db,request=request): keyed = hasattr(db[tablename],'_primarykey') if keyed: firstkey = db[tablename][db[tablename]._primarykey[0]] cond = '>0' if firstkey.type in ['string', 'text']: cond = '!=""' qry = '%s.%s.%s%s' % (request.args[0], request.args[1], firstkey.name, cond) else: qry = '%s.%s.id>0' % tuple(request.args[:2]) return qry # ########################################################## # ## list all databases and tables # ########################################################### def index(): return dict(databases=databases) # ########################################################## # ## insert a new record # ########################################################### def insert(): (db, table) = get_table(request) form = SQLFORM(db[table], ignore_rw=ignore_rw) if form.accepts(request.vars, session): response.flash = T('new record inserted') return dict(form=form,table=db[table]) # ########################################################## # ## list all records in table and insert new record # ########################################################### def download(): import os db = get_database(request) return response.download(request,db) def csv(): import gluon.contenttype response.headers['Content-Type'] = \ gluon.contenttype.contenttype('.csv') db = get_database(request) query = get_query(request) if not query: return None response.headers['Content-disposition'] = 'attachment; filename=%s_%s.csv'\ % tuple(request.vars.query.split('.')[:2]) return str(db(query).select()) def import_csv(table, file): table.import_from_csv_file(file) def select(): import re db = get_database(request) dbname = request.args[0] regex = re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>\d+)') if len(request.args)>1 and hasattr(db[request.args[1]],'_primarykey'): regex = re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>.+)') if request.vars.query: match = regex.match(request.vars.query) if match: request.vars.query = '%s.%s.%s==%s' % (request.args[0], match.group('table'), match.group('field'), match.group('value')) else: request.vars.query = session.last_query query = get_query(request) if request.vars.start: start = int(request.vars.start) else: start = 0 nrows = 0 stop = start + 100 table = None rows = [] orderby = request.vars.orderby if orderby: orderby = dbname + '.' + orderby if orderby == session.last_orderby: if orderby[0] == '~': orderby = orderby[1:] else: orderby = '~' + orderby session.last_orderby = orderby session.last_query = request.vars.query form = FORM(TABLE(TR(T('Query:'), '', INPUT(_style='width:400px', _name='query', _value=request.vars.query or '', requires=IS_NOT_EMPTY(error_message=T("Cannot be empty")))), TR(T('Update:'), INPUT(_name='update_check', _type='checkbox', value=False), INPUT(_style='width:400px', _name='update_fields', _value=request.vars.update_fields or '')), TR(T('Delete:'), INPUT(_name='delete_check', _class='delete', _type='checkbox', value=False), ''), TR('', '', INPUT(_type='submit', _value='submit'))), _action=URL(r=request,args=request.args)) if request.vars.csvfile != None: try: import_csv(db[request.vars.table], request.vars.csvfile.file) response.flash = T('data uploaded') except Exception, e: response.flash = DIV(T('unable to parse csv file'),PRE(str(e))) if form.accepts(request.vars, formname=None): # regex = re.compile(request.args[0] + '\.(?P<table>\w+)\.id\>0') regex = re.compile(request.args[0] + '\.(?P<table>\w+)\..+') match = regex.match(form.vars.query.strip()) if match: table = match.group('table') try: nrows = db(query).count() if form.vars.update_check and form.vars.update_fields: db(query).update(**eval_in_global_env('dict(%s)' % form.vars.update_fields)) response.flash = T('%s rows updated', nrows) elif form.vars.delete_check: db(query).delete() response.flash = T('%s rows deleted', nrows) nrows = db(query).count() if orderby: rows = db(query).select(limitby=(start, stop), orderby=eval_in_global_env(orderby)) else: rows = db(query).select(limitby=(start, stop)) except Exception, e: (rows, nrows) = ([], 0) response.flash = DIV(T('Invalid Query'),PRE(str(e))) return dict( form=form, table=table, start=start, stop=stop, nrows=nrows, rows=rows, query=request.vars.query, ) # ########################################################## # ## edit delete one record # ########################################################### def update(): (db, table) = get_table(request) keyed = hasattr(db[table],'_primarykey') record = None if keyed: key = [f for f in request.vars if f in db[table]._primarykey] if key: record = db(db[table][key[0]] == request.vars[key[0]]).select().first() else: record = db(db[table].id == request.args(2)).select().first() if not record: qry = query_by_table_type(table, db) session.flash = T('record does not exist') redirect(URL('select', args=request.args[:1], vars=dict(query=qry))) if keyed: for k in db[table]._primarykey: db[table][k].writable=False form = SQLFORM(db[table], record, deletable=True, delete_label=T('Check to delete'), ignore_rw=ignore_rw and not keyed, linkto=URL('select', args=request.args[:1]), upload=URL(r=request, f='download', args=request.args[:1])) if form.accepts(request.vars, session): session.flash = T('done!') qry = query_by_table_type(table, db) redirect(URL('select', args=request.args[:1], vars=dict(query=qry))) return dict(form=form,table=db[table]) # ########################################################## # ## get global variables # ########################################################### def state(): return dict() def ccache(): form = FORM( P(TAG.BUTTON("Clear CACHE?", _type="submit", _name="yes", _value="yes")), P(TAG.BUTTON("Clear RAM", _type="submit", _name="ram", _value="ram")), P(TAG.BUTTON("Clear DISK", _type="submit", _name="disk", _value="disk")), ) if form.accepts(request.vars, session): clear_ram = False clear_disk = False session.flash = "" if request.vars.yes: clear_ram = clear_disk = True if request.vars.ram: clear_ram = True if request.vars.disk: clear_disk = True if clear_ram: cache.ram.clear() session.flash += "Ram Cleared " if clear_disk: cache.disk.clear() session.flash += "Disk Cleared" redirect(URL(r=request)) try: from guppy import hpy; hp=hpy() except ImportError: hp = False import shelve, os, copy, time, math from gluon import portalocker ram = { 'bytes': 0, 'objects': 0, 'hits': 0, 'misses': 0, 'ratio': 0, 'oldest': time.time() } disk = copy.copy(ram) total = copy.copy(ram) for key, value in cache.ram.storage.items(): if isinstance(value, dict): ram['hits'] = value['hit_total'] - value['misses'] ram['misses'] = value['misses'] try: ram['ratio'] = ram['hits'] * 100 / value['hit_total'] except (KeyError, ZeroDivisionError): ram['ratio'] = 0 else: if hp: ram['bytes'] += hp.iso(value[1]).size ram['objects'] += hp.iso(value[1]).count if value[0] < ram['oldest']: ram['oldest'] = value[0] locker = open(os.path.join(request.folder, 'cache/cache.lock'), 'a') portalocker.lock(locker, portalocker.LOCK_EX) disk_storage = shelve.open(os.path.join(request.folder, 'cache/cache.shelve')) try: for key, value in disk_storage.items(): if isinstance(value, dict): disk['hits'] = value['hit_total'] - value['misses'] disk['misses'] = value['misses'] try: disk['ratio'] = disk['hits'] * 100 / value['hit_total'] except (KeyError, ZeroDivisionError): disk['ratio'] = 0 else: if hp: disk['bytes'] += hp.iso(value[1]).size disk['objects'] += hp.iso(value[1]).count if value[0] < disk['oldest']: disk['oldest'] = value[0] finally: portalocker.unlock(locker) locker.close() disk_storage.close() total['bytes'] = ram['bytes'] + disk['bytes'] total['objects'] = ram['objects'] + disk['objects'] total['hits'] = ram['hits'] + disk['hits'] total['misses'] = ram['misses'] + disk['misses'] try: total['ratio'] = total['hits'] * 100 / (total['hits'] + total['misses']) except (KeyError, ZeroDivisionError): total['ratio'] = 0 if disk['oldest'] < ram['oldest']: total['oldest'] = disk['oldest'] else: total['oldest'] = ram['oldest'] def GetInHMS(seconds): hours = math.floor(seconds / 3600) seconds -= hours * 3600 minutes = math.floor(seconds / 60) seconds -= minutes * 60 seconds = math.floor(seconds) return (hours, minutes, seconds) ram['oldest'] = GetInHMS(time.time() - ram['oldest']) disk['oldest'] = GetInHMS(time.time() - disk['oldest']) total['oldest'] = GetInHMS(time.time() - total['oldest']) return dict(form=form, total=total, ram=ram, disk=disk)
Python
import sys import cStringIO import gluon.contrib.shell import code, thread from gluon.shell import env if DEMO_MODE or MULTI_USER_MODE: session.flash = T('disabled in demo mode') redirect(URL('default','site')) FE=10**9 def index(): app = request.args(0) or 'admin' reset() return dict(app=app) def callback(): app = request.args[0] command = request.vars.statement escape = command[:1]!='!' history = session['history:'+app] = session.get('history:'+app,gluon.contrib.shell.History()) if not escape: command = command[1:] if command == '%reset': reset() return '*** reset ***' elif command[0] == '%': try: command=session['commands:'+app][int(command[1:])] except ValueError: return '' session['commands:'+app].append(command) environ=env(app,True) output = gluon.contrib.shell.run(history,command,environ) k = len(session['commands:'+app]) - 1 #output = PRE(output) #return TABLE(TR('In[%i]:'%k,PRE(command)),TR('Out[%i]:'%k,output)) return 'In [%i] : %s%s\n' % (k + 1, command, output) def reset(): app = request.args(0) or 'admin' session['commands:'+app] = [] session['history:'+app] = gluon.contrib.shell.History() return 'done'
Python
### this works on linux only import re try: import fcntl import subprocess import signal import os import shutil from gluon.fileutils import read_file, write_file except: session.flash='sorry, only on Unix systems' redirect(URL(request.application,'default','site')) forever=10**8 def kill(): p = cache.ram('gae_upload',lambda:None,forever) if not p or p.poll()!=None: return 'oops' os.kill(p.pid, signal.SIGKILL) cache.ram('gae_upload',lambda:None,-1) class EXISTS(object): def __init__(self, error_message='file not found'): self.error_message = error_message def __call__(self, value): if os.path.exists(value): return (value,None) return (value,self.error_message) def deploy(): regex = re.compile('^\w+$') apps = sorted(file for file in os.listdir(apath(r=request)) if regex.match(file)) form = SQLFORM.factory( Field('appcfg',default=GAE_APPCFG,label='Path to appcfg.py', requires=EXISTS(error_message=T('file not found'))), Field('google_application_id',requires=IS_ALPHANUMERIC()), Field('applications','list:string', requires=IS_IN_SET(apps,multiple=True), label=T('web2py apps to deploy')), Field('email',requires=IS_EMAIL(),label=T('GAE Email')), Field('password','password',requires=IS_NOT_EMPTY(),label=T('GAE Password'))) cmd = output = errors= "" if form.accepts(request,session): try: kill() except: pass ignore_apps = [item for item in apps \ if not item in form.vars.applications] regex = re.compile('\(applications/\(.*') yaml = apath('../app.yaml', r=request) if not os.path.exists(yaml): example = apath('../app.example.yaml', r=request) shutil.copyfile(example,yaml) data = read_file(yaml) data = re.sub('application:.*','application: %s' % form.vars.google_application_id,data) data = regex.sub('(applications/(%s)/.*)|' % '|'.join(ignore_apps),data) write_file(yaml, data) path = request.env.applications_parent cmd = '%s --email=%s --passin update %s' % \ (form.vars.appcfg, form.vars.email, path) p = cache.ram('gae_upload', lambda s=subprocess,c=cmd:s.Popen(c, shell=True, stdin=s.PIPE, stdout=s.PIPE, stderr=s.PIPE, close_fds=True),-1) p.stdin.write(form.vars.password+'\n') fcntl.fcntl(p.stdout.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) fcntl.fcntl(p.stderr.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) return dict(form=form,command=cmd) def callback(): p = cache.ram('gae_upload',lambda:None,forever) if not p or p.poll()!=None: return '<done/>' try: output = p.stdout.read() except: output='' try: errors = p.stderr.read() except: errors='' return (output+errors).replace('\n','<br/>')
Python
import os from gluon.settings import global_settings, read_file # def index(): app = request.args(0) return dict(app=app) def profiler(): """ to use the profiler start web2py with -F profiler.log """ KEY = 'web2py_profiler_size' filename = global_settings.cmd_options.profiler_filename data = 'profiler disabled' if filename: if KEY in request.cookies: size = int(request.cookies[KEY].value) else: size = 0 if os.path.exists(filename): data = read_file('profiler.log','rb') if size<len(data): data = data[size:] else: size=0 size += len(data) response.cookies[KEY] = size return data
Python
# coding: utf8 from gluon.admin import * from gluon.fileutils import abspath, read_file, write_file from glob import glob import shutil import platform if DEMO_MODE and request.function in ['change_password','pack','pack_plugin','upgrade_web2py','uninstall','cleanup','compile_app','remove_compiled_app','delete','delete_plugin','create_file','upload_file','update_languages','reload_routes']: session.flash = T('disabled in demo mode') redirect(URL('site')) if not is_manager() and request.function in ['change_password','upgrade_web2py']: session.flash = T('disabled in multi user mode') redirect(URL('site')) if FILTER_APPS and request.args(0) and not request.args(0) in FILTER_APPS: session.flash = T('disabled in demo mode') redirect(URL('site')) def safe_open(a,b): if DEMO_MODE and 'w' in b: class tmp: def write(self,data): pass return tmp() return open(a,b) def safe_read(a, b='r'): safe_file = safe_open(a, b) try: return safe_file.read() finally: safe_file.close() def safe_write(a, value, b='w'): safe_file = safe_open(a, b) try: safe_file.write(value) finally: safe_file.close() def get_app(name=None): app = name or request.args(0) if app and (not MULTI_USER_MODE or db(db.app.name==app)(db.app.owner==auth.user.id).count()): return app session.flash = 'App does not exist or your are not authorized' redirect(URL('site')) def index(): """ Index handler """ send = request.vars.send if DEMO_MODE: session.authorized = True session.last_time = t0 if not send: send = URL('site') if session.authorized: redirect(send) elif request.vars.password: if verify_password(request.vars.password): session.authorized = True login_record(True) if CHECK_VERSION: session.check_version = True else: session.check_version = False session.last_time = t0 if isinstance(send, list): # ## why does this happen? send = str(send[0]) redirect(send) else: times_denied = login_record(False) if times_denied >= allowed_number_of_attempts: response.flash = \ T('admin disabled because too many invalid login attempts') elif times_denied == allowed_number_of_attempts - 1: response.flash = \ T('You have one more login attempt before you are locked out') else: response.flash = T('invalid password.') return dict(send=send) def check_version(): """ Checks if web2py is up to date """ session.forget() session._unlock(response) new_version, version_number = check_new_version(request.env.web2py_version, WEB2PY_VERSION_URL) if new_version == -1: return A(T('Unable to check for upgrades'), _href=WEB2PY_URL) elif new_version != True: return A(T('web2py is up to date'), _href=WEB2PY_URL) elif platform.system().lower() in ('windows','win32','win64') and os.path.exists("web2py.exe"): return SPAN('You should upgrade to version %s' % version_number) else: return sp_button(URL('upgrade_web2py'), T('upgrade now')) \ + XML(' <strong class="upgrade_version">%s</strong>' % version_number) def logout(): """ Logout handler """ session.authorized = None if MULTI_USER_MODE: redirect(URL('user/logout')) redirect(URL('index')) def change_password(): if session.pam_user: session.flash = T('PAM authenticated user, cannot change password here') redirect(URL('site')) form=SQLFORM.factory(Field('current_admin_password','password'), Field('new_admin_password','password',requires=IS_STRONG()), Field('new_admin_password_again','password')) if form.accepts(request.vars): if not verify_password(request.vars.current_admin_password): form.errors.current_admin_password = T('invalid password') elif form.vars.new_admin_password != form.vars.new_admin_password_again: form.errors.new_admin_password_again = T('no match') else: path = abspath('parameters_%s.py' % request.env.server_port) safe_write(path, 'password="%s"' % CRYPT()(request.vars.new_admin_password)[0]) session.flash = T('password changed') redirect(URL('site')) return dict(form=form) def site(): """ Site handler """ myversion = request.env.web2py_version # Shortcut to make the elif statements more legible file_or_appurl = 'file' in request.vars or 'appurl' in request.vars if DEMO_MODE: pass elif request.vars.filename and not 'file' in request.vars: # create a new application appname = cleanpath(request.vars.filename).replace('.', '_') if app_create(appname, request): if MULTI_USER_MODE: db.app.insert(name=appname,owner=auth.user.id) session.flash = T('new application "%s" created', appname) redirect(URL('design',args=appname)) else: session.flash = \ T('unable to create application "%s" (it may exist already)', request.vars.filename) redirect(URL(r=request)) elif file_or_appurl and not request.vars.filename: # can't do anything without an app name msg = 'you must specify a name for the uploaded application' response.flash = T(msg) elif file_or_appurl and request.vars.filename: # fetch an application via URL or file upload f = None if request.vars.appurl is not '': try: f = urllib.urlopen(request.vars.appurl) except Exception, e: session.flash = DIV(T('Unable to download app because:'),PRE(str(e))) redirect(URL(r=request)) fname = request.vars.appurl elif request.vars.file is not '': f = request.vars.file.file fname = request.vars.file.filename if f: appname = cleanpath(request.vars.filename).replace('.', '_') installed = app_install(appname, f, request, fname, overwrite=request.vars.overwrite_check) if f and installed: msg = 'application %(appname)s installed with md5sum: %(digest)s' session.flash = T(msg, dict(appname=appname, digest=md5_hash(installed))) elif f and request.vars.overwrite_check: msg = 'unable to install application "%(appname)s"' session.flash = T(msg, dict(appname=request.vars.filename)) else: msg = 'unable to install application "%(appname)s"' session.flash = T(msg, dict(appname=request.vars.filename)) redirect(URL(r=request)) regex = re.compile('^\w+$') if is_manager(): apps = [f for f in os.listdir(apath(r=request)) if regex.match(f)] else: apps = [f.name for f in db(db.app.owner==auth.user_id).select()] if FILTER_APPS: apps = [f for f in apps if f in FILTER_APPS] apps = sorted(apps,lambda a,b:cmp(a.upper(),b.upper())) return dict(app=None, apps=apps, myversion=myversion) def pack(): app = get_app() if len(request.args) == 1: fname = 'web2py.app.%s.w2p' % app filename = app_pack(app, request) else: fname = 'web2py.app.%s.compiled.w2p' % app filename = app_pack_compiled(app, request) if filename: response.headers['Content-Type'] = 'application/w2p' disposition = 'attachment; filename=%s' % fname response.headers['Content-Disposition'] = disposition return safe_read(filename, 'rb') else: session.flash = T('internal error') redirect(URL('site')) def pack_plugin(): app = get_app() if len(request.args) == 2: fname = 'web2py.plugin.%s.w2p' % request.args[1] filename = plugin_pack(app, request.args[1], request) if filename: response.headers['Content-Type'] = 'application/w2p' disposition = 'attachment; filename=%s' % fname response.headers['Content-Disposition'] = disposition return safe_read(filename, 'rb') else: session.flash = T('internal error') redirect(URL('plugin',args=request.args)) def upgrade_web2py(): if 'upgrade' in request.vars: (success, error) = upgrade(request) if success: session.flash = T('web2py upgraded; please restart it') else: session.flash = T('unable to upgrade because "%s"', error) redirect(URL('site')) elif 'noupgrade' in request.vars: redirect(URL('site')) return dict() def uninstall(): app = get_app() if 'delete' in request.vars: if MULTI_USER_MODE: if is_manager() and db(db.app.name==app).delete(): pass elif db(db.app.name==app)(db.app.owner==auth.user.id).delete(): pass else: session.flash = T('no permission to uninstall "%s"', app) redirect(URL('site')) if app_uninstall(app, request): session.flash = T('application "%s" uninstalled', app) else: session.flash = T('unable to uninstall "%s"', app) redirect(URL('site')) elif 'nodelete' in request.vars: redirect(URL('site')) return dict(app=app) def cleanup(): app = get_app() clean = app_cleanup(app, request) if not clean: session.flash = T("some files could not be removed") else: session.flash = T('cache, errors and sessions cleaned') redirect(URL('site')) def compile_app(): app = get_app() c = app_compile(app, request) if not c: session.flash = T('application compiled') else: session.flash = DIV(T('Cannot compile: there are errors in your app:'), CODE(c)) redirect(URL('site')) def remove_compiled_app(): """ Remove the compiled application """ app = get_app() remove_compiled_application(apath(app, r=request)) session.flash = T('compiled application removed') redirect(URL('site')) def delete(): """ Object delete handler """ app = get_app() filename = '/'.join(request.args) sender = request.vars.sender if isinstance(sender, list): # ## fix a problem with Vista sender = sender[0] if 'nodelete' in request.vars: redirect(URL(sender)) elif 'delete' in request.vars: try: os.unlink(apath(filename, r=request)) session.flash = T('file "%(filename)s" deleted', dict(filename=filename)) except Exception: session.flash = T('unable to delete file "%(filename)s"', dict(filename=filename)) redirect(URL(sender)) return dict(filename=filename, sender=sender) def peek(): """ Visualize object code """ app = get_app() filename = '/'.join(request.args) try: data = safe_read(apath(filename, r=request)).replace('\r','') except IOError: session.flash = T('file does not exist') redirect(URL('site')) extension = filename[filename.rfind('.') + 1:].lower() return dict(app=request.args[0], filename=filename, data=data, extension=extension) def test(): """ Execute controller tests """ app = get_app() if len(request.args) > 1: file = request.args[1] else: file = '.*\.py' controllers = listdir(apath('%s/controllers/' % app, r=request), file + '$') return dict(app=app, controllers=controllers) def keepalive(): return '' def search(): keywords=request.vars.keywords or '' app = get_app() def match(filename,keywords): filename=os.path.join(apath(app, r=request),filename) if keywords in read_file(filename,'rb'): return True return False path = apath(request.args[0], r=request) files1 = glob(os.path.join(path,'*/*.py')) files2 = glob(os.path.join(path,'*/*.html')) files3 = glob(os.path.join(path,'*/*/*.html')) files=[x[len(path)+1:].replace('\\','/') for x in files1+files2+files3 if match(x,keywords)] return response.json({'files':files}) def edit(): """ File edit handler """ # Load json only if it is ajax edited... app = get_app() filename = '/'.join(request.args) # Try to discover the file type if filename[-3:] == '.py': filetype = 'python' elif filename[-5:] == '.html': filetype = 'html' elif filename[-5:] == '.load': filetype = 'html' elif filename[-4:] == '.css': filetype = 'css' elif filename[-3:] == '.js': filetype = 'js' else: filetype = 'html' # ## check if file is not there path = apath(filename, r=request) if request.vars.revert and os.path.exists(path + '.bak'): try: data = safe_read(path + '.bak') data1 = safe_read(path) except IOError: session.flash = T('Invalid action') if 'from_ajax' in request.vars: return response.json({'error': str(T('Invalid action'))}) else: redirect(URL('site')) safe_write(path, data) file_hash = md5_hash(data) saved_on = time.ctime(os.stat(path)[stat.ST_MTIME]) safe_write(path + '.bak', data1) response.flash = T('file "%s" of %s restored', (filename, saved_on)) else: try: data = safe_read(path) except IOError: session.flash = T('Invalid action') if 'from_ajax' in request.vars: return response.json({'error': str(T('Invalid action'))}) else: redirect(URL('site')) file_hash = md5_hash(data) saved_on = time.ctime(os.stat(path)[stat.ST_MTIME]) if request.vars.file_hash and request.vars.file_hash != file_hash: session.flash = T('file changed on disk') data = request.vars.data.replace('\r\n', '\n').strip() + '\n' safe_write(path + '.1', data) if 'from_ajax' in request.vars: return response.json({'error': str(T('file changed on disk')), 'redirect': URL('resolve', args=request.args)}) else: redirect(URL('resolve', args=request.args)) elif request.vars.data: safe_write(path + '.bak', data) data = request.vars.data.replace('\r\n', '\n').strip() + '\n' safe_write(path, data) file_hash = md5_hash(data) saved_on = time.ctime(os.stat(path)[stat.ST_MTIME]) response.flash = T('file saved on %s', saved_on) data_or_revert = (request.vars.data or request.vars.revert) # Check compile errors highlight = None if filetype == 'python' and request.vars.data: import _ast try: code = request.vars.data.rstrip().replace('\r\n','\n')+'\n' compile(code, path, "exec", _ast.PyCF_ONLY_AST) except Exception, e: start = sum([len(line)+1 for l, line in enumerate(request.vars.data.split("\n")) if l < e.lineno-1]) if e.text and e.offset: offset = e.offset - (len(e.text) - len(e.text.splitlines()[-1])) else: offset = 0 highlight = {'start': start, 'end': start + offset + 1} try: ex_name = e.__class__.__name__ except: ex_name = 'unknown exception!' response.flash = DIV(T('failed to compile file because:'), BR(), B(ex_name), T(' at line %s') % e.lineno, offset and T(' at char %s') % offset or '', PRE(str(e))) if data_or_revert and request.args[1] == 'modules': # Lets try to reload the modules try: mopath = '.'.join(request.args[2:])[:-3] exec 'import applications.%s.modules.%s' % (request.args[0], mopath) reload(sys.modules['applications.%s.modules.%s' % (request.args[0], mopath)]) except Exception, e: response.flash = DIV(T('failed to reload module because:'),PRE(str(e))) edit_controller = None editviewlinks = None view_link = None if filetype == 'html' and len(request.args) >= 3: cfilename = os.path.join(request.args[0], 'controllers', request.args[2] + '.py') if os.path.exists(apath(cfilename, r=request)): edit_controller = URL('edit', args=[cfilename]) view = request.args[3].replace('.html','') view_link = URL(request.args[0],request.args[2],view) elif filetype == 'python' and request.args[1] == 'controllers': ## it's a controller file. ## Create links to all of the associated view files. app = get_app() viewname = os.path.splitext(request.args[2])[0] viewpath = os.path.join(app,'views',viewname) aviewpath = apath(viewpath, r=request) viewlist = [] if os.path.exists(aviewpath): if os.path.isdir(aviewpath): viewlist = glob(os.path.join(aviewpath,'*.html')) elif os.path.exists(aviewpath+'.html'): viewlist.append(aviewpath+'.html') if len(viewlist): editviewlinks = [] for v in viewlist: vf = os.path.split(v)[-1] vargs = "/".join([viewpath.replace(os.sep,"/"),vf]) editviewlinks.append(A(T(vf.split(".")[0]),\ _href=URL('edit',args=[vargs]))) if len(request.args) > 2 and request.args[1] == 'controllers': controller = (request.args[2])[:-3] functions = regex_expose.findall(data) else: (controller, functions) = (None, None) if 'from_ajax' in request.vars: return response.json({'file_hash': file_hash, 'saved_on': saved_on, 'functions':functions, 'controller': controller, 'application': request.args[0], 'highlight': highlight }) else: editarea_preferences = {} editarea_preferences['FONT_SIZE'] = '10' editarea_preferences['FULL_SCREEN'] = 'false' editarea_preferences['ALLOW_TOGGLE'] = 'true' editarea_preferences['REPLACE_TAB_BY_SPACES'] = '4' editarea_preferences['DISPLAY'] = 'onload' for key in editarea_preferences: if globals().has_key(key): editarea_preferences[key]=globals()[key] return dict(app=request.args[0], filename=filename, filetype=filetype, data=data, edit_controller=edit_controller, file_hash=file_hash, saved_on=saved_on, controller=controller, functions=functions, view_link=view_link, editarea_preferences=editarea_preferences, editviewlinks=editviewlinks) def resolve(): """ """ filename = '/'.join(request.args) # ## check if file is not there path = apath(filename, r=request) a = safe_read(path).split('\n') try: b = safe_read(path + '.1').split('\n') except IOError: session.flash = 'Other file, no longer there' redirect(URL('edit', args=request.args)) d = difflib.ndiff(a, b) def leading(line): """ """ # TODO: we really need to comment this z = '' for (k, c) in enumerate(line): if c == ' ': z += '&nbsp;' elif c == ' \t': z += '&nbsp;' elif k == 0 and c == '?': pass else: break return XML(z) def getclass(item): """ Determine item class """ if item[0] == ' ': return 'normal' if item[0] == '+': return 'plus' if item[0] == '-': return 'minus' if request.vars: c = ''.join([item[2:] for (i, item) in enumerate(d) if item[0] \ == ' ' or 'line%i' % i in request.vars]) safe_write(path, c) session.flash = 'files merged' redirect(URL('edit', args=request.args)) else: # Making the short circuit compatible with <= python2.4 gen_data = lambda index,item: not item[:1] in ['+','-'] and "" \ or INPUT(_type='checkbox', _name='line%i' % index, value=item[0] == '+') diff = TABLE(*[TR(TD(gen_data(i,item)), TD(item[0]), TD(leading(item[2:]), TT(item[2:].rstrip())), _class=getclass(item)) for (i, item) in enumerate(d) if item[0] != '?']) return dict(diff=diff, filename=filename) def edit_language(): """ Edit language file """ app = get_app() filename = '/'.join(request.args) from gluon.languages import read_dict, write_dict strings = read_dict(apath(filename, r=request)) keys = sorted(strings.keys(),lambda x,y: cmp(x.lower(), y.lower())) rows = [] rows.append(H2(T('Original/Translation'))) for key in keys: name = md5_hash(key) if key==strings[key]: _class='untranslated' else: _class='translated' if len(key) <= 40: elem = INPUT(_type='text', _name=name,value=strings[key], _size=70,_class=_class) else: elem = TEXTAREA(_name=name, value=strings[key], _cols=70, _rows=5, _class=_class) # Making the short circuit compatible with <= python2.4 k = (strings[key] != key) and key or B(key) rows.append(P(k, BR(), elem, TAG.BUTTON(T('delete'), _onclick='return delkey("%s")' % name), _id=name)) rows.append(INPUT(_type='submit', _value=T('update'))) form = FORM(*rows) if form.accepts(request.vars, keepvalues=True): strs = dict() for key in keys: name = md5_hash(key) if form.vars[name]==chr(127): continue strs[key] = form.vars[name] write_dict(apath(filename, r=request), strs) session.flash = T('file saved on %(time)s', dict(time=time.ctime())) redirect(URL(r=request,args=request.args)) return dict(app=request.args[0], filename=filename, form=form) def about(): """ Read about info """ app = get_app() # ## check if file is not there about = safe_read(apath('%s/ABOUT' % app, r=request)) license = safe_read(apath('%s/LICENSE' % app, r=request)) return dict(app=app, about=MARKMIN(about), license=MARKMIN(license)) def design(): """ Application design handler """ app = get_app() if not response.flash and app == request.application: msg = T('ATTENTION: you cannot edit the running application!') response.flash = msg if request.vars.pluginfile!=None and not isinstance(request.vars.pluginfile,str): filename=os.path.basename(request.vars.pluginfile.filename) if plugin_install(app, request.vars.pluginfile.file, request, filename): session.flash = T('new plugin installed') redirect(URL('design',args=app)) else: session.flash = \ T('unable to create application "%s"', request.vars.filename) redirect(URL(r=request)) elif isinstance(request.vars.pluginfile,str): session.flash = T('plugin not specified') redirect(URL(r=request)) # If we have only pyc files it means that # we cannot design if os.path.exists(apath('%s/compiled' % app, r=request)): session.flash = \ T('application is compiled and cannot be designed') redirect(URL('site')) # Get all models models = listdir(apath('%s/models/' % app, r=request), '.*\.py$') models=[x.replace('\\','/') for x in models] defines = {} for m in models: data = safe_read(apath('%s/models/%s' % (app, m), r=request)) defines[m] = regex_tables.findall(data) defines[m].sort() # Get all controllers controllers = sorted(listdir(apath('%s/controllers/' % app, r=request), '.*\.py$')) controllers = [x.replace('\\','/') for x in controllers] functions = {} for c in controllers: data = safe_read(apath('%s/controllers/%s' % (app, c), r=request)) items = regex_expose.findall(data) functions[c] = items # Get all views views = sorted(listdir(apath('%s/views/' % app, r=request), '[\w/\-]+\.\w+$')) views = [x.replace('\\','/') for x in views] extend = {} include = {} for c in views: data = safe_read(apath('%s/views/%s' % (app, c), r=request)) items = regex_extend.findall(data) if items: extend[c] = items[0][1] items = regex_include.findall(data) include[c] = [i[1] for i in items] # Get all modules modules = listdir(apath('%s/modules/' % app, r=request), '.*\.py$') modules = modules=[x.replace('\\','/') for x in modules] modules.sort() # Get all static files statics = listdir(apath('%s/static/' % app, r=request), '[^\.#].*') statics = [x.replace('\\','/') for x in statics] statics.sort() # Get all languages languages = listdir(apath('%s/languages/' % app, r=request), '[\w-]*\.py') #Get crontab cronfolder = apath('%s/cron' % app, r=request) if not os.path.exists(cronfolder): os.mkdir(cronfolder) crontab = apath('%s/cron/crontab' % app, r=request) if not os.path.exists(crontab): safe_write(crontab, '#crontab') plugins=[] def filter_plugins(items,plugins): plugins+=[item[7:].split('/')[0].split('.')[0] for item in items if item.startswith('plugin_')] plugins[:]=list(set(plugins)) plugins.sort() return [item for item in items if not item.startswith('plugin_')] return dict(app=app, models=filter_plugins(models,plugins), defines=defines, controllers=filter_plugins(controllers,plugins), functions=functions, views=filter_plugins(views,plugins), modules=filter_plugins(modules,plugins), extend=extend, include=include, statics=filter_plugins(statics,plugins), languages=languages, crontab=crontab, plugins=plugins) def delete_plugin(): """ Object delete handler """ app=request.args(0) plugin = request.args(1) plugin_name='plugin_'+plugin if 'nodelete' in request.vars: redirect(URL('design',args=app)) elif 'delete' in request.vars: try: for folder in ['models','views','controllers','static','modules']: path=os.path.join(apath(app,r=request),folder) for item in os.listdir(path): if item.startswith(plugin_name): filename=os.path.join(path,item) if os.path.isdir(filename): shutil.rmtree(filename) else: os.unlink(filename) session.flash = T('plugin "%(plugin)s" deleted', dict(plugin=plugin)) except Exception: session.flash = T('unable to delete file plugin "%(plugin)s"', dict(plugin=plugin)) redirect(URL('design',args=request.args(0))) return dict(plugin=plugin) def plugin(): """ Application design handler """ app = get_app() plugin = request.args(1) if not response.flash and app == request.application: msg = T('ATTENTION: you cannot edit the running application!') response.flash = msg # If we have only pyc files it means that # we cannot design if os.path.exists(apath('%s/compiled' % app, r=request)): session.flash = \ T('application is compiled and cannot be designed') redirect(URL('site')) # Get all models models = listdir(apath('%s/models/' % app, r=request), '.*\.py$') models=[x.replace('\\','/') for x in models] defines = {} for m in models: data = safe_read(apath('%s/models/%s' % (app, m), r=request)) defines[m] = regex_tables.findall(data) defines[m].sort() # Get all controllers controllers = sorted(listdir(apath('%s/controllers/' % app, r=request), '.*\.py$')) controllers = [x.replace('\\','/') for x in controllers] functions = {} for c in controllers: data = safe_read(apath('%s/controllers/%s' % (app, c), r=request)) items = regex_expose.findall(data) functions[c] = items # Get all views views = sorted(listdir(apath('%s/views/' % app, r=request), '[\w/\-]+\.\w+$')) views = [x.replace('\\','/') for x in views] extend = {} include = {} for c in views: data = safe_read(apath('%s/views/%s' % (app, c), r=request)) items = regex_extend.findall(data) if items: extend[c] = items[0][1] items = regex_include.findall(data) include[c] = [i[1] for i in items] # Get all modules modules = listdir(apath('%s/modules/' % app, r=request), '.*\.py$') modules = modules=[x.replace('\\','/') for x in modules] modules.sort() # Get all static files statics = listdir(apath('%s/static/' % app, r=request), '[^\.#].*') statics = [x.replace('\\','/') for x in statics] statics.sort() # Get all languages languages = listdir(apath('%s/languages/' % app, r=request), '[\w-]*\.py') #Get crontab crontab = apath('%s/cron/crontab' % app, r=request) if not os.path.exists(crontab): safe_write(crontab, '#crontab') def filter_plugins(items): regex=re.compile('^plugin_'+plugin+'(/.*|\..*)?$') return [item for item in items if regex.match(item)] return dict(app=app, models=filter_plugins(models), defines=defines, controllers=filter_plugins(controllers), functions=functions, views=filter_plugins(views), modules=filter_plugins(modules), extend=extend, include=include, statics=filter_plugins(statics), languages=languages, crontab=crontab) def create_file(): """ Create files handler """ try: app = get_app(name=request.vars.location.split('/')[0]) path = apath(request.vars.location, r=request) filename = re.sub('[^\w./-]+', '_', request.vars.filename) if path[-11:] == '/languages/': # Handle language files if len(filename) == 0: raise SyntaxError if not filename[-3:] == '.py': filename += '.py' app = path.split('/')[-3] path=os.path.join(apath(app, r=request),'languages',filename) if not os.path.exists(path): safe_write(path, '') findT(apath(app, r=request), filename[:-3]) session.flash = T('language file "%(filename)s" created/updated', dict(filename=filename)) redirect(request.vars.sender) elif path[-8:] == '/models/': # Handle python models if not filename[-3:] == '.py': filename += '.py' if len(filename) == 3: raise SyntaxError text = '# coding: utf8\n' elif path[-13:] == '/controllers/': # Handle python controllers if not filename[-3:] == '.py': filename += '.py' if len(filename) == 3: raise SyntaxError text = '# coding: utf8\n# %s\ndef index(): return dict(message="hello from %s")' text = text % (T('try something like'), filename) elif path[-7:] == '/views/': if request.vars.plugin and not filename.startswith('plugin_%s/' % request.vars.plugin): filename = 'plugin_%s/%s' % (request.vars.plugin, filename) # Handle template (html) views if filename.find('.')<0: filename += '.html' extension = filename.split('.')[-1].lower() if len(filename) == 5: raise SyntaxError msg = T('This is the %(filename)s template', dict(filename=filename)) if extension == 'html': text = dedent(""" {{extend 'layout.html'}} <h1>%s</h1> {{=BEAUTIFY(response._vars)}}""" % msg) else: generic = os.path.join(path,'generic.'+extension) if os.path.exists(generic): text = read_file(generic) else: text = '' elif path[-9:] == '/modules/': if request.vars.plugin and not filename.startswith('plugin_%s/' % request.vars.plugin): filename = 'plugin_%s/%s' % (request.vars.plugin, filename) # Handle python module files if not filename[-3:] == '.py': filename += '.py' if len(filename) == 3: raise SyntaxError text = dedent(""" #!/usr/bin/env python # coding: utf8 from gluon import *\n""") elif path[-8:] == '/static/': if request.vars.plugin and not filename.startswith('plugin_%s/' % request.vars.plugin): filename = 'plugin_%s/%s' % (request.vars.plugin, filename) text = '' else: redirect(request.vars.sender) full_filename = os.path.join(path, filename) dirpath = os.path.dirname(full_filename) if not os.path.exists(dirpath): os.makedirs(dirpath) if os.path.exists(full_filename): raise SyntaxError safe_write(full_filename, text) session.flash = T('file "%(filename)s" created', dict(filename=full_filename[len(path):])) redirect(URL('edit', args=[os.path.join(request.vars.location, filename)])) except Exception, e: if not isinstance(e,HTTP): session.flash = T('cannot create file') redirect(request.vars.sender) def upload_file(): """ File uploading handler """ try: filename = None app = get_app(name=request.vars.location.split('/')[0]) path = apath(request.vars.location, r=request) if request.vars.filename: filename = re.sub('[^\w\./]+', '_', request.vars.filename) else: filename = os.path.split(request.vars.file.filename)[-1] if path[-8:] == '/models/' and not filename[-3:] == '.py': filename += '.py' if path[-9:] == '/modules/' and not filename[-3:] == '.py': filename += '.py' if path[-13:] == '/controllers/' and not filename[-3:] == '.py': filename += '.py' if path[-7:] == '/views/' and not filename[-5:] == '.html': filename += '.html' if path[-11:] == '/languages/' and not filename[-3:] == '.py': filename += '.py' filename = os.path.join(path, filename) dirpath = os.path.dirname(filename) if not os.path.exists(dirpath): os.makedirs(dirpath) safe_write(filename, request.vars.file.file.read(), 'wb') session.flash = T('file "%(filename)s" uploaded', dict(filename=filename[len(path):])) except Exception: if filename: d = dict(filename = filename[len(path):]) else: d = dict(filename = 'unkown') session.flash = T('cannot upload file "%(filename)s"', d) redirect(request.vars.sender) def errors(): """ Error handler """ import operator import os import pickle import hashlib app = get_app() method = request.args(1) or 'new' if method == 'new': errors_path = apath('%s/errors' % app, r=request) delete_hashes = [] for item in request.vars: if item[:7] == 'delete_': delete_hashes.append(item[7:]) hash2error = dict() for fn in listdir(errors_path, '^\w.*'): fullpath = os.path.join(errors_path, fn) if not os.path.isfile(fullpath): continue try: fullpath_file = open(fullpath, 'r') try: error = pickle.load(fullpath_file) finally: fullpath_file.close() except IOError: continue hash = hashlib.md5(error['traceback']).hexdigest() if hash in delete_hashes: os.unlink(fullpath) else: try: hash2error[hash]['count'] += 1 except KeyError: error_lines = error['traceback'].split("\n") last_line = error_lines[-2] error_causer = os.path.split(error['layer'])[1] hash2error[hash] = dict(count=1, pickel=error, causer=error_causer, last_line=last_line, hash=hash,ticket=fn) decorated = [(x['count'], x) for x in hash2error.values()] decorated.sort(key=operator.itemgetter(0), reverse=True) return dict(errors = [x[1] for x in decorated], app=app, method=method) else: for item in request.vars: if item[:7] == 'delete_': os.unlink(apath('%s/errors/%s' % (app, item[7:]), r=request)) func = lambda p: os.stat(apath('%s/errors/%s' % \ (app, p), r=request)).st_mtime tickets = sorted(listdir(apath('%s/errors/' % app, r=request), '^\w.*'), key=func, reverse=True) return dict(app=app, tickets=tickets, method=method) def make_link(path): """ Create a link from a path """ tryFile = path.replace('\\', '/') if os.path.isabs(tryFile) and os.path.isfile(tryFile): (folder, filename) = os.path.split(tryFile) (base, ext) = os.path.splitext(filename) app = get_app() editable = {'controllers': '.py', 'models': '.py', 'views': '.html'} for key in editable.keys(): check_extension = folder.endswith("%s/%s" % (app,key)) if ext.lower() == editable[key] and check_extension: return A('"' + tryFile + '"', _href=URL(r=request, f='edit/%s/%s/%s' % (app, key, filename))).xml() return '' def make_links(traceback): """ Make links using the given traceback """ lwords = traceback.split('"') # Making the short circuit compatible with <= python2.4 result = (len(lwords) != 0) and lwords[0] or '' i = 1 while i < len(lwords): link = make_link(lwords[i]) if link == '': result += '"' + lwords[i] else: result += link if i + 1 < len(lwords): result += lwords[i + 1] i = i + 1 i = i + 1 return result class TRACEBACK(object): """ Generate the traceback """ def __init__(self, text): """ TRACEBACK constructor """ self.s = make_links(CODE(text).xml()) def xml(self): """ Returns the xml """ return self.s def ticket(): """ Ticket handler """ if len(request.args) != 2: session.flash = T('invalid ticket') redirect(URL('site')) app = get_app() myversion = request.env.web2py_version ticket = request.args[1] e = RestrictedError() e.load(request, app, ticket) return dict(app=app, ticket=ticket, output=e.output, traceback=(e.traceback and TRACEBACK(e.traceback)), snapshot=e.snapshot, code=e.code, layer=e.layer, myversion=myversion) def error(): """ Generate a ticket (for testing) """ raise RuntimeError('admin ticket generator at your service') def update_languages(): """ Update available languages """ app = get_app() update_all_languages(apath(app, r=request)) session.flash = T('Language files (static strings) updated') redirect(URL('design',args=app)) def twitter(): session.forget() session._unlock(response) import gluon.tools import gluon.contrib.simplejson as sj try: if TWITTER_HASH: page = gluon.tools.fetch('http://twitter.com/%s?format=json'%TWITTER_HASH) return sj.loads(page)['#timeline'] else: return 'disabled' except Exception, e: return DIV(T('Unable to download because:'),BR(),str(e)) def user(): if MULTI_USER_MODE: if not db(db.auth_user).count(): auth.settings.registration_requires_approval = False return dict(form=auth()) else: return dict(form=T("Disabled")) def reload_routes(): """ Reload routes.py """ gluon.rewrite.load() redirect(URL('site'))
Python
# -*- coding: utf-8 -*- import os, uuid, re, pickle, urllib, glob from gluon.admin import app_create, plugin_install from gluon.fileutils import abspath, read_file, write_file def reset(session): session.app={ 'name':'', 'params':[('title','My New App'), ('subtitle','powered by web2py'), ('author','you'), ('author_email','you@example.com'), ('keywords',''), ('description',''), ('layout_theme','Default'), ('database_uri','sqlite://storage.sqlite'), ('security_key',str(uuid.uuid4())), ('email_server','localhost'), ('email_sender','you@example.com'), ('email_login',''), ('login_method','local'), ('login_config',''), ('plugins',[])], 'tables':['auth_user'], 'table_auth_user':['username','first_name','last_name','email','password'], 'pages':['index','error'], 'page_index':'# Welcome to my new app', 'page_error':'# Error: the document does not exist', } if not session.app: reset(session) def listify(x): if not isinstance(x,(list,tuple)): return x and [x] or [] return x def clean(name): return re.sub('\W+','_',name.strip().lower()) def index(): response.view='wizard/step.html' reset(session) apps=os.listdir(os.path.join(request.folder,'..')) form=SQLFORM.factory(Field('name',requires=[IS_NOT_EMPTY(),IS_ALPHANUMERIC()])) if form.accepts(request.vars): app = form.vars.name session.app['name'] = app if MULTI_USER_MODE and db(db.app.name==app)(db.app.owner!=auth.user.id).count(): session.flash = 'App belongs already to other user' elif app in apps: meta = os.path.normpath(\ os.path.join(os.path.normpath(request.folder), '..',app,'wizard.metadata')) if os.path.exists(meta): try: metafile = open(meta,'rb') try: session.app = pickle.load(metafile) finally: metafile.close() session.flash = "The app exists, was created by wizard, continue to overwrite!" except: session.flash = "The app exists, was NOT created by wizard, continue to overwrite!" redirect(URL('step1')) return dict(step='Start',form=form) def step1(): from gluon.contrib.simplejson import loads import urllib if not session.themes: url=LAYOUTS_APP+'/default/layouts.json' try: data = urllib.urlopen(url).read() session.themes = ['Default'] + loads(data)['layouts'] except: session.themes = ['Default'] themes = session.themes if not session.plugins: url = PLUGINS_APP+'/default/plugins.json' try: data = urllib.urlopen(url).read() session.plugins = loads(data)['plugins'] except: session.plugins = [] plugins = [x.split('.')[2] for x in session.plugins] response.view='wizard/step.html' params = dict(session.app['params']) form=SQLFORM.factory( Field('title',default=params.get('title',None), requires=IS_NOT_EMPTY()), Field('subtitle',default=params.get('subtitle',None)), Field('author',default=params.get('author',None)), Field('author_email',default=params.get('author_email',None)), Field('keywords',default=params.get('keywords',None)), Field('description','text', default=params.get('description',None)), Field('layout_theme',requires=IS_IN_SET(themes), default=params.get('layout_theme',themes[0])), Field('database_uri',default=params.get('database_uri',None)), Field('security_key',default=params.get('security_key',None)), Field('email_server',default=params.get('email_server',None)), Field('email_sender',default=params.get('email_sender',None)), Field('email_login',default=params.get('email_login',None)), Field('login_method',requires=IS_IN_SET(('local','janrain')), default=params.get('login_method','local')), Field('login_config',default=params.get('login_config',None)), Field('plugins','list:string',requires=IS_IN_SET(plugins,multiple=True))) if form.accepts(request.vars): session.app['params']=[(key,form.vars.get(key,None)) for key,value in session.app['params']] redirect(URL('step2')) return dict(step='1: Setting Parameters',form=form) def step2(): response.view='wizard/step.html' form=SQLFORM.factory(Field('table_names','list:string', default=session.app['tables'])) if form.accepts(request.vars): table_names = [clean(t) for t in listify(form.vars.table_names) if t.strip()] if [t for t in table_names if t.startswith('auth_') and not t=='auth_user']: form.error.table_names = T('invalid table names (auth_* tables already defined)') else: session.app['tables']=table_names for table in session.app['tables']: if not 'table_'+table in session.app: session.app['table_'+table]=['name'] if not table=='auth_user': for key in ['create','read','update','select','search']: name = table+'_'+key if not name in session.app['pages']: session.app['pages'].append(name) session.app['page_'+name]='## %s %s' % (key.capitalize(),table) if session.app['tables']: redirect(URL('step3',args=0)) else: redirect(URL('step4')) return dict(step='2: Tables',form=form) def step3(): response.view='wizard/step.html' n=int(request.args(0) or 0) m=len(session.app['tables']) if n>=m: redirect(URL('step2')) table=session.app['tables'][n] form=SQLFORM.factory(Field('field_names','list:string', default=session.app.get('table_'+table,[]))) if form.accepts(request.vars) and form.vars.field_names: fields=listify(form.vars.field_names) if table=='auth_user': for field in ['first_name','last_name','username','email','password']: if not field in fields: fields.append(field) session.app['table_'+table]=[t.strip().lower() for t in listify(form.vars.field_names) if t.strip()] try: tables=sort_tables(session.app['tables']) except RuntimeError: response.flash=T('invalid circual reference') else: if n<m-1: redirect(URL('step3',args=n+1)) else: redirect(URL('step4')) return dict(step='3: Fields for table "%s" (%s of %s)' % (table,n+1,m),table=table,form=form) def step4(): response.view='wizard/step.html' form=SQLFORM.factory(Field('pages','list:string', default=session.app['pages'])) if form.accepts(request.vars): session.app['pages']=[clean(t) for t in listify(form.vars.pages) if t.strip()] if session.app['pages']: redirect(URL('step5',args=0)) else: redirect(URL('step6')) return dict(step='4: Pages',form=form) def step5(): response.view='wizard/step.html' n=int(request.args(0) or 0) m=len(session.app['pages']) if n>=m: redirect(URL('step4')) page=session.app['pages'][n] markmin_url='http://web2py.com/examples/static/markmin.html' form=SQLFORM.factory(Field('content','text', default=session.app.get('page_'+page,[]), comment=A('use markmin',_href=markmin_url,_target='_blank')), formstyle='table2cols') if form.accepts(request.vars): session.app['page_'+page]=form.vars.content if n<m-1: redirect(URL('step5',args=n+1)) else: redirect(URL('step6')) return dict(step='5: View for page "%s" (%s of %s)' % (page,n+1,m),form=form) def step6(): response.view='wizard/step.html' params = dict(session.app['params']) app = session.app['name'] form=SQLFORM.factory( Field('generate_model','boolean',default=True), Field('generate_controller','boolean',default=True), Field('generate_views','boolean',default=True), Field('generate_menu','boolean',default=True), Field('apply_layout','boolean',default=True), Field('erase_database','boolean',default=True), Field('populate_database','boolean',default=True)) if form.accepts(request.vars): if DEMO_MODE: session.flash = T('Application cannot be generated in demo mode') redirect(URL('index')) create(form.vars) session.flash = 'Application %s created' % app redirect(URL('generated')) return dict(step='6: Generate app "%s"' % app,form=form) def generated(): return dict(app=session.app['name']) def sort_tables(tables): import re regex = re.compile('(%s)' % '|'.join(tables)) is_auth_user = 'auth_user' in tables d={} for table in tables: d[table]=[] for field in session.app['table_%s' % table]: d[table]+=regex.findall(field) tables=[] if is_auth_user: tables.append('auth_user') def append(table,trail=[]): if table in trail: raise RuntimeError for t in d[table]: append(t,trail=trail+[table]) if not table in tables: tables.append(table) for table in d: append(table) return tables def make_table(table,fields): rawtable=table if table!='auth_user': table='t_'+table s='' s+='\n'+'#'*40+'\n' s+="db.define_table('%s',\n" % table s+=" Field('id','id',\n" s+=" represent=lambda id:SPAN(id,' ',A('view',_href=URL('%s_read',args=id)))),\n"%rawtable first_field='id' for field in fields: items=[x.lower() for x in field.split()] has = {} keys = [] for key in ['notnull','unique','integer','double','boolean','float', 'boolean', 'date','time','datetime','text','wiki', 'html','file','upload','image','true', 'hidden','readonly','writeonly','multiple', 'notempty','required']: if key in items[1:]: keys.append(key) has[key] = True tables = session.app['tables'] refs = [t for t in tables if t in items] items = items[:1] + [x for x in items[1:] if not x in keys and not x in tables] barename = name = '_'.join(items) if table[:2]=='t_': name='f_'+name if first_field=='id': first_field=name ### determine field type ftype='string' deftypes={'integer':'integer','double':'double','boolean':'boolean', 'float':'double','bool':'boolean', 'date':'date','time':'time','datetime':'datetime', 'text':'text','file':'upload','image':'upload','upload':'upload', 'wiki':'text', 'html':'text'} for key,t in deftypes.items(): if key in has: ftype = t if refs: key = refs[0] if not key=='auth_user': key='t_'+key if 'multiple' in has: ftype='list:reference %s' % key else: ftype='reference %s' % key if ftype=='string' and 'multiple' in has: ftype='list:string' elif ftype=='integer' and 'multiple' in has: ftype='list:integer' elif name=='password': ftype='password' s+=" Field('%s', type='%s'" % (name, ftype) ### determine field attributes if 'notnull' in has or 'notempty' in has or 'required' in has: s+=', notnull=True' if 'unique' in has: s+=', unique=True' if ftype=='boolean' and 'true' in has: s+=",\n default=True" ### determine field representation if 'image' in has: s+=",\n represent=lambda x: x and IMG(_alt='image',_src=URL('download',args=x), _width='200px') or ''" elif ftype in ('file','upload'): s+=",\n represent=lambda x: x and A('download',_href=URL('download',args=x)) or ''" elif 'wiki' in has: s+=",\n represent=lambda x: MARKMIN(x)" s+=",\n comment='WIKI (markmin)'" elif 'html' in has: s+=",\n represent=lambda x: XML(x,sanitize=True)" s+=",\n comment='HTML (sanitized)'" ### determine field access if name=='password' or 'writeonly' in has: s+=",\n readable=False" elif 'hidden' in has: s+=",\n writable=False, readable=False" elif 'readonly' in has: s+=",\n writable=False" ### make up a label s+=",\n label=T('%s')),\n" % \ ' '.join(x.capitalize() for x in barename.split('_')) if table!='auth_user': s+=" Field('is_active','boolean',default=True,\n" s+=" label=T('Active'),writable=False,readable=False),\n" s+=" Field('created_on','datetime',default=request.now,\n" s+=" label=T('Created On'),writable=False,readable=False),\n" s+=" Field('modified_on','datetime',default=request.now,\n" s+=" label=T('Modified On'),writable=False,readable=False,\n" s+=" update=request.now),\n" if not table=='auth_user' and 'auth_user' in session.app['tables']: s+=" Field('created_by',db.auth_user,default=auth.user_id,\n" s+=" label=T('Created By'),writable=False,readable=False),\n" s+=" Field('modified_by',db.auth_user,default=auth.user_id,\n" s+=" label=T('Modified By'),writable=False,readable=False,\n" s+=" update=auth.user_id),\n" elif table=='auth_user': s+=" Field('registration_key',default='',\n" s+=" writable=False,readable=False),\n" s+=" Field('reset_password_key',default='',\n" s+=" writable=False,readable=False),\n" s+=" Field('registration_id',default='',\n" s+=" writable=False,readable=False),\n" s+=" format='%("+first_field+")s',\n" s+=" migrate=settings.migrate)\n\n" if table=='auth_user': s+=""" db.auth_user.first_name.requires = IS_NOT_EMPTY(error_message=auth.messages.is_empty) db.auth_user.last_name.requires = IS_NOT_EMPTY(error_message=auth.messages.is_empty) db.auth_user.password.requires = CRYPT(key=auth.settings.hmac_key) db.auth_user.username.requires = IS_NOT_IN_DB(db, db.auth_user.username) db.auth_user.registration_id.requires = IS_NOT_IN_DB(db, db.auth_user.registration_id) db.auth_user.email.requires = (IS_EMAIL(error_message=auth.messages.invalid_email), IS_NOT_IN_DB(db, db.auth_user.email)) """ else: s+="db.define_table('%s_archive',db.%s,Field('current_record','reference %s'))\n" % (table,table,table) return s def fix_db(filename): params = dict(session.app['params']) content = read_file(filename,'rb') if 'auth_user' in session.app['tables']: auth_user = make_table('auth_user',session.app['table_auth_user']) content = content.replace('sqlite://storage.sqlite', params['database_uri']) content = content.replace('auth.define_tables()',\ auth_user+'auth.define_tables(migrate = settings.migrate)') content += """ mail.settings.server = settings.email_server mail.settings.sender = settings.email_sender mail.settings.login = settings.email_login """ if params['login_method']=='janrain': content+=""" from gluon.contrib.login_methods.rpx_account import RPXAccount auth.settings.actions_disabled=['register','change_password','request_reset_password'] auth.settings.login_form = RPXAccount(request, api_key = settings.login_config.split(':')[-1], domain = settings.login_config.split(':')[0], url = "http://%s/%s/default/user/login" % (request.env.http_host,request.application)) """ write_file(filename, content, 'wb') def make_menu(pages): s=""" response.title = settings.title response.subtitle = settings.subtitle response.meta.author = '%s <%s>' % (settings.author, settings.author_email) response.meta.keywords = settings.keywords response.meta.description = settings.description response.menu = [ """ for page in pages: if not page.endswith('_read') and \ not page.endswith('_update') and \ not page.endswith('_search') and \ not page.startswith('_') and not page.startswith('error'): s+=" (T('%s'),URL('default','%s')==URL(),URL('default','%s'),[]),\n" % \ (' '.join(x.capitalize() for x in page.split('_')),page,page) s+=']' return s def make_page(page,contents): if 'auth_user' in session.app['tables'] and not page in ('index','error'): s="@auth.requires_login()\ndef %s():\n" % page else: s="def %s():\n" % page items=page.rsplit('_',1) if items[0] in session.app['tables'] and len(items)==2: t=items[0] if items[1]=='read': s+=" record = db.t_%s(request.args(0)) or redirect(URL('error'))\n" % t s+=" form=crud.read(db.t_%s,record)\n" % t s+=" return dict(form=form)\n\n" elif items[1]=='update': s+=" record = db.t_%s(request.args(0),is_active=True) or redirect(URL('error'))\n" % t s+=" form=crud.update(db.t_%s,record,next='%s_read/[id]',\n" % (t,t) s+=" ondelete=lambda form: redirect(URL('%s_select')),\n" % t s+=" onaccept=crud.archive)\n" s+=" return dict(form=form)\n\n" elif items[1]=='create': s+=" form=crud.create(db.t_%s,next='%s_read/[id]')\n" % (t,t) s+=" return dict(form=form)\n\n" elif items[1]=='select': s+=" f,v=request.args(0),request.args(1)\n" s+=" try: query=f and db.t_%s[f]==v or db.t_%s\n" % (t,t) s+=" except: redirect(URL('error'))\n" s+=" rows=db(query)(db.t_%s.is_active==True).select()\n" % t s+=" return dict(rows=rows)\n\n" elif items[1]=='search': s+=" form, rows=crud.search(db.t_%s,query=db.t_%s.is_active==True)\n" % (t,t) s+=" return dict(form=form, rows=rows)\n\n" else: t=None else: t=None if not t: s+=" return dict()\n\n" return s def make_view(page,contents): s="{{extend 'layout.html'}}\n\n" s+=str(MARKMIN(contents)) items=page.rsplit('_',1) if items[0] in session.app['tables'] and len(items)==2: t=items[0] if items[1]=='read': s+="\n{{=A(T('edit %s'),_href=URL('%s_update',args=request.args(0)))}}\n<br/>\n"%(t,t) s+='\n{{=form}}\n' s+="{{for t,f in db.t_%s._referenced_by:}}{{if not t[-8:]=='_archive':}}" % t s+="[{{=A(t[2:],_href=URL('%s_select'%t[2:],args=(f,form.record.id)))}}]" s+='{{pass}}{{pass}}' elif items[1]=='create': s+="\n{{=A(T('select %s'),_href=URL('%s_select'))}}\n<br/>\n"%(t,t) s+='\n{{=form}}\n' elif items[1]=='update': s+="\n{{=A(T('show %s'),_href=URL('%s_read',args=request.args(0)))}}\n<br/>\n"%(t,t) s+='\n{{=form}}\n' elif items[1]=='select': s+="\n{{if request.args:}}<h3>{{=T('For %s #%s' % (request.args(0)[2:],request.args(1)))}}</h3>{{pass}}\n" s+="\n{{=A(T('create new %s'),_href=URL('%s_create'))}}\n<br/>\n"%(t,t) s+="\n{{=A(T('search %s'),_href=URL('%s_search'))}}\n<br/>\n"%(t,t) s+="\n{{if rows:}}" s+="\n {{headers=dict((str(k),k.label) for k in db.t_%s)}}" % t s+="\n {{=SQLTABLE(rows,headers=headers)}}" s+="\n{{else:}}" s+="\n {{=TAG.blockquote(T('No Data'))}}" s+="\n{{pass}}\n" elif items[1]=='search': s+="\n{{=A(T('create new %s'),_href=URL('%s_create'))}}\n<br/>\n"%(t,t) s+='\n{{=form}}\n' s+="\n{{if rows:}}" s+="\n {{headers=dict((str(k),k.label) for k in db.t_%s)}}" % t s+="\n {{=SQLTABLE(rows,headers=headers)}}" s+="\n{{else:}}" s+="\n {{=TAG.blockquote(T('No Data'))}}" s+="\n{{pass}}\n" return s def populate(tables): s = 'from gluon.contrib.populate import populate\n' s+= 'if not db(db.auth_user).count():\n' for table in sort_tables(tables): t=table=='auth_user' and 'auth_user' or 't_'+table s+=" populate(db.%s,10)\n" % t return s def create(options): if DEMO_MODE: session.flash = T('disabled in demo mode') redirect(URL('step6')) params = dict(session.app['params']) app = session.app['name'] if not app_create(app,request,force=True,key=params['security_key']): session.flash = 'Failure to create application' redirect(URL('step6')) ### save metadata in newapp/wizard.metadata try: meta = os.path.join(request.folder,'..',app,'wizard.metadata') file=open(meta,'wb') pickle.dump(session.app,file) file.close() except IOError: session.flash = 'Failure to write wizard metadata' redirect(URL('step6')) ### apply theme if options.apply_layout and params['layout_theme']!='Default': try: fn = 'web2py.plugin.layout_%s.w2p' % params['layout_theme'] theme = urllib.urlopen(LAYOUTS_APP+'/static/plugin_layouts/plugins/'+fn) plugin_install(app, theme, request, fn) except: session.flash = T("unable to download layout") ### apply plugins for plugin in params['plugins']: try: plugin_name = 'web2py.plugin.'+plugin+'.w2p' stream = urllib.urlopen(PLUGINS_APP+'/static/'+plugin_name) plugin_install(app, stream, request, plugin_name) except Exception, e: session.flash = T("unable to download plugin: %s" % plugin) ### write configuration file into newapp/models/0.py model = os.path.join(request.folder,'..',app,'models','0.py') file = open(model, 'wb') try: file.write("from gluon.storage import Storage\n") file.write("settings = Storage()\n\n") file.write("settings.migrate = True\n") for key,value in session.app['params']: file.write("settings.%s = %s\n" % (key,repr(value))) finally: file.close() ### write configuration file into newapp/models/menu.py if options.generate_menu: model = os.path.join(request.folder,'..',app,'models','menu.py') file = open(model,'wb') try: file.write(make_menu(session.app['pages'])) finally: file.close() ### customize the auth_user table model = os.path.join(request.folder,'..',app,'models','db.py') fix_db(model) ### create newapp/models/db_wizard.py if options.generate_model: model = os.path.join(request.folder,'..',app,'models','db_wizard.py') file = open(model,'wb') try: file.write('### we prepend t_ to tablenames and f_ to fieldnames for disambiguity\n\n') tables = sort_tables(session.app['tables']) for table in tables: if table=='auth_user': continue file.write(make_table(table,session.app['table_'+table])) finally: file.close() model = os.path.join(request.folder,'..',app, 'models','db_wizard_populate.py') if os.path.exists(model): os.unlink(model) if options.populate_database and session.app['tables']: file = open(model,'wb') try: file.write(populate(session.app['tables'])) finally: file.close() ### create newapp/controllers/default.py if options.generate_controller: controller = os.path.join(request.folder,'..',app,'controllers','default.py') file = open(controller,'wb') try: file.write("""# -*- coding: utf-8 -*- ### required - do no delete def user(): return dict(form=auth()) def download(): return response.download(request,db) def call(): session.forget() return service() ### end requires """) for page in session.app['pages']: file.write(make_page(page,session.app.get('page_'+page,''))) finally: file.close() ### create newapp/views/default/*.html if options.generate_views: for page in session.app['pages']: view = os.path.join(request.folder,'..',app,'views','default',page+'.html') file = open(view,'wb') try: file.write(make_view(page,session.app.get('page_'+page,''))) finally: file.close() if options.erase_database: path = os.path.join(request.folder,'..',app,'databases','*') for file in glob.glob(path): os.unlink(file)
Python
APP_ID = "139729456078929" APP_SECRET = '9add4c1095d74c2d05b61c5702d6cf0c' FAN_PAGE = "https://www.facebook.com/pages/Systemsthoughts-test/240071796045643?sk=%s" % APP_ID LANDER = '<center><h2>Howdy Like Our Page To Begin!</h2></center>'#fancy graphic to make them like the page HEADER = '<center><img src="http://img33.imageshack.us/img33/4262/logossa.png"></center>' # header graphic or html can be empty if ya want. FOOTER = '<center><img src="http://img542.imageshack.us/img542/7862/blanksssss.png"></center>' # footer graphic or html... can be left blank if so please. INVITE_TITLE = "share your Prize With Your Friends First! (10)" #title on top the app request dialog INVITE_MESSAGE = "FarmVille Bonus fanpage" # message sent to invite friend.. probably wanna let them know its a fanpage FORCE_COUNT_NUMBER = 1 FORCE_HEADER = "required" #title of error window if haven't invited enough friend FORCE_MESSAGE_BEFORE = "You must invite<font color=red>"# message to show before the number FORCE_MESSAGE_AFTER = "</font> more friends"# message to show after the number
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s rows deleted': '%s \xe0\xa4\xaa\xe0\xa4\x82\xe0\xa4\x95\xe0\xa5\x8d\xe0\xa4\xa4\xe0\xa4\xbf\xe0\xa4\xaf\xe0\xa4\xbe\xe0\xa4\x81 \xe0\xa4\xae\xe0\xa4\xbf\xe0\xa4\x9f\xe0\xa4\xbe\xe0\xa4\x8f\xe0\xa4\x81', '%s rows updated': '%s \xe0\xa4\xaa\xe0\xa4\x82\xe0\xa4\x95\xe0\xa5\x8d\xe0\xa4\xa4\xe0\xa4\xbf\xe0\xa4\xaf\xe0\xa4\xbe\xe0\xa4\x81 \xe0\xa4\x85\xe0\xa4\xa6\xe0\xa5\x8d\xe0\xa4\xaf\xe0\xa4\xa4\xe0\xa4\xa8', 'Available databases and tables': '\xe0\xa4\x89\xe0\xa4\xaa\xe0\xa4\xb2\xe0\xa4\xac\xe0\xa5\x8d\xe0\xa4\xa7 \xe0\xa4\xa1\xe0\xa5\x87\xe0\xa4\x9f\xe0\xa4\xbe\xe0\xa4\xac\xe0\xa5\x87\xe0\xa4\xb8 \xe0\xa4\x94\xe0\xa4\xb0 \xe0\xa4\xa4\xe0\xa4\xbe\xe0\xa4\xb2\xe0\xa4\xbf\xe0\xa4\x95\xe0\xa4\xbe', 'Cannot be empty': '\xe0\xa4\x96\xe0\xa4\xbe\xe0\xa4\xb2\xe0\xa5\x80 \xe0\xa4\xa8\xe0\xa4\xb9\xe0\xa5\x80\xe0\xa4\x82 \xe0\xa4\xb9\xe0\xa5\x8b \xe0\xa4\xb8\xe0\xa4\x95\xe0\xa4\xa4\xe0\xa4\xbe', 'Change Password': '\xe0\xa4\xaa\xe0\xa4\xbe\xe0\xa4\xb8\xe0\xa4\xb5\xe0\xa4\xb0\xe0\xa5\x8d\xe0\xa4\xa1 \xe0\xa4\xac\xe0\xa4\xa6\xe0\xa4\xb2\xe0\xa5\x87\xe0\xa4\x82', 'Check to delete': '\xe0\xa4\xb9\xe0\xa4\x9f\xe0\xa4\xbe\xe0\xa4\xa8\xe0\xa5\x87 \xe0\xa4\x95\xe0\xa5\x87 \xe0\xa4\xb2\xe0\xa4\xbf\xe0\xa4\x8f \xe0\xa4\x9a\xe0\xa5\x81\xe0\xa4\xa8\xe0\xa5\x87\xe0\xa4\x82', 'Controller': 'Controller', 'Copyright': 'Copyright', 'Current request': '\xe0\xa4\xb5\xe0\xa4\xb0\xe0\xa5\x8d\xe0\xa4\xa4\xe0\xa4\xae\xe0\xa4\xbe\xe0\xa4\xa8 \xe0\xa4\x85\xe0\xa4\xa8\xe0\xa5\x81\xe0\xa4\xb0\xe0\xa5\x8b\xe0\xa4\xa7', 'Current response': '\xe0\xa4\xb5\xe0\xa4\xb0\xe0\xa5\x8d\xe0\xa4\xa4\xe0\xa4\xae\xe0\xa4\xbe\xe0\xa4\xa8 \xe0\xa4\xaa\xe0\xa5\x8d\xe0\xa4\xb0\xe0\xa4\xa4\xe0\xa4\xbf\xe0\xa4\x95\xe0\xa5\x8d\xe0\xa4\xb0\xe0\xa4\xbf\xe0\xa4\xaf\xe0\xa4\xbe', 'Current session': '\xe0\xa4\xb5\xe0\xa4\xb0\xe0\xa5\x8d\xe0\xa4\xa4\xe0\xa4\xae\xe0\xa4\xbe\xe0\xa4\xa8 \xe0\xa4\xb8\xe0\xa5\x87\xe0\xa4\xb6\xe0\xa4\xa8', 'DB Model': 'DB Model', 'Database': 'Database', 'Delete:': '\xe0\xa4\xae\xe0\xa4\xbf\xe0\xa4\x9f\xe0\xa4\xbe\xe0\xa4\xa8\xe0\xa4\xbe:', 'Edit': 'Edit', 'Edit Profile': '\xe0\xa4\xaa\xe0\xa5\x8d\xe0\xa4\xb0\xe0\xa5\x8b\xe0\xa4\xab\xe0\xa4\xbc\xe0\xa4\xbe\xe0\xa4\x87\xe0\xa4\xb2 \xe0\xa4\xb8\xe0\xa4\x82\xe0\xa4\xaa\xe0\xa4\xbe\xe0\xa4\xa6\xe0\xa4\xbf\xe0\xa4\xa4 \xe0\xa4\x95\xe0\xa4\xb0\xe0\xa5\x87\xe0\xa4\x82', 'Edit This App': 'Edit This App', 'Edit current record': '\xe0\xa4\xb5\xe0\xa4\xb0\xe0\xa5\x8d\xe0\xa4\xa4\xe0\xa4\xae\xe0\xa4\xbe\xe0\xa4\xa8 \xe0\xa4\xb0\xe0\xa5\x87\xe0\xa4\x95\xe0\xa5\x89\xe0\xa4\xb0\xe0\xa5\x8d\xe0\xa4\xa1 \xe0\xa4\xb8\xe0\xa4\x82\xe0\xa4\xaa\xe0\xa4\xbe\xe0\xa4\xa6\xe0\xa4\xbf\xe0\xa4\xa4 \xe0\xa4\x95\xe0\xa4\xb0\xe0\xa5\x87\xe0\xa4\x82 ', 'Hello World': 'Hello World', 'Hello from MyApp': 'Hello from MyApp', 'Import/Export': '\xe0\xa4\x86\xe0\xa4\xaf\xe0\xa4\xbe\xe0\xa4\xa4 / \xe0\xa4\xa8\xe0\xa4\xbf\xe0\xa4\xb0\xe0\xa5\x8d\xe0\xa4\xaf\xe0\xa4\xbe\xe0\xa4\xa4', 'Index': 'Index', 'Internal State': '\xe0\xa4\x86\xe0\xa4\x82\xe0\xa4\xa4\xe0\xa4\xb0\xe0\xa4\xbf\xe0\xa4\x95 \xe0\xa4\xb8\xe0\xa5\x8d\xe0\xa4\xa5\xe0\xa4\xbf\xe0\xa4\xa4\xe0\xa4\xbf', 'Invalid Query': '\xe0\xa4\x85\xe0\xa4\xae\xe0\xa4\xbe\xe0\xa4\xa8\xe0\xa5\x8d\xe0\xa4\xaf \xe0\xa4\xaa\xe0\xa5\x8d\xe0\xa4\xb0\xe0\xa4\xb6\xe0\xa5\x8d\xe0\xa4\xa8', 'Layout': 'Layout', 'Login': '\xe0\xa4\xb2\xe0\xa5\x89\xe0\xa4\x97 \xe0\xa4\x87\xe0\xa4\xa8', 'Logout': '\xe0\xa4\xb2\xe0\xa5\x89\xe0\xa4\x97 \xe0\xa4\x86\xe0\xa4\x89\xe0\xa4\x9f', 'Lost Password': '\xe0\xa4\xaa\xe0\xa4\xbe\xe0\xa4\xb8\xe0\xa4\xb5\xe0\xa4\xb0\xe0\xa5\x8d\xe0\xa4\xa1 \xe0\xa4\x96\xe0\xa5\x8b \xe0\xa4\x97\xe0\xa4\xaf\xe0\xa4\xbe', 'Main Menu': 'Main Menu', 'Menu Model': 'Menu Model', 'New Record': '\xe0\xa4\xa8\xe0\xa4\xaf\xe0\xa4\xbe \xe0\xa4\xb0\xe0\xa5\x87\xe0\xa4\x95\xe0\xa5\x89\xe0\xa4\xb0\xe0\xa5\x8d\xe0\xa4\xa1', 'No databases in this application': '\xe0\xa4\x87\xe0\xa4\xb8 \xe0\xa4\x85\xe0\xa4\xa8\xe0\xa5\x81\xe0\xa4\xaa\xe0\xa5\x8d\xe0\xa4\xb0\xe0\xa4\xaf\xe0\xa5\x8b\xe0\xa4\x97 \xe0\xa4\xae\xe0\xa5\x87\xe0\xa4\x82 \xe0\xa4\x95\xe0\xa5\x8b\xe0\xa4\x88 \xe0\xa4\xa1\xe0\xa5\x87\xe0\xa4\x9f\xe0\xa4\xbe\xe0\xa4\xac\xe0\xa5\x87\xe0\xa4\xb8 \xe0\xa4\xa8\xe0\xa4\xb9\xe0\xa5\x80\xe0\xa4\x82 \xe0\xa4\xb9\xe0\xa5\x88\xe0\xa4\x82', 'Powered by': 'Powered by', 'Query:': '\xe0\xa4\xaa\xe0\xa5\x8d\xe0\xa4\xb0\xe0\xa4\xb6\xe0\xa5\x8d\xe0\xa4\xa8:', 'Register': '\xe0\xa4\xaa\xe0\xa4\x82\xe0\xa4\x9c\xe0\xa5\x80\xe0\xa4\x95\xe0\xa5\x83\xe0\xa4\xa4 (\xe0\xa4\xb0\xe0\xa4\x9c\xe0\xa4\xbf\xe0\xa4\xb8\xe0\xa5\x8d\xe0\xa4\x9f\xe0\xa4\xb0) \xe0\xa4\x95\xe0\xa4\xb0\xe0\xa4\xa8\xe0\xa4\xbe ', 'Rows in table': '\xe0\xa4\xa4\xe0\xa4\xbe\xe0\xa4\xb2\xe0\xa4\xbf\xe0\xa4\x95\xe0\xa4\xbe \xe0\xa4\xae\xe0\xa5\x87\xe0\xa4\x82 \xe0\xa4\xaa\xe0\xa4\x82\xe0\xa4\x95\xe0\xa5\x8d\xe0\xa4\xa4\xe0\xa4\xbf\xe0\xa4\xaf\xe0\xa4\xbe\xe0\xa4\x81 ', 'Rows selected': '\xe0\xa4\x9a\xe0\xa4\xaf\xe0\xa4\xa8\xe0\xa4\xbf\xe0\xa4\xa4 (\xe0\xa4\x9a\xe0\xa5\x81\xe0\xa4\xa8\xe0\xa5\x87 \xe0\xa4\x97\xe0\xa4\xaf\xe0\xa5\x87) \xe0\xa4\xaa\xe0\xa4\x82\xe0\xa4\x95\xe0\xa5\x8d\xe0\xa4\xa4\xe0\xa4\xbf\xe0\xa4\xaf\xe0\xa4\xbe\xe0\xa4\x81 ', 'Stylesheet': 'Stylesheet', 'Sure you want to delete this object?': '\xe0\xa4\xb8\xe0\xa5\x81\xe0\xa4\xa8\xe0\xa4\xbf\xe0\xa4\xb6\xe0\xa5\x8d\xe0\xa4\x9a\xe0\xa4\xbf\xe0\xa4\xa4 \xe0\xa4\xb9\xe0\xa5\x88\xe0\xa4\x82 \xe0\xa4\x95\xe0\xa4\xbf \xe0\xa4\x86\xe0\xa4\xaa \xe0\xa4\x87\xe0\xa4\xb8 \xe0\xa4\xb5\xe0\xa4\xb8\xe0\xa5\x8d\xe0\xa4\xa4\xe0\xa5\x81 \xe0\xa4\x95\xe0\xa5\x8b \xe0\xa4\xb9\xe0\xa4\x9f\xe0\xa4\xbe\xe0\xa4\xa8\xe0\xa4\xbe \xe0\xa4\x9a\xe0\xa4\xbe\xe0\xa4\xb9\xe0\xa4\xa4\xe0\xa5\x87 \xe0\xa4\xb9\xe0\xa5\x88\xe0\xa4\x82?', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.', 'Update:': '\xe0\xa4\x85\xe0\xa4\xa6\xe0\xa5\x8d\xe0\xa4\xaf\xe0\xa4\xa4\xe0\xa4\xa8 \xe0\xa4\x95\xe0\xa4\xb0\xe0\xa4\xa8\xe0\xa4\xbe:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.', 'View': 'View', 'Welcome %s': 'Welcome %s', 'Welcome to web2py': '\xe0\xa4\xb5\xe0\xa5\x87\xe0\xa4\xac\xe0\xa5\xa8\xe0\xa4\xaa\xe0\xa4\xbe\xe0\xa4\x87 (web2py) \xe0\xa4\xae\xe0\xa5\x87\xe0\xa4\x82 \xe0\xa4\x86\xe0\xa4\xaa\xe0\xa4\x95\xe0\xa4\xbe \xe0\xa4\xb8\xe0\xa5\x8d\xe0\xa4\xb5\xe0\xa4\xbe\xe0\xa4\x97\xe0\xa4\xa4 \xe0\xa4\xb9\xe0\xa5\x88', 'appadmin is disabled because insecure channel': '\xe0\xa4\x85\xe0\xa4\xaa \xe0\xa4\x86\xe0\xa4\xa1\xe0\xa4\xae\xe0\xa4\xbf\xe0\xa4\xa8 (appadmin) \xe0\xa4\x85\xe0\xa4\x95\xe0\xa5\x8d\xe0\xa4\xb7\xe0\xa4\xae \xe0\xa4\xb9\xe0\xa5\x88 \xe0\xa4\x95\xe0\xa5\x8d\xe0\xa4\xaf\xe0\xa5\x8b\xe0\xa4\x82\xe0\xa4\x95\xe0\xa4\xbf \xe0\xa4\x85\xe0\xa4\xb8\xe0\xa5\x81\xe0\xa4\xb0\xe0\xa4\x95\xe0\xa5\x8d\xe0\xa4\xb7\xe0\xa4\xbf\xe0\xa4\xa4 \xe0\xa4\x9a\xe0\xa5\x88\xe0\xa4\xa8\xe0\xa4\xb2', 'cache': 'cache', 'change password': 'change password', 'Online examples': '\xe0\xa4\x91\xe0\xa4\xa8\xe0\xa4\xb2\xe0\xa4\xbe\xe0\xa4\x87\xe0\xa4\xa8 \xe0\xa4\x89\xe0\xa4\xa6\xe0\xa4\xbe\xe0\xa4\xb9\xe0\xa4\xb0\xe0\xa4\xa3 \xe0\xa4\x95\xe0\xa5\x87 \xe0\xa4\xb2\xe0\xa4\xbf\xe0\xa4\x8f \xe0\xa4\xaf\xe0\xa4\xb9\xe0\xa4\xbe\xe0\xa4\x81 \xe0\xa4\x95\xe0\xa5\x8d\xe0\xa4\xb2\xe0\xa4\xbf\xe0\xa4\x95 \xe0\xa4\x95\xe0\xa4\xb0\xe0\xa5\x87\xe0\xa4\x82', 'Administrative interface': '\xe0\xa4\xaa\xe0\xa5\x8d\xe0\xa4\xb0\xe0\xa4\xb6\xe0\xa4\xbe\xe0\xa4\xb8\xe0\xa4\xa8\xe0\xa4\xbf\xe0\xa4\x95 \xe0\xa4\x87\xe0\xa4\x82\xe0\xa4\x9f\xe0\xa4\xb0\xe0\xa4\xab\xe0\xa5\x87\xe0\xa4\xb8 \xe0\xa4\x95\xe0\xa5\x87 \xe0\xa4\xb2\xe0\xa4\xbf\xe0\xa4\x8f \xe0\xa4\xaf\xe0\xa4\xb9\xe0\xa4\xbe\xe0\xa4\x81 \xe0\xa4\x95\xe0\xa5\x8d\xe0\xa4\xb2\xe0\xa4\xbf\xe0\xa4\x95 \xe0\xa4\x95\xe0\xa4\xb0\xe0\xa5\x87\xe0\xa4\x82', 'customize me!': '\xe0\xa4\xae\xe0\xa5\x81\xe0\xa4\x9d\xe0\xa5\x87 \xe0\xa4\x85\xe0\xa4\xa8\xe0\xa5\x81\xe0\xa4\x95\xe0\xa5\x82\xe0\xa4\xb2\xe0\xa4\xbf\xe0\xa4\xa4 (\xe0\xa4\x95\xe0\xa4\xb8\xe0\xa5\x8d\xe0\xa4\x9f\xe0\xa4\xae\xe0\xa4\xbe\xe0\xa4\x87\xe0\xa4\x9c\xe0\xa4\xbc) \xe0\xa4\x95\xe0\xa4\xb0\xe0\xa5\x87\xe0\xa4\x82!', 'data uploaded': '\xe0\xa4\xa1\xe0\xa4\xbe\xe0\xa4\x9f\xe0\xa4\xbe \xe0\xa4\x85\xe0\xa4\xaa\xe0\xa4\xb2\xe0\xa5\x8b\xe0\xa4\xa1 \xe0\xa4\xb8\xe0\xa4\xae\xe0\xa5\x8d\xe0\xa4\xaa\xe0\xa4\xa8\xe0\xa5\x8d\xe0\xa4\xa8 ', 'database': '\xe0\xa4\xa1\xe0\xa5\x87\xe0\xa4\x9f\xe0\xa4\xbe\xe0\xa4\xac\xe0\xa5\x87\xe0\xa4\xb8', 'database %s select': '\xe0\xa4\xa1\xe0\xa5\x87\xe0\xa4\x9f\xe0\xa4\xbe\xe0\xa4\xac\xe0\xa5\x87\xe0\xa4\xb8 %s \xe0\xa4\x9a\xe0\xa5\x81\xe0\xa4\xa8\xe0\xa5\x80 \xe0\xa4\xb9\xe0\xa5\x81\xe0\xa4\x88', 'db': 'db', 'design': '\xe0\xa4\xb0\xe0\xa4\x9a\xe0\xa4\xa8\xe0\xa4\xbe \xe0\xa4\x95\xe0\xa4\xb0\xe0\xa5\x87\xe0\xa4\x82', 'done!': '\xe0\xa4\xb9\xe0\xa5\x8b \xe0\xa4\x97\xe0\xa4\xaf\xe0\xa4\xbe!', 'edit profile': 'edit profile', 'export as csv file': 'csv \xe0\xa4\xab\xe0\xa4\xbc\xe0\xa4\xbe\xe0\xa4\x87\xe0\xa4\xb2 \xe0\xa4\x95\xe0\xa5\x87 \xe0\xa4\xb0\xe0\xa5\x82\xe0\xa4\xaa \xe0\xa4\xae\xe0\xa5\x87\xe0\xa4\x82 \xe0\xa4\xa8\xe0\xa4\xbf\xe0\xa4\xb0\xe0\xa5\x8d\xe0\xa4\xaf\xe0\xa4\xbe\xe0\xa4\xa4', 'insert new': '\xe0\xa4\xa8\xe0\xa4\xaf\xe0\xa4\xbe \xe0\xa4\xa1\xe0\xa4\xbe\xe0\xa4\xb2\xe0\xa5\x87\xe0\xa4\x82', 'insert new %s': '\xe0\xa4\xa8\xe0\xa4\xaf\xe0\xa4\xbe %s \xe0\xa4\xa1\xe0\xa4\xbe\xe0\xa4\xb2\xe0\xa5\x87\xe0\xa4\x82', 'invalid request': '\xe0\xa4\x85\xe0\xa4\xb5\xe0\xa5\x88\xe0\xa4\xa7 \xe0\xa4\x85\xe0\xa4\xa8\xe0\xa5\x81\xe0\xa4\xb0\xe0\xa5\x8b\xe0\xa4\xa7', 'login': 'login', 'logout': 'logout', 'new record inserted': '\xe0\xa4\xa8\xe0\xa4\xaf\xe0\xa4\xbe \xe0\xa4\xb0\xe0\xa5\x87\xe0\xa4\x95\xe0\xa5\x89\xe0\xa4\xb0\xe0\xa5\x8d\xe0\xa4\xa1 \xe0\xa4\xa1\xe0\xa4\xbe\xe0\xa4\xb2\xe0\xa4\xbe', 'next 100 rows': '\xe0\xa4\x85\xe0\xa4\x97\xe0\xa4\xb2\xe0\xa5\x87 100 \xe0\xa4\xaa\xe0\xa4\x82\xe0\xa4\x95\xe0\xa5\x8d\xe0\xa4\xa4\xe0\xa4\xbf\xe0\xa4\xaf\xe0\xa4\xbe\xe0\xa4\x81', 'or import from csv file': '\xe0\xa4\xaf\xe0\xa4\xbe csv \xe0\xa4\xab\xe0\xa4\xbc\xe0\xa4\xbe\xe0\xa4\x87\xe0\xa4\xb2 \xe0\xa4\xb8\xe0\xa5\x87 \xe0\xa4\x86\xe0\xa4\xaf\xe0\xa4\xbe\xe0\xa4\xa4', 'previous 100 rows': '\xe0\xa4\xaa\xe0\xa4\xbf\xe0\xa4\x9b\xe0\xa4\xb2\xe0\xa5\x87 100 \xe0\xa4\xaa\xe0\xa4\x82\xe0\xa4\x95\xe0\xa5\x8d\xe0\xa4\xa4\xe0\xa4\xbf\xe0\xa4\xaf\xe0\xa4\xbe\xe0\xa4\x81', 'record': 'record', 'record does not exist': '\xe0\xa4\xb0\xe0\xa4\xbf\xe0\xa4\x95\xe0\xa5\x89\xe0\xa4\xb0\xe0\xa5\x8d\xe0\xa4\xa1 \xe0\xa4\xae\xe0\xa5\x8c\xe0\xa4\x9c\xe0\xa5\x82\xe0\xa4\xa6 \xe0\xa4\xa8\xe0\xa4\xb9\xe0\xa5\x80\xe0\xa4\x82 \xe0\xa4\xb9\xe0\xa5\x88', 'record id': '\xe0\xa4\xb0\xe0\xa4\xbf\xe0\xa4\x95\xe0\xa5\x89\xe0\xa4\xb0\xe0\xa5\x8d\xe0\xa4\xa1 \xe0\xa4\xaa\xe0\xa4\xb9\xe0\xa4\x9a\xe0\xa4\xbe\xe0\xa4\xa8\xe0\xa4\x95\xe0\xa4\xb0\xe0\xa5\x8d\xe0\xa4\xa4\xe0\xa4\xbe (\xe0\xa4\x86\xe0\xa4\x88\xe0\xa4\xa1\xe0\xa5\x80)', 'register': 'register', 'selected': '\xe0\xa4\x9a\xe0\xa5\x81\xe0\xa4\xa8\xe0\xa4\xbe \xe0\xa4\xb9\xe0\xa5\x81\xe0\xa4\x86', 'state': '\xe0\xa4\xb8\xe0\xa5\x8d\xe0\xa4\xa5\xe0\xa4\xbf\xe0\xa4\xa4\xe0\xa4\xbf', 'table': '\xe0\xa4\xa4\xe0\xa4\xbe\xe0\xa4\xb2\xe0\xa4\xbf\xe0\xa4\x95\xe0\xa4\xbe', 'unable to parse csv file': 'csv \xe0\xa4\xab\xe0\xa4\xbc\xe0\xa4\xbe\xe0\xa4\x87\xe0\xa4\xb2 \xe0\xa4\xaa\xe0\xa4\xbe\xe0\xa4\xb0\xe0\xa5\x8d\xe0\xa4\xb8 \xe0\xa4\x95\xe0\xa4\xb0\xe0\xa4\xa8\xe0\xa5\x87 \xe0\xa4\xae\xe0\xa5\x87\xe0\xa4\x82 \xe0\xa4\x85\xe0\xa4\xb8\xe0\xa4\xae\xe0\xa4\xb0\xe0\xa5\x8d\xe0\xa4\xa5', }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"Uaktualnij" jest dodatkowym wyra\xc5\xbceniem postaci "pole1=\'nowawarto\xc5\x9b\xc4\x87\'". Nie mo\xc5\xbcesz uaktualni\xc4\x87 lub usun\xc4\x85\xc4\x87 wynik\xc3\xb3w z JOIN:', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s rows deleted': 'Wierszy usuni\xc4\x99tych: %s', '%s rows updated': 'Wierszy uaktualnionych: %s', 'Available databases and tables': 'Dost\xc4\x99pne bazy danych i tabele', 'Cannot be empty': 'Nie mo\xc5\xbce by\xc4\x87 puste', 'Change Password': 'Change Password', 'Check to delete': 'Zaznacz aby usun\xc4\x85\xc4\x87', 'Controller': 'Controller', 'Copyright': 'Copyright', 'Current request': 'Aktualne \xc5\xbc\xc4\x85danie', 'Current response': 'Aktualna odpowied\xc5\xba', 'Current session': 'Aktualna sesja', 'DB Model': 'DB Model', 'Database': 'Database', 'Delete:': 'Usu\xc5\x84:', 'Edit': 'Edit', 'Edit Profile': 'Edit Profile', 'Edit This App': 'Edit This App', 'Edit current record': 'Edytuj aktualny rekord', 'Hello World': 'Witaj \xc5\x9awiecie', 'Import/Export': 'Importuj/eksportuj', 'Index': 'Index', 'Internal State': 'Stan wewn\xc4\x99trzny', 'Invalid Query': 'B\xc5\x82\xc4\x99dne zapytanie', 'Layout': 'Layout', 'Login': 'Zaloguj', 'Logout': 'Logout', 'Lost Password': 'Przypomnij has\xc5\x82o', 'Main Menu': 'Main Menu', 'Menu Model': 'Menu Model', 'New Record': 'Nowy rekord', 'No databases in this application': 'Brak baz danych w tej aplikacji', 'Powered by': 'Powered by', 'Query:': 'Zapytanie:', 'Register': 'Zarejestruj', 'Rows in table': 'Wiersze w tabeli', 'Rows selected': 'Wybrane wiersze', 'Stylesheet': 'Stylesheet', 'Sure you want to delete this object?': 'Czy na pewno chcesz usun\xc4\x85\xc4\x87 ten obiekt?', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': '"Zapytanie" jest warunkiem postaci "db.tabela1.pole1==\'warto\xc5\x9b\xc4\x87\'". Takie co\xc5\x9b jak "db.tabela1.pole1==db.tabela2.pole2" oznacza SQL JOIN.', 'Update:': 'Uaktualnij:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'U\xc5\xbcyj (...)&(...) jako AND, (...)|(...) jako OR oraz ~(...) jako NOT do tworzenia bardziej skomplikowanych zapyta\xc5\x84.', 'View': 'View', 'Welcome %s': 'Welcome %s', 'Welcome to web2py': 'Witaj w web2py', 'appadmin is disabled because insecure channel': 'appadmin is disabled because insecure channel', 'cache': 'cache', 'change password': 'change password', 'Online examples': 'Kliknij aby przej\xc5\x9b\xc4\x87 do interaktywnych przyk\xc5\x82ad\xc3\xb3w', 'Administrative interface': 'Kliknij aby przej\xc5\x9b\xc4\x87 do panelu administracyjnego', 'customize me!': 'dostosuj mnie!', 'data uploaded': 'dane wys\xc5\x82ane', 'database': 'baza danych', 'database %s select': 'wyb\xc3\xb3r z bazy danych %s', 'db': 'baza danych', 'design': 'projektuj', 'done!': 'zrobione!', 'edit profile': 'edit profile', 'export as csv file': 'eksportuj jako plik csv', 'insert new': 'wstaw nowy rekord tabeli', 'insert new %s': 'wstaw nowy rekord do tabeli %s', 'invalid request': 'B\xc5\x82\xc4\x99dne \xc5\xbc\xc4\x85danie', 'login': 'login', 'logout': 'logout', 'new record inserted': 'nowy rekord zosta\xc5\x82 wstawiony', 'next 100 rows': 'nast\xc4\x99pne 100 wierszy', 'or import from csv file': 'lub zaimportuj z pliku csv', 'previous 100 rows': 'poprzednie 100 wierszy', 'record': 'record', 'record does not exist': 'rekord nie istnieje', 'record id': 'id rekordu', 'register': 'register', 'selected': 'wybranych', 'state': 'stan', 'table': 'tabela', 'unable to parse csv file': 'nie mo\xc5\xbcna sparsowa\xc4\x87 pliku csv', }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"actualice" es una expresión opcional como "campo1=\'nuevo_valor\'". No se puede actualizar o eliminar resultados de un JOIN', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s rows deleted': '%s filas eliminadas', '%s rows updated': '%s filas actualizadas', '(something like "it-it")': '(algo como "it-it")', 'A new version of web2py is available': 'Hay una nueva versión de web2py disponible', 'A new version of web2py is available: %s': 'Hay una nueva versión de web2py disponible: %s', 'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.': 'ATENCION: Inicio de sesión requiere una conexión segura (HTTPS) o localhost.', 'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.': 'ATENCION: NO EJECUTE VARIAS PRUEBAS SIMULTANEAMENTE, NO SON THREAD SAFE.', 'ATTENTION: you cannot edit the running application!': 'ATENCION: no puede modificar la aplicación que se ejecuta!', 'About': 'Acerca de', 'About application': 'Acerca de la aplicación', 'Admin is disabled because insecure channel': 'Admin deshabilitado, el canal no es seguro', 'Admin is disabled because unsecure channel': 'Admin deshabilitado, el canal no es seguro', 'Administrator Password:': 'Contraseña del Administrador:', 'Are you sure you want to delete file "%s"?': '¿Está seguro que desea eliminar el archivo "%s"?', 'Are you sure you want to uninstall application "%s"': '¿Está seguro que desea desinstalar la aplicación "%s"', 'Are you sure you want to uninstall application "%s"?': '¿Está seguro que desea desinstalar la aplicación "%s"?', 'Authentication': 'Autenticación', 'Available databases and tables': 'Bases de datos y tablas disponibles', 'Cannot be empty': 'No puede estar vacío', 'Cannot compile: there are errors in your app. Debug it, correct errors and try again.': 'No se puede compilar: hay errores en su aplicación. Depure, corrija errores y vuelva a intentarlo.', 'Change Password': 'Cambie Contraseña', 'Check to delete': 'Marque para eliminar', 'Client IP': 'IP del Cliente', 'Controller': 'Controlador', 'Controllers': 'Controladores', 'Copyright': 'Derechos de autor', 'Create new application': 'Cree una nueva aplicación', 'Current request': 'Solicitud en curso', 'Current response': 'Respuesta en curso', 'Current session': 'Sesión en curso', 'DB Model': 'Modelo "db"', 'DESIGN': 'DISEÑO', 'Database': 'Base de datos', 'Date and Time': 'Fecha y Hora', 'Delete': 'Elimine', 'Delete:': 'Elimine:', 'Deploy on Google App Engine': 'Instale en Google App Engine', 'Description': 'Descripción', 'Design for': 'Diseño para', 'E-mail': 'Correo electrónico', 'EDIT': 'EDITAR', 'Edit': 'Editar', 'Edit Profile': 'Editar Perfil', 'Edit This App': 'Edite esta App', 'Edit application': 'Editar aplicación', 'Edit current record': 'Edite el registro actual', 'Editing file': 'Editando archivo', 'Editing file "%s"': 'Editando archivo "%s"', 'Error logs for "%(app)s"': 'Bitácora de errores en "%(app)s"', 'First name': 'Nombre', 'Functions with no doctests will result in [passed] tests.': 'Funciones sin doctests equivalen a pruebas [aceptadas].', 'Group ID': 'ID de Grupo', 'Hello World': 'Hola Mundo', 'Import/Export': 'Importar/Exportar', 'Index': 'Indice', 'Installed applications': 'Aplicaciones instaladas', 'Internal State': 'Estado Interno', 'Invalid Query': 'Consulta inválida', 'Invalid action': 'Acción inválida', 'Invalid email': 'Correo inválido', 'Language files (static strings) updated': 'Archivos de lenguaje (cadenas estáticas) actualizados', 'Languages': 'Lenguajes', 'Last name': 'Apellido', 'Last saved on:': 'Guardado en:', 'Layout': 'Diseño de página', 'License for': 'Licencia para', 'Login': 'Inicio de sesión', 'Login to the Administrative Interface': 'Inicio de sesión para la Interfaz Administrativa', 'Logout': 'Fin de sesión', 'Lost Password': 'Contraseña perdida', 'Main Menu': 'Menú principal', 'Menu Model': 'Modelo "menu"', 'Models': 'Modelos', 'Modules': 'Módulos', 'NO': 'NO', 'Name': 'Nombre', 'New Record': 'Registro nuevo', 'No databases in this application': 'No hay bases de datos en esta aplicación', 'Origin': 'Origen', 'Original/Translation': 'Original/Traducción', 'Password': 'Contraseña', 'Peeking at file': 'Visualizando archivo', 'Powered by': 'Este sitio usa', 'Query:': 'Consulta:', 'Record ID': 'ID de Registro', 'Register': 'Registrese', 'Registration key': 'Contraseña de Registro', 'Reset Password key': 'Reset Password key', 'Resolve Conflict file': 'archivo Resolución de Conflicto', 'Role': 'Rol', 'Rows in table': 'Filas en la tabla', 'Rows selected': 'Filas seleccionadas', 'Saved file hash:': 'Hash del archivo guardado:', 'Static files': 'Archivos estáticos', 'Stylesheet': 'Hoja de estilo', 'Sure you want to delete this object?': '¿Está seguro que desea eliminar este objeto?', 'Table name': 'Nombre de la tabla', 'Testing application': 'Probando aplicación', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'La "consulta" es una condición como "db.tabla1.campo1==\'valor\'". Algo como "db.tabla1.campo1==db.tabla2.campo2" resulta en un JOIN SQL.', 'The output of the file is a dictionary that was rendered by the view': 'La salida del archivo es un diccionario escenificado por la vista', 'There are no controllers': 'No hay controladores', 'There are no models': 'No hay modelos', 'There are no modules': 'No hay módulos', 'There are no static files': 'No hay archivos estáticos', 'There are no translators, only default language is supported': 'No hay traductores, sólo el lenguaje por defecto es soportado', 'There are no views': 'No hay vistas', 'This is a copy of the scaffolding application': 'Esta es una copia de la aplicación de andamiaje', 'This is the %(filename)s template': 'Esta es la plantilla %(filename)s', 'Ticket': 'Tiquete', 'Timestamp': 'Timestamp', 'Unable to check for upgrades': 'No es posible verificar la existencia de actualizaciones', 'Unable to download': 'No es posible la descarga', 'Unable to download app': 'No es posible descarga la aplicación', 'Update:': 'Actualice:', 'Upload existing application': 'Suba esta aplicación', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Use (...)&(...) para AND, (...)|(...) para OR, y ~(...) para NOT, para crear consultas más complejas.', 'User ID': 'ID de Usuario', 'View': 'Vista', 'Views': 'Vistas', 'Welcome': 'Welcome', 'Welcome %s': 'Bienvenido %s', 'Welcome to web2py': 'Bienvenido a web2py', 'Which called the function': 'La cual llamó la función', 'YES': 'SI', 'You are successfully running web2py': 'Usted está ejecutando web2py exitosamente', 'You can modify this application and adapt it to your needs': 'Usted puede modificar esta aplicación y adaptarla a sus necesidades', 'You visited the url': 'Usted visitó la url', 'about': 'acerca de', 'additional code for your application': 'código adicional para su aplicación', 'admin disabled because no admin password': ' por falta de contraseña', 'admin disabled because not supported on google app engine': 'admin deshabilitado, no es soportado en GAE', 'admin disabled because unable to access password file': 'admin deshabilitado, imposible acceder al archivo con la contraseña', 'and rename it (required):': 'y renombrela (requerido):', 'and rename it:': ' y renombrelo:', 'appadmin': 'appadmin', 'appadmin is disabled because insecure channel': 'admin deshabilitado, el canal no es seguro', 'application "%s" uninstalled': 'aplicación "%s" desinstalada', 'application compiled': 'aplicación compilada', 'application is compiled and cannot be designed': 'la aplicación está compilada y no puede ser modificada', 'cache': 'cache', 'cache, errors and sessions cleaned': 'cache, errores y sesiones eliminados', 'cannot create file': 'no es posible crear archivo', 'cannot upload file "%(filename)s"': 'no es posible subir archivo "%(filename)s"', 'change password': 'cambie contraseña', 'check all': 'marcar todos', 'clean': 'limpiar', 'Online examples': 'Ejemplos en línea', 'Administrative interface': 'Interfaz administrativa', 'click to check for upgrades': 'haga clic para buscar actualizaciones', 'compile': 'compilar', 'compiled application removed': 'aplicación compilada removida', 'controllers': 'controladores', 'create file with filename:': 'cree archivo con nombre:', 'create new application:': 'nombre de la nueva aplicación:', 'crontab': 'crontab', 'currently saved or': 'actualmente guardado o', 'customize me!': 'Adaptame!', 'data uploaded': 'datos subidos', 'database': 'base de datos', 'database %s select': 'selección en base de datos %s', 'database administration': 'administración base de datos', 'db': 'db', 'defines tables': 'define tablas', 'delete': 'eliminar', 'delete all checked': 'eliminar marcados', 'design': 'modificar', 'Documentation': 'Documentación', 'done!': 'listo!', 'edit': 'editar', 'edit controller': 'editar controlador', 'edit profile': 'editar perfil', 'errors': 'errores', 'export as csv file': 'exportar como archivo CSV', 'exposes': 'expone', 'extends': 'extiende', 'failed to reload module': 'recarga del módulo ha fallado', 'file "%(filename)s" created': 'archivo "%(filename)s" creado', 'file "%(filename)s" deleted': 'archivo "%(filename)s" eliminado', 'file "%(filename)s" uploaded': 'archivo "%(filename)s" subido', 'file "%(filename)s" was not deleted': 'archivo "%(filename)s" no fué eliminado', 'file "%s" of %s restored': 'archivo "%s" de %s restaurado', 'file changed on disk': 'archivo modificado en el disco', 'file does not exist': 'archivo no existe', 'file saved on %(time)s': 'archivo guardado %(time)s', 'file saved on %s': 'archivo guardado %s', 'help': 'ayuda', 'htmledit': 'htmledit', 'includes': 'incluye', 'insert new': 'inserte nuevo', 'insert new %s': 'inserte nuevo %s', 'internal error': 'error interno', 'invalid password': 'contraseña inválida', 'invalid request': 'solicitud inválida', 'invalid ticket': 'tiquete inválido', 'language file "%(filename)s" created/updated': 'archivo de lenguaje "%(filename)s" creado/actualizado', 'languages': 'lenguajes', 'languages updated': 'lenguajes actualizados', 'loading...': 'cargando...', 'located in the file': 'localizada en el archivo', 'login': 'inicio de sesión', 'logout': 'fin de sesión', 'lost password?': '¿olvido la contraseña?', 'merge': 'combinar', 'models': 'modelos', 'modules': 'módulos', 'new application "%s" created': 'nueva aplicación "%s" creada', 'new record inserted': 'nuevo registro insertado', 'next 100 rows': '100 filas siguientes', 'or import from csv file': 'o importar desde archivo CSV', 'or provide application url:': 'o provea URL de la aplicación:', 'pack all': 'empaquetar todo', 'pack compiled': 'empaquete compiladas', 'previous 100 rows': '100 filas anteriores', 'record': 'registro', 'record does not exist': 'el registro no existe', 'record id': 'id de registro', 'register': 'registrese', 'remove compiled': 'eliminar compiladas', 'restore': 'restaurar', 'revert': 'revertir', 'save': 'guardar', 'selected': 'seleccionado(s)', 'session expired': 'sesión expirada', 'shell': 'shell', 'site': 'sitio', 'some files could not be removed': 'algunos archivos no pudieron ser removidos', 'state': 'estado', 'static': 'estáticos', 'table': 'tabla', 'test': 'probar', 'the application logic, each URL path is mapped in one exposed function in the controller': 'la lógica de la aplicación, cada ruta URL se mapea en una función expuesta en el controlador', 'the data representation, define database tables and sets': 'la representación de datos, define tablas y conjuntos de base de datos', 'the presentations layer, views are also known as templates': 'la capa de presentación, las vistas también son llamadas plantillas', 'these files are served without processing, your images go here': 'estos archivos son servidos sin procesar, sus imágenes van aquí', 'to previous version.': 'a la versión previa.', 'translation strings for the application': 'cadenas de caracteres de traducción para la aplicación', 'try': 'intente', 'try something like': 'intente algo como', 'unable to create application "%s"': 'no es posible crear la aplicación "%s"', 'unable to delete file "%(filename)s"': 'no es posible eliminar el archivo "%(filename)s"', 'unable to parse csv file': 'no es posible analizar el archivo CSV', 'unable to uninstall "%s"': 'no es posible instalar "%s"', 'uncheck all': 'desmarcar todos', 'uninstall': 'desinstalar', 'update': 'actualizar', 'update all languages': 'actualizar todos los lenguajes', 'upload application:': 'subir aplicación:', 'upload file:': 'suba archivo:', 'versioning': 'versiones', 'view': 'vista', 'views': 'vistas', 'web2py Recent Tweets': 'Tweets Recientes de web2py', 'web2py is up to date': 'web2py está actualizado', }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" è un\'espressione opzionale come "campo1=\'nuovo valore\'". Non si può fare "update" o "delete" dei risultati di un JOIN ', '%Y-%m-%d': '%d/%m/%Y', '%Y-%m-%d %H:%M:%S': '%d/%m/%Y %H:%M:%S', '%s rows deleted': '%s righe ("record") cancellate', '%s rows updated': '%s righe ("record") modificate', 'Available databases and tables': 'Database e tabelle disponibili', 'Cannot be empty': 'Non può essere vuoto', 'Check to delete': 'Seleziona per cancellare', 'Client IP': 'Client IP', 'Controller': 'Controller', 'Copyright': 'Copyright', 'Current request': 'Richiesta (request) corrente', 'Current response': 'Risposta (response) corrente', 'Current session': 'Sessione (session) corrente', 'DB Model': 'Modello di DB', 'Database': 'Database', 'Delete:': 'Cancella:', 'Description': 'Descrizione', 'E-mail': 'E-mail', 'Edit': 'Modifica', 'Edit This App': 'Modifica questa applicazione', 'Edit current record': 'Modifica record corrente', 'First name': 'Nome', 'Group ID': 'ID Gruppo', 'Hello World': 'Salve Mondo', 'Hello World in a flash!': 'Salve Mondo in un flash!', 'Import/Export': 'Importa/Esporta', 'Index': 'Indice', 'Internal State': 'Stato interno', 'Invalid Query': 'Richiesta (query) non valida', 'Invalid email': 'Email non valida', 'Last name': 'Cognome', 'Layout': 'Layout', 'Main Menu': 'Menu principale', 'Menu Model': 'Menu Modelli', 'Name': 'Nome', 'New Record': 'Nuovo elemento (record)', 'No databases in this application': 'Nessun database presente in questa applicazione', 'Origin': 'Origine', 'Password': 'Password', 'Powered by': 'Powered by', 'Query:': 'Richiesta (query):', 'Record ID': 'Record ID', 'Registration key': 'Chiave di Registazione', 'Reset Password key': 'Resetta chiave Password ', 'Role': 'Ruolo', 'Rows in table': 'Righe nella tabella', 'Rows selected': 'Righe selezionate', 'Stylesheet': 'Foglio di stile (stylesheet)', 'Sure you want to delete this object?': 'Vuoi veramente cancellare questo oggetto?', 'Table name': 'Nome tabella', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'La richiesta (query) è una condizione come ad esempio "db.tabella1.campo1==\'valore\'". Una condizione come "db.tabella1.campo1==db.tabella2.campo2" produce un "JOIN" SQL.', 'The output of the file is a dictionary that was rendered by the view': 'L\'output del file è un "dictionary" che è stato visualizzato dalla vista', 'This is a copy of the scaffolding application': "Questa è una copia dell'applicazione di base (scaffold)", 'Timestamp': 'Ora (timestamp)', 'Update:': 'Aggiorna:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Per costruire richieste (query) più complesse si usano (...)&(...) come "e" (AND), (...)|(...) come "o" (OR), e ~(...) come negazione (NOT).', 'User ID': 'ID Utente', 'View': 'Vista', 'Welcome %s': 'Benvenuto %s', 'Welcome to web2py': 'Benvenuto su web2py', 'Which called the function': 'che ha chiamato la funzione', 'You are successfully running web2py': 'Stai eseguendo web2py con successo', 'You can modify this application and adapt it to your needs': 'Puoi modificare questa applicazione adattandola alle tue necessità', 'You visited the url': "Hai visitato l'URL", 'appadmin is disabled because insecure channel': 'Amministrazione (appadmin) disabilitata: comunicazione non sicura', 'cache': 'cache', 'change password': 'Cambia password', 'Online examples': 'Vedere gli esempi', 'Administrative interface': "Interfaccia amministrativa", 'customize me!': 'Personalizzami!', 'data uploaded': 'dati caricati', 'database': 'database', 'database %s select': 'database %s select', 'db': 'db', 'design': 'progetta', 'Documentation': 'Documentazione', 'done!': 'fatto!', 'edit profile': 'modifica profilo', 'export as csv file': 'esporta come file CSV', 'hello world': 'salve mondo', 'insert new': 'inserisci nuovo', 'insert new %s': 'inserisci nuovo %s', 'invalid request': 'richiesta non valida', 'located in the file': 'presente nel file', 'login': 'accesso', 'logout': 'uscita', 'lost password?': 'dimenticato la password?', 'new record inserted': 'nuovo record inserito', 'next 100 rows': 'prossime 100 righe', 'not authorized': 'non autorizzato', 'or import from csv file': 'oppure importa da file CSV', 'previous 100 rows': '100 righe precedenti', 'record': 'record', 'record does not exist': 'il record non esiste', 'record id': 'record id', 'register': 'registrazione', 'selected': 'selezionato', 'state': 'stato', 'table': 'tabella', 'unable to parse csv file': 'non riesco a decodificare questo file CSV', }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"Изменить" - необязательное выражение вида "field1=\'новое значение\'". Результаты операции JOIN нельзя изменить или удалить.', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s rows deleted': '%s строк удалено', '%s rows updated': '%s строк изменено', 'Available databases and tables': 'Базы данных и таблицы', 'Cannot be empty': 'Пустое значение недопустимо', 'Change Password': 'Смените пароль', 'Check to delete': 'Удалить', 'Check to delete:': 'Удалить:', 'Client IP': 'Client IP', 'Current request': 'Текущий запрос', 'Current response': 'Текущий ответ', 'Current session': 'Текущая сессия', 'Delete:': 'Удалить:', 'Description': 'Описание', 'E-mail': 'E-mail', 'Edit Profile': 'Редактировать профиль', 'Edit current record': 'Редактировать текущую запись', 'First name': 'Имя', 'Group ID': 'Group ID', 'Hello World': 'Заработало!', 'Import/Export': 'Импорт/экспорт', 'Internal State': 'Внутренне состояние', 'Invalid Query': 'Неверный запрос', 'Invalid email': 'Неверный email', 'Invalid login': 'Неверный логин', 'Invalid password': 'Неверный пароль', 'Last name': 'Фамилия', 'Logged in': 'Вход выполнен', 'Logged out': 'Выход выполнен', 'Login': 'Вход', 'Logout': 'Выход', 'Lost Password': 'Забыли пароль?', 'Name': 'Name', 'New Record': 'Новая запись', 'New password': 'Новый пароль', 'No databases in this application': 'В приложении нет баз данных', 'Old password': 'Старый пароль', 'Origin': 'Происхождение', 'Password': 'Пароль', "Password fields don't match": 'Пароли не совпадают', 'Query:': 'Запрос:', 'Record ID': 'ID записи', 'Register': 'Зарегистрироваться', 'Registration key': 'Ключ регистрации', 'Remember me (for 30 days)': 'Запомнить меня (на 30 дней)', 'Reset Password key': 'Сбросить ключ пароля', 'Role': 'Роль', 'Rows in table': 'Строк в таблице', 'Rows selected': 'Выделено строк', 'Submit': 'Отправить', 'Sure you want to delete this object?': 'Подтвердите удаление объекта', 'Table name': 'Имя таблицы', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': '"Запрос" - это условие вида "db.table1.field1==\'значение\'". Выражение вида "db.table1.field1==db.table2.field2" формирует SQL JOIN.', 'Timestamp': 'Отметка времени', 'Update:': 'Изменить:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Для построение сложных запросов используйте операторы "И": (...)&(...), "ИЛИ": (...)|(...), "НЕ": ~(...).', 'User %(id)s Logged-in': 'Пользователь %(id)s вошёл', 'User %(id)s Logged-out': 'Пользователь %(id)s вышел', 'User %(id)s Password changed': 'Пользователь %(id)s сменил пароль', 'User %(id)s Profile updated': 'Пользователь %(id)s обновил профиль', 'User %(id)s Registered': 'Пользователь %(id)s зарегистрировался', 'User ID': 'ID пользователя', 'Verify Password': 'Повторите пароль', 'Welcome to web2py': 'Добро пожаловать в web2py', 'Online examples': 'примеры он-лайн', 'Administrative interface': 'административный интерфейс', 'customize me!': 'настройте внешний вид!', 'data uploaded': 'данные загружены', 'database': 'база данных', 'database %s select': 'выбор базы данных %s', 'db': 'БД', 'design': 'дизайн', 'done!': 'готово!', 'export as csv file': 'экспорт в csv-файл', 'insert new': 'добавить', 'insert new %s': 'добавить %s', 'invalid request': 'неверный запрос', 'login': 'вход', 'logout': 'выход', 'new record inserted': 'новая запись добавлена', 'next 100 rows': 'следующие 100 строк', 'or import from csv file': 'или импорт из csv-файла', 'password': 'пароль', 'previous 100 rows': 'предыдущие 100 строк', 'profile': 'профиль', 'record does not exist': 'запись не найдена', 'record id': 'id записи', 'selected': 'выбрано', 'state': 'состояние', 'table': 'таблица', 'unable to parse csv file': 'нечитаемый csv-файл', }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"Uaktualnij" jest dodatkowym wyra\xc5\xbceniem postaci "pole1=\'nowawarto\xc5\x9b\xc4\x87\'". Nie mo\xc5\xbcesz uaktualni\xc4\x87 lub usun\xc4\x85\xc4\x87 wynik\xc3\xb3w z JOIN:', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s rows deleted': 'Wierszy usuni\xc4\x99tych: %s', '%s rows updated': 'Wierszy uaktualnionych: %s', 'Authentication': 'Uwierzytelnienie', 'Available databases and tables': 'Dost\xc4\x99pne bazy danych i tabele', 'Cannot be empty': 'Nie mo\xc5\xbce by\xc4\x87 puste', 'Change Password': 'Zmie\xc5\x84 has\xc5\x82o', 'Check to delete': 'Zaznacz aby usun\xc4\x85\xc4\x87', 'Check to delete:': 'Zaznacz aby usun\xc4\x85\xc4\x87:', 'Client IP': 'IP klienta', 'Controller': 'Kontroler', 'Copyright': 'Copyright', 'Current request': 'Aktualne \xc5\xbc\xc4\x85danie', 'Current response': 'Aktualna odpowied\xc5\xba', 'Current session': 'Aktualna sesja', 'DB Model': 'Model bazy danych', 'Database': 'Baza danych', 'Delete:': 'Usu\xc5\x84:', 'Description': 'Opis', 'E-mail': 'Adres e-mail', 'Edit': 'Edycja', 'Edit Profile': 'Edytuj profil', 'Edit This App': 'Edytuj t\xc4\x99 aplikacj\xc4\x99', 'Edit current record': 'Edytuj obecny rekord', 'First name': 'Imi\xc4\x99', 'Function disabled': 'Funkcja wy\xc5\x82\xc4\x85czona', 'Group ID': 'ID grupy', 'Hello World': 'Witaj \xc5\x9awiecie', 'Import/Export': 'Importuj/eksportuj', 'Index': 'Indeks', 'Internal State': 'Stan wewn\xc4\x99trzny', 'Invalid Query': 'B\xc5\x82\xc4\x99dne zapytanie', 'Invalid email': 'B\xc5\x82\xc4\x99dny adres email', 'Last name': 'Nazwisko', 'Layout': 'Uk\xc5\x82ad', 'Login': 'Zaloguj', 'Logout': 'Wyloguj', 'Lost Password': 'Przypomnij has\xc5\x82o', 'Main Menu': 'Menu g\xc5\x82\xc3\xb3wne', 'Menu Model': 'Model menu', 'Name': 'Nazwa', 'New Record': 'Nowy rekord', 'No databases in this application': 'Brak baz danych w tej aplikacji', 'Origin': '\xc5\xb9r\xc3\xb3d\xc5\x82o', 'Password': 'Has\xc5\x82o', "Password fields don't match": 'Pola has\xc5\x82a nie s\xc4\x85 zgodne ze sob\xc4\x85', 'Powered by': 'Zasilane przez', 'Query:': 'Zapytanie:', 'Record ID': 'ID rekordu', 'Register': 'Zarejestruj', 'Registration key': 'Klucz rejestracji', 'Role': 'Rola', 'Rows in table': 'Wiersze w tabeli', 'Rows selected': 'Wybrane wiersze', 'Stylesheet': 'Arkusz styl\xc3\xb3w', 'Submit': 'Wy\xc5\x9blij', 'Sure you want to delete this object?': 'Czy na pewno chcesz usun\xc4\x85\xc4\x87 ten obiekt?', 'Table name': 'Nazwa tabeli', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': '"Zapytanie" jest warunkiem postaci "db.tabela1.pole1==\'warto\xc5\x9b\xc4\x87\'". Takie co\xc5\x9b jak "db.tabela1.pole1==db.tabela2.pole2" oznacza SQL JOIN.', 'Timestamp': 'Znacznik czasu', 'Update:': 'Uaktualnij:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'U\xc5\xbcyj (...)&(...) jako AND, (...)|(...) jako OR oraz ~(...) jako NOT do tworzenia bardziej skomplikowanych zapyta\xc5\x84.', 'User %(id)s Registered': 'U\xc5\xbcytkownik %(id)s zosta\xc5\x82 zarejestrowany', 'User ID': 'ID u\xc5\xbcytkownika', 'Verify Password': 'Potwierd\xc5\xba has\xc5\x82o', 'View': 'Widok', 'Welcome %s': 'Welcome %s', 'Welcome to web2py': 'Witaj w web2py', 'appadmin is disabled because insecure channel': 'administracja aplikacji wy\xc5\x82\xc4\x85czona z powodu braku bezpiecznego po\xc5\x82\xc4\x85czenia', 'cache': 'cache', 'change password': 'change password', 'Online examples': 'Kliknij aby przej\xc5\x9b\xc4\x87 do interaktywnych przyk\xc5\x82ad\xc3\xb3w', 'Administrative interface': 'Kliknij aby przej\xc5\x9b\xc4\x87 do panelu administracyjnego', 'customize me!': 'dostosuj mnie!', 'data uploaded': 'dane wys\xc5\x82ane', 'database': 'baza danych', 'database %s select': 'wyb\xc3\xb3r z bazy danych %s', 'db': 'baza danych', 'design': 'projektuj', 'done!': 'zrobione!', 'edit profile': 'edit profile', 'export as csv file': 'eksportuj jako plik csv', 'insert new': 'wstaw nowy rekord tabeli', 'insert new %s': 'wstaw nowy rekord do tabeli %s', 'invalid request': 'B\xc5\x82\xc4\x99dne \xc5\xbc\xc4\x85danie', 'login': 'login', 'logout': 'logout', 'new record inserted': 'nowy rekord zosta\xc5\x82 wstawiony', 'next 100 rows': 'nast\xc4\x99pne 100 wierszy', 'or import from csv file': 'lub zaimportuj z pliku csv', 'previous 100 rows': 'poprzednie 100 wierszy', 'record': 'rekord', 'record does not exist': 'rekord nie istnieje', 'record id': 'id rekordu', 'register': 'register', 'selected': 'wybranych', 'state': 'stan', 'table': 'tabela', 'unable to parse csv file': 'nie mo\xc5\xbcna sparsowa\xc4\x87 pliku csv', }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" è un\'espressione opzionale come "campo1=\'nuovo valore\'". Non si può fare "update" o "delete" dei risultati di un JOIN ', '%Y-%m-%d': '%d/%m/%Y', '%Y-%m-%d %H:%M:%S': '%d/%m/%Y %H:%M:%S', '%s rows deleted': '%s righe ("record") cancellate', '%s rows updated': '%s righe ("record") modificate', 'Available databases and tables': 'Database e tabelle disponibili', 'Cannot be empty': 'Non può essere vuoto', 'Check to delete': 'Seleziona per cancellare', 'Client IP': 'Client IP', 'Controller': 'Controller', 'Copyright': 'Copyright', 'Current request': 'Richiesta (request) corrente', 'Current response': 'Risposta (response) corrente', 'Current session': 'Sessione (session) corrente', 'DB Model': 'Modello di DB', 'Database': 'Database', 'Delete:': 'Cancella:', 'Description': 'Descrizione', 'E-mail': 'E-mail', 'Edit': 'Modifica', 'Edit This App': 'Modifica questa applicazione', 'Edit current record': 'Modifica record corrente', 'First name': 'Nome', 'Group ID': 'ID Gruppo', 'Hello World': 'Salve Mondo', 'Hello World in a flash!': 'Salve Mondo in un flash!', 'Import/Export': 'Importa/Esporta', 'Index': 'Indice', 'Internal State': 'Stato interno', 'Invalid Query': 'Richiesta (query) non valida', 'Invalid email': 'Email non valida', 'Last name': 'Cognome', 'Layout': 'Layout', 'Main Menu': 'Menu principale', 'Menu Model': 'Menu Modelli', 'Name': 'Nome', 'New Record': 'Nuovo elemento (record)', 'No databases in this application': 'Nessun database presente in questa applicazione', 'Origin': 'Origine', 'Password': 'Password', 'Powered by': 'Powered by', 'Query:': 'Richiesta (query):', 'Record ID': 'Record ID', 'Registration key': 'Chiave di Registazione', 'Reset Password key': 'Resetta chiave Password ', 'Role': 'Ruolo', 'Rows in table': 'Righe nella tabella', 'Rows selected': 'Righe selezionate', 'Stylesheet': 'Foglio di stile (stylesheet)', 'Sure you want to delete this object?': 'Vuoi veramente cancellare questo oggetto?', 'Table name': 'Nome tabella', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'La richiesta (query) è una condizione come ad esempio "db.tabella1.campo1==\'valore\'". Una condizione come "db.tabella1.campo1==db.tabella2.campo2" produce un "JOIN" SQL.', 'The output of the file is a dictionary that was rendered by the view': 'L\'output del file è un "dictionary" che è stato visualizzato dalla vista', 'This is a copy of the scaffolding application': "Questa è una copia dell'applicazione di base (scaffold)", 'Timestamp': 'Ora (timestamp)', 'Update:': 'Aggiorna:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Per costruire richieste (query) più complesse si usano (...)&(...) come "e" (AND), (...)|(...) come "o" (OR), e ~(...) come negazione (NOT).', 'User ID': 'ID Utente', 'View': 'Vista', 'Welcome %s': 'Benvenuto %s', 'Welcome to web2py': 'Benvenuto su web2py', 'Which called the function': 'che ha chiamato la funzione', 'You are successfully running web2py': 'Stai eseguendo web2py con successo', 'You can modify this application and adapt it to your needs': 'Puoi modificare questa applicazione adattandola alle tue necessità', 'You visited the url': "Hai visitato l'URL", 'appadmin is disabled because insecure channel': 'Amministrazione (appadmin) disabilitata: comunicazione non sicura', 'cache': 'cache', 'change password': 'Cambia password', 'Online examples': 'Vedere gli esempi', 'Administrative interface': "Interfaccia amministrativa", 'customize me!': 'Personalizzami!', 'data uploaded': 'dati caricati', 'database': 'database', 'database %s select': 'database %s select', 'db': 'db', 'design': 'progetta', 'Documentation': 'Documentazione', 'done!': 'fatto!', 'edit profile': 'modifica profilo', 'export as csv file': 'esporta come file CSV', 'hello world': 'salve mondo', 'insert new': 'inserisci nuovo', 'insert new %s': 'inserisci nuovo %s', 'invalid request': 'richiesta non valida', 'located in the file': 'presente nel file', 'login': 'accesso', 'logout': 'uscita', 'lost password?': 'dimenticato la password?', 'new record inserted': 'nuovo record inserito', 'next 100 rows': 'prossime 100 righe', 'not authorized': 'non autorizzato', 'or import from csv file': 'oppure importa da file CSV', 'previous 100 rows': '100 righe precedenti', 'record': 'record', 'record does not exist': 'il record non esiste', 'record id': 'record id', 'register': 'registrazione', 'selected': 'selezionato', 'state': 'stato', 'table': 'tabella', 'unable to parse csv file': 'non riesco a decodificare questo file CSV', }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" est une expression optionnelle comme "champ1=\'nouvellevaleur\'". Vous ne pouvez mettre à jour ou supprimer les résultats d\'un JOIN', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s rows deleted': '%s rangées supprimées', '%s rows updated': '%s rangées mises à jour', 'About': 'À propos', 'Access Control': 'Contrôle d\'accès', 'Ajax Recipes': 'Recettes Ajax', 'Are you sure you want to delete this object?': 'Êtes-vous sûr de vouloir supprimer cet objet?', 'Authentication': 'Authentification', 'Available databases and tables': 'Bases de données et tables disponibles', 'Buy this book': 'Acheter ce livre', 'Cannot be empty': 'Ne peut pas être vide', 'Check to delete': 'Cliquez pour supprimer', 'Check to delete:': 'Cliquez pour supprimer:', 'Client IP': 'IP client', 'Community': 'Communauté', 'Controller': 'Contrôleur', 'Copyright': 'Copyright', 'Current request': 'Demande actuelle', 'Current response': 'Réponse actuelle', 'Current session': 'Session en cours', 'DB Model': 'Modèle DB', 'Database': 'Base de données', 'Delete:': 'Supprimer:', 'Demo': 'Démo', 'Deployment Recipes': 'Recettes de déploiement', 'Description': 'Description', 'Documentation': 'Documentation', 'Download': 'Téléchargement', 'E-mail': 'E-mail', 'Edit': 'Éditer', 'Edit This App': 'Modifier cette application', 'Edit current record': "Modifier l'enregistrement courant", 'Errors': 'Erreurs', 'FAQ': 'FAQ', 'First name': 'Prénom', 'Forms and Validators': 'Formulaires et Validateurs', 'Free Applications': 'Applications gratuites', 'Function disabled': 'Fonction désactivée', 'Group ID': 'Groupe ID', 'Groups': 'Groups', 'Hello World': 'Bonjour le monde', 'Home': 'Accueil', 'Import/Export': 'Importer/Exporter', 'Index': 'Index', 'Internal State': 'État interne', 'Introduction': 'Introduction', 'Invalid Query': 'Requête Invalide', 'Invalid email': 'E-mail invalide', 'Last name': 'Nom', 'Layout': 'Mise en page', 'Layouts': 'Layouts', 'Live chat': 'Chat live', 'Login': 'Connectez-vous', 'Lost Password': 'Mot de passe perdu', 'Main Menu': 'Menu principal', 'Menu Model': 'Menu modèle', 'Name': 'Nom', 'New Record': 'Nouvel enregistrement', 'No databases in this application': "Cette application n'a pas de bases de données", 'Origin': 'Origine', 'Other Recipes': 'Autres recettes', 'Overview': 'Présentation', 'Password': 'Mot de passe', "Password fields don't match": 'Les mots de passe ne correspondent pas', 'Plugins': 'Plugiciels', 'Powered by': 'Alimenté par', 'Preface': 'Préface', 'Python': 'Python', 'Query:': 'Requête:', 'Quick Examples': 'Examples Rapides', 'Recipes': 'Recettes', 'Record ID': 'ID d\'enregistrement', 'Register': "S'inscrire", 'Registration key': "Clé d'enregistrement", 'Remember me (for 30 days)': 'Se souvenir de moi (pendant 30 jours)', 'Request reset password': 'Demande de réinitialiser le mot clé', 'Reset Password key': 'Réinitialiser le mot clé', 'Resources': 'Ressources', 'Role': 'Rôle', 'Rows in table': 'Lignes du tableau', 'Rows selected': 'Lignes sélectionnées', 'Semantic': 'Sémantique', 'Services': 'Services', 'Stylesheet': 'Feuille de style', 'Submit': 'Soumettre', 'Support': 'Support', 'Sure you want to delete this object?': 'Êtes-vous sûr de vouloir supprimer cet objet?', 'Table name': 'Nom du tableau', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'La "query" est une condition comme "db.table1.champ1==\'valeur\'". Quelque chose comme "db.table1.champ1==db.table2.champ2" résulte en un JOIN SQL.', 'The Core': 'Le noyau', 'The Views': 'Les Vues', 'The output of the file is a dictionary that was rendered by the view': 'La sortie de ce fichier est un dictionnaire qui été restitué par la vue', 'This App': 'Cette Appli', 'This is a copy of the scaffolding application': 'Ceci est une copie de l\'application échafaudage', 'Timestamp': 'Horodatage', 'Twitter': 'Twitter', 'Update:': 'Mise à jour:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Employez (...)&(...) pour AND, (...)|(...) pour OR, and ~(...) pour NOT pour construire des requêtes plus complexes.', 'User %(id)s Logged-in': 'Utilisateur %(id)s connecté', 'User %(id)s Registered': 'Utilisateur %(id)s enregistré', 'User ID': 'ID utilisateur', 'User Voice': 'User Voice', 'Verify Password': 'Vérifiez le mot de passe', 'Videos': 'Vidéos', 'View': 'Présentation', 'Web2py': 'Web2py', 'Welcome': 'Bienvenu', 'Welcome %s': 'Bienvenue %s', 'Welcome to web2py': 'Bienvenue à web2py', 'Which called the function': 'Qui a appelé la fonction', 'You are successfully running web2py': 'Vous roulez avec succès web2py', 'You can modify this application and adapt it to your needs': 'Vous pouvez modifier cette application et l\'adapter à vos besoins', 'You visited the url': 'Vous avez visité l\'URL', 'appadmin is disabled because insecure channel': "appadmin est désactivée parce que le canal n'est pas sécurisé", 'cache': 'cache', 'change password': 'changer le mot de passe', 'Online examples': 'Exemples en ligne', 'Administrative interface': "Interface d'administration", 'customize me!': 'personnalisez-moi!', 'data uploaded': 'données téléchargées', 'database': 'base de données', 'database %s select': 'base de données %s select', 'db': 'db', 'design': 'design', 'Documentation': 'Documentation', 'done!': 'fait!', 'edit profile': 'modifier le profil', 'enter an integer between %(min)g and %(max)g': 'enter an integer between %(min)g and %(max)g', 'export as csv file': 'exporter sous forme de fichier csv', 'insert new': 'insérer un nouveau', 'insert new %s': 'insérer un nouveau %s', 'invalid request': 'requête invalide', 'located in the file': 'se trouvant dans le fichier', 'login': 'connectez-vous', 'logout': 'déconnectez-vous', 'lost password': 'mot de passe perdu', 'lost password?': 'mot de passe perdu?', 'new record inserted': 'nouvel enregistrement inséré', 'next 100 rows': '100 prochaines lignes', 'or import from csv file': "ou importer d'un fichier CSV", 'previous 100 rows': '100 lignes précédentes', 'record': 'enregistrement', 'record does not exist': "l'archive n'existe pas", 'record id': "id d'enregistrement", 'register': "s'inscrire", 'selected': 'sélectionné', 'state': 'état', 'table': 'tableau', 'unable to parse csv file': "incapable d'analyser le fichier cvs", 'Readme': "Lisez-moi", }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" é uma expressão opcional como "field1=\'newvalue\'". Não pode actualizar ou eliminar os resultados de um JOIN', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s rows deleted': '%s linhas eliminadas', '%s rows updated': '%s linhas actualizadas', 'About': 'About', 'Author Reference Auth User': 'Author Reference Auth User', 'Author Reference Auth User.username': 'Author Reference Auth User.username', 'Available databases and tables': 'bases de dados e tabelas disponíveis', 'Cannot be empty': 'não pode ser vazio', 'Category Create': 'Category Create', 'Category Select': 'Category Select', 'Check to delete': 'seleccione para eliminar', 'Comment Create': 'Comment Create', 'Comment Select': 'Comment Select', 'Content': 'Content', 'Controller': 'Controlador', 'Copyright': 'Direitos de cópia', 'Created By': 'Created By', 'Created On': 'Created On', 'Current request': 'pedido currente', 'Current response': 'resposta currente', 'Current session': 'sessão currente', 'DB Model': 'Modelo de BD', 'Database': 'Base de dados', 'Delete:': 'Eliminar:', 'Edit': 'Editar', 'Edit This App': 'Edite esta aplicação', 'Edit current record': 'Edição de registo currente', 'Email': 'Email', 'First Name': 'First Name', 'For %s #%s': 'For %s #%s', 'Hello World': 'Olá Mundo', 'Import/Export': 'Importar/Exportar', 'Index': 'Índice', 'Internal State': 'Estado interno', 'Invalid Query': 'Consulta Inválida', 'Last Name': 'Last Name', 'Layout': 'Esboço', 'Main Menu': 'Menu Principal', 'Menu Model': 'Menu do Modelo', 'Modified By': 'Modified By', 'Modified On': 'Modified On', 'Name': 'Name', 'New Record': 'Novo Registo', 'No Data': 'No Data', 'No databases in this application': 'Não há bases de dados nesta aplicação', 'Password': 'Password', 'Post Create': 'Post Create', 'Post Select': 'Post Select', 'Powered by': 'Suportado por', 'Query:': 'Interrogação:', 'Replyto Reference Post': 'Replyto Reference Post', 'Rows in table': 'Linhas numa tabela', 'Rows selected': 'Linhas seleccionadas', 'Stylesheet': 'Folha de estilo', 'Sure you want to delete this object?': 'Tem a certeza que deseja eliminar este objecto?', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'A "query" é uma condição do tipo "db.table1.field1==\'value\'". Algo como "db.table1.field1==db.table2.field2" resultaria num SQL JOIN.', 'Title': 'Title', 'Update:': 'Actualização:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Utilize (...)&(...) para AND, (...)|(...) para OR, e ~(...) para NOT para construir interrogações mais complexas.', 'Username': 'Username', 'View': 'Vista', 'Welcome %s': 'Bem-vindo(a) %s', 'Welcome to Gluonization': 'Bem vindo ao Web2py', 'Welcome to web2py': 'Bem-vindo(a) ao web2py', 'When': 'When', 'appadmin is disabled because insecure channel': 'appadmin está desactivada pois o canal é inseguro', 'cache': 'cache', 'change password': 'alterar palavra-chave', 'Online examples': 'Exemplos online', 'Administrative interface': 'Painel administrativo', 'create new category': 'create new category', 'create new comment': 'create new comment', 'create new post': 'create new post', 'customize me!': 'Personaliza-me!', 'data uploaded': 'informação enviada', 'database': 'base de dados', 'database %s select': 'selecção de base de dados %s', 'db': 'bd', 'design': 'design', 'done!': 'concluído!', 'edit category': 'edit category', 'edit comment': 'edit comment', 'edit post': 'edit post', 'edit profile': 'Editar perfil', 'export as csv file': 'exportar como ficheiro csv', 'insert new': 'inserir novo', 'insert new %s': 'inserir novo %s', 'invalid request': 'Pedido Inválido', 'login': 'login', 'logout': 'logout', 'new record inserted': 'novo registo inserido', 'next 100 rows': 'próximas 100 linhas', 'or import from csv file': 'ou importe a partir de ficheiro csv', 'previous 100 rows': '100 linhas anteriores', 'record': 'registo', 'record does not exist': 'registo inexistente', 'record id': 'id de registo', 'register': 'register', 'search category': 'search category', 'search comment': 'search comment', 'search post': 'search post', 'select category': 'select category', 'select comment': 'select comment', 'select post': 'select post', 'selected': 'seleccionado(s)', 'show category': 'show category', 'show comment': 'show comment', 'show post': 'show post', 'state': 'estado', 'table': 'tabela', 'unable to parse csv file': 'não foi possível carregar ficheiro csv', }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN', '%Y-%m-%d': '%Y.%m.%d.', '%Y-%m-%d %H:%M:%S': '%Y.%m.%d. %H:%M:%S', '%s rows deleted': '%s sorok t\xc3\xb6rl\xc5\x91dtek', '%s rows updated': '%s sorok friss\xc3\xadt\xc5\x91dtek', 'Available databases and tables': 'El\xc3\xa9rhet\xc5\x91 adatb\xc3\xa1zisok \xc3\xa9s t\xc3\xa1bl\xc3\xa1k', 'Cannot be empty': 'Nem lehet \xc3\xbcres', 'Check to delete': 'T\xc3\xb6rl\xc3\xa9shez v\xc3\xa1laszd ki', 'Client IP': 'Client IP', 'Controller': 'Controller', 'Copyright': 'Copyright', 'Current request': 'Jelenlegi lek\xc3\xa9rdez\xc3\xa9s', 'Current response': 'Jelenlegi v\xc3\xa1lasz', 'Current session': 'Jelenlegi folyamat', 'DB Model': 'DB Model', 'Database': 'Adatb\xc3\xa1zis', 'Delete:': 'T\xc3\xb6r\xc3\xb6l:', 'Description': 'Description', 'E-mail': 'E-mail', 'Edit': 'Szerkeszt', 'Edit This App': 'Alkalmaz\xc3\xa1st szerkeszt', 'Edit current record': 'Aktu\xc3\xa1lis bejegyz\xc3\xa9s szerkeszt\xc3\xa9se', 'First name': 'First name', 'Group ID': 'Group ID', 'Hello World': 'Hello Vil\xc3\xa1g', 'Import/Export': 'Import/Export', 'Index': 'Index', 'Internal State': 'Internal State', 'Invalid Query': 'Hib\xc3\xa1s lek\xc3\xa9rdez\xc3\xa9s', 'Invalid email': 'Invalid email', 'Last name': 'Last name', 'Layout': 'Szerkezet', 'Main Menu': 'F\xc5\x91men\xc3\xbc', 'Menu Model': 'Men\xc3\xbc model', 'Name': 'Name', 'New Record': '\xc3\x9aj bejegyz\xc3\xa9s', 'No databases in this application': 'Nincs adatb\xc3\xa1zis ebben az alkalmaz\xc3\xa1sban', 'Origin': 'Origin', 'Password': 'Password', 'Powered by': 'Powered by', 'Query:': 'Lek\xc3\xa9rdez\xc3\xa9s:', 'Record ID': 'Record ID', 'Registration key': 'Registration key', 'Reset Password key': 'Reset Password key', 'Role': 'Role', 'Rows in table': 'Sorok a t\xc3\xa1bl\xc3\xa1ban', 'Rows selected': 'Kiv\xc3\xa1lasztott sorok', 'Stylesheet': 'Stylesheet', 'Sure you want to delete this object?': 'Biztos t\xc3\xb6rli ezt az objektumot?', 'Table name': 'Table name', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.', 'Timestamp': 'Timestamp', 'Update:': 'Friss\xc3\xadt:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.', 'User ID': 'User ID', 'View': 'N\xc3\xa9zet', 'Welcome %s': 'Welcome %s', 'Welcome to web2py': 'Isten hozott a web2py-ban', 'appadmin is disabled because insecure channel': 'az appadmin a biztons\xc3\xa1gtalan csatorna miatt letiltva', 'cache': 'gyors\xc3\xadt\xc3\xb3t\xc3\xa1r', 'change password': 'jelsz\xc3\xb3 megv\xc3\xa1ltoztat\xc3\xa1sa', 'Online examples': 'online p\xc3\xa9ld\xc3\xa1k\xc3\xa9rt kattints ide', 'Administrative interface': 'az adminisztr\xc3\xa1ci\xc3\xb3s fel\xc3\xbclet\xc3\xa9rt kattints ide', 'customize me!': 'v\xc3\xa1ltoztass meg!', 'data uploaded': 'adat felt\xc3\xb6ltve', 'database': 'adatb\xc3\xa1zis', 'database %s select': 'adatb\xc3\xa1zis %s kiv\xc3\xa1laszt\xc3\xa1s', 'db': 'db', 'design': 'design', 'done!': 'k\xc3\xa9sz!', 'edit profile': 'profil szerkeszt\xc3\xa9se', 'export as csv file': 'export\xc3\xa1l csv f\xc3\xa1jlba', 'insert new': '\xc3\xbaj beilleszt\xc3\xa9se', 'insert new %s': '\xc3\xbaj beilleszt\xc3\xa9se %s', 'invalid request': 'hib\xc3\xa1s k\xc3\xa9r\xc3\xa9s', 'login': 'bel\xc3\xa9p', 'logout': 'kil\xc3\xa9p', 'lost password': 'elveszett jelsz\xc3\xb3', 'new record inserted': '\xc3\xbaj bejegyz\xc3\xa9s felv\xc3\xa9ve', 'next 100 rows': 'k\xc3\xb6vetkez\xc5\x91 100 sor', 'or import from csv file': 'vagy bet\xc3\xb6lt\xc3\xa9s csv f\xc3\xa1jlb\xc3\xb3l', 'previous 100 rows': 'el\xc5\x91z\xc5\x91 100 sor', 'record': 'bejegyz\xc3\xa9s', 'record does not exist': 'bejegyz\xc3\xa9s nem l\xc3\xa9tezik', 'record id': 'bejegyz\xc3\xa9s id', 'register': 'regisztr\xc3\xa1ci\xc3\xb3', 'selected': 'kiv\xc3\xa1lasztott', 'state': '\xc3\xa1llapot', 'table': 't\xc3\xa1bla', 'unable to parse csv file': 'nem lehet a csv f\xc3\xa1jlt beolvasni', }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" é uma expressão opcional como "campo1=\'novovalor\'". Você não pode atualizar ou apagar os resultados de um JOIN', '%Y-%m-%d': '%d-%m-%Y', '%Y-%m-%d %H:%M:%S': '%d-%m-%Y %H:%M:%S', '%s rows deleted': '%s linhas apagadas', '%s rows updated': '%s linhas atualizadas', 'About': 'About', 'Access Control': 'Access Control', 'Ajax Recipes': 'Ajax Recipes', 'Available databases and tables': 'Bancos de dados e tabelas disponíveis', 'Buy this book': 'Buy this book', 'Cannot be empty': 'Não pode ser vazio', 'Check to delete': 'Marque para apagar', 'Client IP': 'Client IP', 'Community': 'Community', 'Controller': 'Controlador', 'Copyright': 'Copyright', 'Current request': 'Requisição atual', 'Current response': 'Resposta atual', 'Current session': 'Sessão atual', 'DB Model': 'Modelo BD', 'Database': 'Banco de dados', 'Delete:': 'Apagar:', 'Demo': 'Demo', 'Deployment Recipes': 'Deployment Recipes', 'Description': 'Description', 'Documentation': 'Documentation', 'Download': 'Download', 'E-mail': 'E-mail', 'Edit': 'Editar', 'Edit This App': 'Edit This App', 'Edit current record': 'Editar o registro atual', 'Errors': 'Errors', 'FAQ': 'FAQ', 'First name': 'First name', 'Forms and Validators': 'Forms and Validators', 'Free Applications': 'Free Applications', 'Group ID': 'Group ID', 'Groups': 'Groups', 'Hello World': 'Olá Mundo', 'Home': 'Home', 'Import/Export': 'Importar/Exportar', 'Index': 'Início', 'Internal State': 'Estado Interno', 'Introduction': 'Introduction', 'Invalid Query': 'Consulta Inválida', 'Invalid email': 'Invalid email', 'Last name': 'Last name', 'Layout': 'Layout', 'Layouts': 'Layouts', 'Live chat': 'Live chat', 'Login': 'Autentique-se', 'Lost Password': 'Esqueceu sua senha?', 'Main Menu': 'Menu Principal', 'Menu Model': 'Modelo de Menu', 'Name': 'Name', 'New Record': 'Novo Registro', 'No databases in this application': 'Sem bancos de dados nesta aplicação', 'Origin': 'Origin', 'Other Recipes': 'Other Recipes', 'Overview': 'Overview', 'Password': 'Password', 'Plugins': 'Plugins', 'Powered by': 'Powered by', 'Preface': 'Preface', 'Python': 'Python', 'Query:': 'Consulta:', 'Quick Examples': 'Quick Examples', 'Recipes': 'Recipes', 'Record ID': 'Record ID', 'Register': 'Registre-se', 'Registration key': 'Registration key', 'Reset Password key': 'Reset Password key', 'Resources': 'Resources', 'Role': 'Role', 'Rows in table': 'Linhas na tabela', 'Rows selected': 'Linhas selecionadas', 'Semantic': 'Semantic', 'Services': 'Services', 'Stylesheet': 'Stylesheet', 'Support': 'Support', 'Sure you want to delete this object?': 'Está certo(a) que deseja apagar esse objeto ?', 'Table name': 'Table name', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'Uma "consulta" é uma condição como "db.tabela1.campo1==\'valor\'". Expressões como "db.tabela1.campo1==db.tabela2.campo2" resultam em um JOIN SQL.', 'The Core': 'The Core', 'The Views': 'The Views', 'The output of the file is a dictionary that was rendered by the view': 'The output of the file is a dictionary that was rendered by the view', 'This App': 'This App', 'This is a copy of the scaffolding application': 'This is a copy of the scaffolding application', 'Timestamp': 'Timestamp', 'Twitter': 'Twitter', 'Update:': 'Atualizar:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Use (...)&(...) para AND, (...)|(...) para OR, e ~(...) para NOT para construir consultas mais complexas.', 'User ID': 'User ID', 'User Voice': 'User Voice', 'Videos': 'Videos', 'View': 'Visualização', 'Web2py': 'Web2py', 'Welcome': 'Welcome', 'Welcome %s': 'Vem vindo %s', 'Welcome to web2py': 'Bem vindo ao web2py', 'Which called the function': 'Which called the function', 'You are successfully running web2py': 'You are successfully running web2py', 'You are successfully running web2py.': 'You are successfully running web2py.', 'You can modify this application and adapt it to your needs': 'You can modify this application and adapt it to your needs', 'You visited the url': 'You visited the url', 'appadmin is disabled because insecure channel': 'Administração desativada devido ao canal inseguro', 'cache': 'cache', 'change password': 'modificar senha', 'Online examples': 'Alguns exemplos', 'Administrative interface': 'Interface administrativa', 'customize me!': 'Personalize-me!', 'data uploaded': 'dados enviados', 'database': 'banco de dados', 'database %s select': 'Selecionar banco de dados %s', 'db': 'bd', 'design': 'design', 'Documentation': 'Documentation', 'done!': 'concluído!', 'edit profile': 'editar perfil', 'export as csv file': 'exportar como um arquivo csv', 'insert new': 'inserir novo', 'insert new %s': 'inserir novo %s', 'invalid request': 'requisição inválida', 'located in the file': 'located in the file', 'login': 'Entrar', 'logout': 'Sair', 'lost password?': 'lost password?', 'new record inserted': 'novo registro inserido', 'next 100 rows': 'próximas 100 linhas', 'or import from csv file': 'ou importar de um arquivo csv', 'previous 100 rows': '100 linhas anteriores', 'record': 'registro', 'record does not exist': 'registro não existe', 'record id': 'id do registro', 'register': 'Registre-se', 'selected': 'selecionado', 'state': 'estado', 'table': 'tabela', 'unable to parse csv file': 'não foi possível analisar arquivo csv', }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" est une expression optionnelle comme "champ1=\'nouvellevaleur\'". Vous ne pouvez mettre à jour ou supprimer les résultats d\'un JOIN', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s rows deleted': '%s rangées supprimées', '%s rows updated': '%s rangées mises à jour', 'About': 'À propos', 'Access Control': "Contrôle d'accès", 'Administrative interface': "Interface d'administration", 'Ajax Recipes': 'Recettes Ajax', 'Are you sure you want to delete this object?': 'Êtes-vous sûr de vouloir supprimer cet objet?', 'Authentication': 'Authentification', 'Available databases and tables': 'Bases de données et tables disponibles', 'Buy this book': 'Acheter ce livre', 'Cannot be empty': 'Ne peut pas être vide', 'Check to delete': 'Cliquez pour supprimer', 'Check to delete:': 'Cliquez pour supprimer:', 'Client IP': 'IP client', 'Community': 'Communauté', 'Controller': 'Contrôleur', 'Copyright': "Droit d'auteur", 'Current request': 'Demande actuelle', 'Current response': 'Réponse actuelle', 'Current session': 'Session en cours', 'DB Model': 'Modèle DB', 'Database': 'Base de données', 'Delete:': 'Supprimer:', 'Demo': 'Démo', 'Deployment Recipes': 'Recettes de déploiement ', 'Description': 'Descriptif', 'Documentation': 'Documentation', 'Download': 'Téléchargement', 'E-mail': 'Courriel', 'Edit': 'Éditer', 'Edit This App': 'Modifier cette application', 'Edit current record': "Modifier l'enregistrement courant", 'Errors': 'Erreurs', 'FAQ': 'faq', 'First name': 'Prénom', 'Forms and Validators': 'Formulaires et Validateurs', 'Free Applications': 'Applications gratuites', 'Function disabled': 'Fonction désactivée', 'Group %(group_id)s created': '%(group_id)s groupe créé', 'Group ID': 'Groupe ID', 'Group uniquely assigned to user %(id)s': "Groupe unique attribué à l'utilisateur %(id)s", 'Groups': 'Groupes', 'Hello World': 'Bonjour le monde', 'Home': 'Accueil', 'Import/Export': 'Importer/Exporter', 'Index': 'Index', 'Internal State': 'État interne', 'Introduction': 'Présentation', 'Invalid Query': 'Requête Invalide', 'Invalid email': 'Courriel invalide', 'Last name': 'Nom', 'Layout': 'Mise en page', 'Layouts': 'layouts', 'Live chat': 'Clavardage en direct', 'Logged in': 'Connecté', 'Login': 'Connectez-vous', 'Lost Password': 'Mot de passe perdu', 'Main Menu': 'Menu principal', 'Menu Model': 'Menu modèle', 'Name': 'Nom', 'New Record': 'Nouvel enregistrement', 'No databases in this application': "Cette application n'a pas de bases de données", 'Online examples': 'Exemples en ligne', 'Origin': 'Origine', 'Other Recipes': 'Autres recettes', 'Overview': 'Présentation', 'Password': 'Mot de passe', "Password fields don't match": 'Les mots de passe ne correspondent pas', 'Plugins': 'Plugiciels', 'Powered by': 'Alimenté par', 'Preface': 'Préface', 'Python': 'Python', 'Query:': 'Requête:', 'Quick Examples': 'Examples Rapides', 'Readme': 'Lisez-moi', 'Recipes': 'Recettes', 'Record %(id)s created': 'Record %(id)s created', 'Record %(id)s updated': 'Record %(id)s updated', 'Record Created': 'Record Created', 'Record ID': "ID d'enregistrement", 'Record Updated': 'Record Updated', 'Register': "S'inscrire", 'Registration key': "Clé d'enregistrement", 'Registration successful': 'Inscription réussie', 'Remember me (for 30 days)': 'Se souvenir de moi (pendant 30 jours)', 'Request reset password': 'Demande de réinitialiser le mot clé', 'Reset Password key': 'Réinitialiser le mot clé', 'Resources': 'Ressources', 'Role': 'Rôle', 'Rows in table': 'Lignes du tableau', 'Rows selected': 'Lignes sélectionnées', 'Semantic': 'Sémantique', 'Services': 'Services', 'Stylesheet': 'Feuille de style', 'Submit': 'Soumettre', 'Support': 'Soutien', 'Sure you want to delete this object?': 'Êtes-vous sûr de vouloir supprimer cet objet?', 'Table name': 'Nom du tableau', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'La "query" est une condition comme "db.table1.champ1==\'valeur\'". Quelque chose comme "db.table1.champ1==db.table2.champ2" résulte en un JOIN SQL.', 'The Core': 'Le noyau', 'The Views': 'Les Vues', 'The output of the file is a dictionary that was rendered by the view': 'La sortie de ce fichier est un dictionnaire qui été restitué par la vue', 'This App': 'Cette Appli', 'This is a copy of the scaffolding application': "Ceci est une copie de l'application échafaudage", 'Timestamp': 'Horodatage', 'Twitter': 'Twitter', 'Update:': 'Mise à jour:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Employez (...)&(...) pour AND, (...)|(...) pour OR, and ~(...) pour NOT pour construire des requêtes plus complexes.', 'User %(id)s Logged-in': 'Utilisateur %(id)s connecté', 'User %(id)s Registered': 'Utilisateur %(id)s enregistré', 'User ID': 'ID utilisateur', 'User Voice': 'User Voice', 'Verify Password': 'Vérifiez le mot de passe', 'Videos': 'Vidéos', 'View': 'Présentation', 'Web2py': 'Web2py', 'Welcome': 'Bienvenu', 'Welcome %s': 'Bienvenue %s', 'Welcome to web2py': 'Bienvenue à web2py', 'Which called the function': 'Qui a appelé la fonction', 'You are successfully running web2py': 'Vous roulez avec succès web2py', 'You can modify this application and adapt it to your needs': "Vous pouvez modifier cette application et l'adapter à vos besoins", 'You visited the url': "Vous avez visité l'URL", 'about': 'à propos', 'appadmin is disabled because insecure channel': "appadmin est désactivée parce que le canal n'est pas sécurisé", 'cache': 'cache', 'change password': 'changer le mot de passe', 'customize me!': 'personnalisez-moi!', 'data uploaded': 'données téléchargées', 'database': 'base de données', 'database %s select': 'base de données %s select', 'db': 'db', 'design': 'design', 'done!': 'fait!', 'edit profile': 'modifier le profil', 'enter an integer between %(min)g and %(max)g': 'entrer un entier compris entre %(min)g et %(max)g', 'export as csv file': 'exporter sous forme de fichier csv', 'insert new': 'insérer un nouveau', 'insert new %s': 'insérer un nouveau %s', 'invalid request': 'requête invalide', 'located in the file': 'se trouvant dans le fichier', 'login': 'connectez-vous', 'logout': 'déconnectez-vous', 'lost password': 'mot de passe perdu', 'lost password?': 'mot de passe perdu?', 'new record inserted': 'nouvel enregistrement inséré', 'next 100 rows': '100 prochaines lignes', 'or import from csv file': "ou importer d'un fichier CSV", 'password': 'mot de passe', 'please input your password again': "S'il vous plaît entrer votre mot de passe", 'previous 100 rows': '100 lignes précédentes', 'profile': 'profile', 'record': 'enregistrement', 'record does not exist': "l'archive n'existe pas", 'record id': "id d'enregistrement", 'register': "s'inscrire", 'selected': 'sélectionné', 'state': 'état', 'table': 'tableau', 'unable to parse csv file': "incapable d'analyser le fichier cvs", 'value already in database or empty': 'valeur déjà dans la base ou vide', }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"更新" 是選擇性的條件式, 格式就像 "欄位1=\'值\'". 但是 JOIN 的資料不可以使用 update 或是 delete"', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s rows deleted': '已刪除 %s 筆', '%s rows updated': '已更新 %s 筆', '(something like "it-it")': '(格式類似 "zh-tw")', 'A new version of web2py is available': '新版的 web2py 已發行', 'A new version of web2py is available: %s': '新版的 web2py 已發行: %s', 'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.': '注意: 登入管理帳號需要安全連線(HTTPS)或是在本機連線(localhost).', 'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.': '注意: 因為在測試模式不保證多執行緒安全性,也就是說不可以同時執行多個測試案例', 'ATTENTION: you cannot edit the running application!': '注意:不可編輯正在執行的應用程式!', 'About': '關於', 'About application': '關於本應用程式', 'Admin is disabled because insecure channel': '管理功能(Admin)在不安全連線環境下自動關閉', 'Admin is disabled because unsecure channel': '管理功能(Admin)在不安全連線環境下自動關閉', 'Administrator Password:': '管理員密碼:', 'Are you sure you want to delete file "%s"?': '確定要刪除檔案"%s"?', 'Are you sure you want to uninstall application "%s"': '確定要移除應用程式 "%s"', 'Are you sure you want to uninstall application "%s"?': '確定要移除應用程式 "%s"', 'Authentication': '驗證', 'Available databases and tables': '可提供的資料庫和資料表', 'Cannot be empty': '不可空白', 'Cannot compile: there are errors in your app. Debug it, correct errors and try again.': '無法編譯:應用程式中含有錯誤,請除錯後再試一次.', 'Change Password': '變更密碼', 'Check to delete': '打勾代表刪除', 'Check to delete:': '點選以示刪除:', 'Client IP': '客戶端網址(IP)', 'Controller': '控件', 'Controllers': '控件', 'Copyright': '版權所有', 'Create new application': '創建應用程式', 'Current request': '目前網路資料要求(request)', 'Current response': '目前網路資料回應(response)', 'Current session': '目前網路連線資訊(session)', 'DB Model': '資料庫模組', 'DESIGN': '設計', 'Database': '資料庫', 'Date and Time': '日期和時間', 'Delete': '刪除', 'Delete:': '刪除:', 'Deploy on Google App Engine': '配置到 Google App Engine', 'Description': '描述', 'Design for': '設計為了', 'E-mail': '電子郵件', 'EDIT': '編輯', 'Edit': '編輯', 'Edit Profile': '編輯設定檔', 'Edit This App': '編輯本應用程式', 'Edit application': '編輯應用程式', 'Edit current record': '編輯當前紀錄', 'Editing file': '編輯檔案', 'Editing file "%s"': '編輯檔案"%s"', 'Error logs for "%(app)s"': '"%(app)s"的錯誤紀錄', 'First name': '名', 'Functions with no doctests will result in [passed] tests.': '沒有 doctests 的函式會顯示 [passed].', 'Group ID': '群組編號', 'Hello World': '嗨! 世界', 'Import/Export': '匯入/匯出', 'Index': '索引', 'Installed applications': '已安裝應用程式', 'Internal State': '內部狀態', 'Invalid Query': '不合法的查詢', 'Invalid action': '不合法的動作(action)', 'Invalid email': '不合法的電子郵件', 'Language files (static strings) updated': '語言檔已更新', 'Languages': '各國語言', 'Last name': '姓', 'Last saved on:': '最後儲存時間:', 'Layout': '網頁配置', 'License for': '軟體版權為', 'Login': '登入', 'Login to the Administrative Interface': '登入到管理員介面', 'Logout': '登出', 'Lost Password': '密碼遺忘', 'Main Menu': '主選單', 'Menu Model': '選單模組(menu)', 'Models': '資料模組', 'Modules': '程式模組', 'NO': '否', 'Name': '名字', 'New Record': '新紀錄', 'No databases in this application': '這應用程式不含資料庫', 'Origin': '原文', 'Original/Translation': '原文/翻譯', 'Password': '密碼', "Password fields don't match": '密碼欄不匹配', 'Peeking at file': '選擇檔案', 'Powered by': '基於以下技術構建:', 'Query:': '查詢:', 'Record ID': '紀錄編號', 'Register': '註冊', 'Registration key': '註冊金鑰', 'Remember me (for 30 days)': '記住我(30 天)', 'Reset Password key': '重設密碼', 'Resolve Conflict file': '解決衝突檔案', 'Role': '角色', 'Rows in table': '在資料表裏的資料', 'Rows selected': '筆資料被選擇', 'Saved file hash:': '檔案雜湊值已紀錄:', 'Static files': '靜態檔案', 'Stylesheet': '網頁風格檔', 'Submit': '傳送', 'Sure you want to delete this object?': '確定要刪除此物件?', 'Table name': '資料表名稱', 'Testing application': '測試中的應用程式', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': '"查詢"是一個像 "db.表1.欄位1==\'值\'" 的條件式. 以"db.表1.欄位1==db.表2.欄位2"方式則相當於執行 JOIN SQL.', 'There are no controllers': '沒有控件(controllers)', 'There are no models': '沒有資料庫模組(models)', 'There are no modules': '沒有程式模組(modules)', 'There are no static files': '沒有靜態檔案', 'There are no translators, only default language is supported': '沒有翻譯檔,只支援原始語言', 'There are no views': '沒有視圖', 'This is the %(filename)s template': '這是%(filename)s檔案的樣板(template)', 'Ticket': '問題單', 'Timestamp': '時間標記', 'Unable to check for upgrades': '無法做升級檢查', 'Unable to download': '無法下載', 'Unable to download app': '無法下載應用程式', 'Update:': '更新:', 'Upload existing application': '更新存在的應用程式', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': '使用下列方式來組合更複雜的條件式, (...)&(...) 代表同時存在的條件, (...)|(...) 代表擇一的條件, ~(...)則代表反向條件.', 'User %(id)s Logged-in': '使用者 %(id)s 已登入', 'User %(id)s Registered': '使用者 %(id)s 已註冊', 'User ID': '使用者編號', 'Verify Password': '驗證密碼', 'View': '視圖', 'Views': '視圖', 'Welcome %s': '歡迎 %s', 'Welcome to web2py': '歡迎使用 web2py', 'YES': '是', 'about': '關於', 'appadmin is disabled because insecure channel': '因為來自非安全通道,管理介面關閉', 'cache': '快取記憶體', 'change password': '變更密碼', 'Online examples': '點此處進入線上範例', 'Administrative interface': '點此處進入管理介面', 'customize me!': '請調整我!', 'data uploaded': '資料已上傳', 'database': '資料庫', 'database %s select': '已選擇 %s 資料庫', 'db': 'db', 'design': '設計', 'done!': '完成!', 'edit profile': '編輯設定檔', 'export as csv file': '以逗號分隔檔(csv)格式匯出', 'insert new': '插入新資料', 'insert new %s': '插入新資料 %s', 'invalid request': '不合法的網路要求(request)', 'login': '登入', 'logout': '登出', 'new record inserted': '已插入新紀錄', 'next 100 rows': '往後 100 筆', 'or import from csv file': '或是從逗號分隔檔(CSV)匯入', 'previous 100 rows': '往前 100 筆', 'record': '紀錄', 'record does not exist': '紀錄不存在', 'record id': '紀錄編號', 'register': '註冊', 'selected': '已選擇', 'state': '狀態', 'table': '資料表', 'unable to parse csv file': '無法解析逗號分隔檔(csv)', }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" é uma expressão opcional como "field1=\'newvalue\'". Não pode actualizar ou eliminar os resultados de um JOIN', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s rows deleted': '%s linhas eliminadas', '%s rows updated': '%s linhas actualizadas', 'About': 'About', 'Author Reference Auth User': 'Author Reference Auth User', 'Author Reference Auth User.username': 'Author Reference Auth User.username', 'Available databases and tables': 'bases de dados e tabelas disponíveis', 'Cannot be empty': 'não pode ser vazio', 'Category Create': 'Category Create', 'Category Select': 'Category Select', 'Check to delete': 'seleccione para eliminar', 'Comment Create': 'Comment Create', 'Comment Select': 'Comment Select', 'Content': 'Content', 'Controller': 'Controlador', 'Copyright': 'Direitos de cópia', 'Created By': 'Created By', 'Created On': 'Created On', 'Current request': 'pedido currente', 'Current response': 'resposta currente', 'Current session': 'sessão currente', 'DB Model': 'Modelo de BD', 'Database': 'Base de dados', 'Delete:': 'Eliminar:', 'Edit': 'Editar', 'Edit This App': 'Edite esta aplicação', 'Edit current record': 'Edição de registo currente', 'Email': 'Email', 'First Name': 'First Name', 'For %s #%s': 'For %s #%s', 'Hello World': 'Olá Mundo', 'Import/Export': 'Importar/Exportar', 'Index': 'Índice', 'Internal State': 'Estado interno', 'Invalid Query': 'Consulta Inválida', 'Last Name': 'Last Name', 'Layout': 'Esboço', 'Main Menu': 'Menu Principal', 'Menu Model': 'Menu do Modelo', 'Modified By': 'Modified By', 'Modified On': 'Modified On', 'Name': 'Name', 'New Record': 'Novo Registo', 'No Data': 'No Data', 'No databases in this application': 'Não há bases de dados nesta aplicação', 'Password': 'Password', 'Post Create': 'Post Create', 'Post Select': 'Post Select', 'Powered by': 'Suportado por', 'Query:': 'Interrogação:', 'Replyto Reference Post': 'Replyto Reference Post', 'Rows in table': 'Linhas numa tabela', 'Rows selected': 'Linhas seleccionadas', 'Stylesheet': 'Folha de estilo', 'Sure you want to delete this object?': 'Tem a certeza que deseja eliminar este objecto?', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'A "query" é uma condição do tipo "db.table1.field1==\'value\'". Algo como "db.table1.field1==db.table2.field2" resultaria num SQL JOIN.', 'Title': 'Title', 'Update:': 'Actualização:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Utilize (...)&(...) para AND, (...)|(...) para OR, e ~(...) para NOT para construir interrogações mais complexas.', 'Username': 'Username', 'View': 'Vista', 'Welcome %s': 'Bem-vindo(a) %s', 'Welcome to Gluonization': 'Bem vindo ao Web2py', 'Welcome to web2py': 'Bem-vindo(a) ao web2py', 'When': 'When', 'appadmin is disabled because insecure channel': 'appadmin está desactivada pois o canal é inseguro', 'cache': 'cache', 'change password': 'alterar palavra-chave', 'Online examples': 'Exemplos online', 'Administrative interface': 'Painel administrativo', 'create new category': 'create new category', 'create new comment': 'create new comment', 'create new post': 'create new post', 'customize me!': 'Personaliza-me!', 'data uploaded': 'informação enviada', 'database': 'base de dados', 'database %s select': 'selecção de base de dados %s', 'db': 'bd', 'design': 'design', 'done!': 'concluído!', 'edit category': 'edit category', 'edit comment': 'edit comment', 'edit post': 'edit post', 'edit profile': 'Editar perfil', 'export as csv file': 'exportar como ficheiro csv', 'insert new': 'inserir novo', 'insert new %s': 'inserir novo %s', 'invalid request': 'Pedido Inválido', 'login': 'login', 'logout': 'logout', 'new record inserted': 'novo registo inserido', 'next 100 rows': 'próximas 100 linhas', 'or import from csv file': 'ou importe a partir de ficheiro csv', 'previous 100 rows': '100 linhas anteriores', 'record': 'registo', 'record does not exist': 'registo inexistente', 'record id': 'id de registo', 'register': 'register', 'search category': 'search category', 'search comment': 'search comment', 'search post': 'search post', 'select category': 'select category', 'select comment': 'select comment', 'select post': 'select post', 'selected': 'seleccionado(s)', 'show category': 'show category', 'show comment': 'show comment', 'show post': 'show post', 'state': 'estado', 'table': 'tabela', 'unable to parse csv file': 'não foi possível carregar ficheiro csv', }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN', '%Y-%m-%d': '%Y.%m.%d.', '%Y-%m-%d %H:%M:%S': '%Y.%m.%d. %H:%M:%S', '%s rows deleted': '%s sorok t\xc3\xb6rl\xc5\x91dtek', '%s rows updated': '%s sorok friss\xc3\xadt\xc5\x91dtek', 'Available databases and tables': 'El\xc3\xa9rhet\xc5\x91 adatb\xc3\xa1zisok \xc3\xa9s t\xc3\xa1bl\xc3\xa1k', 'Cannot be empty': 'Nem lehet \xc3\xbcres', 'Check to delete': 'T\xc3\xb6rl\xc3\xa9shez v\xc3\xa1laszd ki', 'Client IP': 'Client IP', 'Controller': 'Controller', 'Copyright': 'Copyright', 'Current request': 'Jelenlegi lek\xc3\xa9rdez\xc3\xa9s', 'Current response': 'Jelenlegi v\xc3\xa1lasz', 'Current session': 'Jelenlegi folyamat', 'DB Model': 'DB Model', 'Database': 'Adatb\xc3\xa1zis', 'Delete:': 'T\xc3\xb6r\xc3\xb6l:', 'Description': 'Description', 'E-mail': 'E-mail', 'Edit': 'Szerkeszt', 'Edit This App': 'Alkalmaz\xc3\xa1st szerkeszt', 'Edit current record': 'Aktu\xc3\xa1lis bejegyz\xc3\xa9s szerkeszt\xc3\xa9se', 'First name': 'First name', 'Group ID': 'Group ID', 'Hello World': 'Hello Vil\xc3\xa1g', 'Import/Export': 'Import/Export', 'Index': 'Index', 'Internal State': 'Internal State', 'Invalid Query': 'Hib\xc3\xa1s lek\xc3\xa9rdez\xc3\xa9s', 'Invalid email': 'Invalid email', 'Last name': 'Last name', 'Layout': 'Szerkezet', 'Main Menu': 'F\xc5\x91men\xc3\xbc', 'Menu Model': 'Men\xc3\xbc model', 'Name': 'Name', 'New Record': '\xc3\x9aj bejegyz\xc3\xa9s', 'No databases in this application': 'Nincs adatb\xc3\xa1zis ebben az alkalmaz\xc3\xa1sban', 'Origin': 'Origin', 'Password': 'Password', 'Powered by': 'Powered by', 'Query:': 'Lek\xc3\xa9rdez\xc3\xa9s:', 'Record ID': 'Record ID', 'Registration key': 'Registration key', 'Reset Password key': 'Reset Password key', 'Role': 'Role', 'Rows in table': 'Sorok a t\xc3\xa1bl\xc3\xa1ban', 'Rows selected': 'Kiv\xc3\xa1lasztott sorok', 'Stylesheet': 'Stylesheet', 'Sure you want to delete this object?': 'Biztos t\xc3\xb6rli ezt az objektumot?', 'Table name': 'Table name', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.', 'Timestamp': 'Timestamp', 'Update:': 'Friss\xc3\xadt:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.', 'User ID': 'User ID', 'View': 'N\xc3\xa9zet', 'Welcome %s': 'Welcome %s', 'Welcome to web2py': 'Isten hozott a web2py-ban', 'appadmin is disabled because insecure channel': 'az appadmin a biztons\xc3\xa1gtalan csatorna miatt letiltva', 'cache': 'gyors\xc3\xadt\xc3\xb3t\xc3\xa1r', 'change password': 'jelsz\xc3\xb3 megv\xc3\xa1ltoztat\xc3\xa1sa', 'Online examples': 'online p\xc3\xa9ld\xc3\xa1k\xc3\xa9rt kattints ide', 'Administrative interface': 'az adminisztr\xc3\xa1ci\xc3\xb3s fel\xc3\xbclet\xc3\xa9rt kattints ide', 'customize me!': 'v\xc3\xa1ltoztass meg!', 'data uploaded': 'adat felt\xc3\xb6ltve', 'database': 'adatb\xc3\xa1zis', 'database %s select': 'adatb\xc3\xa1zis %s kiv\xc3\xa1laszt\xc3\xa1s', 'db': 'db', 'design': 'design', 'done!': 'k\xc3\xa9sz!', 'edit profile': 'profil szerkeszt\xc3\xa9se', 'export as csv file': 'export\xc3\xa1l csv f\xc3\xa1jlba', 'insert new': '\xc3\xbaj beilleszt\xc3\xa9se', 'insert new %s': '\xc3\xbaj beilleszt\xc3\xa9se %s', 'invalid request': 'hib\xc3\xa1s k\xc3\xa9r\xc3\xa9s', 'login': 'bel\xc3\xa9p', 'logout': 'kil\xc3\xa9p', 'lost password': 'elveszett jelsz\xc3\xb3', 'new record inserted': '\xc3\xbaj bejegyz\xc3\xa9s felv\xc3\xa9ve', 'next 100 rows': 'k\xc3\xb6vetkez\xc5\x91 100 sor', 'or import from csv file': 'vagy bet\xc3\xb6lt\xc3\xa9s csv f\xc3\xa1jlb\xc3\xb3l', 'previous 100 rows': 'el\xc5\x91z\xc5\x91 100 sor', 'record': 'bejegyz\xc3\xa9s', 'record does not exist': 'bejegyz\xc3\xa9s nem l\xc3\xa9tezik', 'record id': 'bejegyz\xc3\xa9s id', 'register': 'regisztr\xc3\xa1ci\xc3\xb3', 'selected': 'kiv\xc3\xa1lasztott', 'state': '\xc3\xa1llapot', 'table': 't\xc3\xa1bla', 'unable to parse csv file': 'nem lehet a csv f\xc3\xa1jlt beolvasni', }
Python
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" je voliteľný výraz ako "field1=\'newvalue\'". Nemôžete upravovať alebo zmazať výsledky JOINu', '%Y-%m-%d': '%d.%m.%Y', '%Y-%m-%d %H:%M:%S': '%d.%m.%Y %H:%M:%S', '%s rows deleted': '%s zmazaných záznamov', '%s rows updated': '%s upravených záznamov', 'Available databases and tables': 'Dostupné databázy a tabuľky', 'Cannot be empty': 'Nemôže byť prázdne', 'Check to delete': 'Označiť na zmazanie', 'Controller': 'Controller', 'Copyright': 'Copyright', 'Current request': 'Aktuálna požiadavka', 'Current response': 'Aktuálna odpoveď', 'Current session': 'Aktuálne sedenie', 'DB Model': 'DB Model', 'Database': 'Databáza', 'Delete:': 'Zmazať:', 'Description': 'Popis', 'Edit': 'Upraviť', 'Edit Profile': 'Upraviť profil', 'Edit current record': 'Upraviť aktuálny záznam', 'First name': 'Krstné meno', 'Group ID': 'ID skupiny', 'Hello World': 'Ahoj svet', 'Import/Export': 'Import/Export', 'Index': 'Index', 'Internal State': 'Vnútorný stav', 'Invalid email': 'Neplatný email', 'Invalid Query': 'Neplatná otázka', 'Invalid password': 'Nesprávne heslo', 'Last name': 'Priezvisko', 'Layout': 'Layout', 'Logged in': 'Prihlásený', 'Logged out': 'Odhlásený', 'Lost Password': 'Stratené heslo?', 'Menu Model': 'Menu Model', 'Name': 'Meno', 'New Record': 'Nový záznam', 'New password': 'Nové heslo', 'No databases in this application': 'V tejto aplikácii nie sú databázy', 'Old password': 'Staré heslo', 'Origin': 'Pôvod', 'Password': 'Heslo', 'Powered by': 'Powered by', 'Query:': 'Otázka:', 'Record ID': 'ID záznamu', 'Register': 'Zaregistrovať sa', 'Registration key': 'Registračný kľúč', 'Remember me (for 30 days)': 'Zapamätaj si ma (na 30 dní)', 'Reset Password key': 'Nastaviť registračný kľúč', 'Role': 'Rola', 'Rows in table': 'riadkov v tabuľke', 'Rows selected': 'označených riadkov', 'Submit': 'Odoslať', 'Stylesheet': 'Stylesheet', 'Sure you want to delete this object?': 'Ste si istí, že chcete zmazať tento objekt?', 'Table name': 'Názov tabuľky', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': '"query" je podmienka ako "db.table1.field1==\'value\'". Niečo ako "db.table1.field1==db.table2.field2" má za výsledok SQL JOIN.', 'The output of the file is a dictionary that was rendered by the view': 'Výstup zo súboru je slovník, ktorý bol zobrazený vo view', 'This is a copy of the scaffolding application': 'Toto je kópia skeletu aplikácie', 'Timestamp': 'Časová pečiatka', 'Update:': 'Upraviť:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Použite (...)&(...) pre AND, (...)|(...) pre OR a ~(...) pre NOT na poskladanie komplexnejších otázok.', 'User %(id)s Logged-in': 'Používateľ %(id)s prihlásený', 'User %(id)s Logged-out': 'Používateľ %(id)s odhlásený', 'User %(id)s Password changed': 'Používateľ %(id)s zmenil heslo', 'User %(id)s Profile updated': 'Používateľ %(id)s upravil profil', 'User %(id)s Registered': 'Používateľ %(id)s sa zaregistroval', 'User ID': 'ID používateľa', 'Verify Password': 'Zopakujte heslo', 'View': 'Zobraziť', 'Welcome to web2py': 'Vitajte vo web2py', 'Which called the function': 'Ktorý zavolal funkciu', 'You are successfully running web2py': 'Úspešne ste spustili web2py', 'You can modify this application and adapt it to your needs': 'Môžete upraviť túto aplikáciu a prispôsobiť ju svojim potrebám', 'You visited the url': 'Navštívili ste URL', 'appadmin is disabled because insecure channel': 'appadmin je zakázaný bez zabezpečeného spojenia', 'cache': 'cache', 'Online examples': 'pre online príklady kliknite sem', 'Administrative interface': 'pre administrátorské rozhranie kliknite sem', 'customize me!': 'prispôsob ma!', 'data uploaded': 'údaje naplnené', 'database': 'databáza', 'database %s select': 'databáza %s výber', 'db': 'db', 'design': 'návrh', 'Documentation': 'Dokumentácia', 'done!': 'hotovo!', 'export as csv file': 'exportovať do csv súboru', 'insert new': 'vložiť nový záznam ', 'insert new %s': 'vložiť nový záznam %s', 'invalid request': 'Neplatná požiadavka', 'located in the file': 'nachádzajúci sa v súbore ', 'login': 'prihlásiť', 'logout': 'odhlásiť', 'lost password?': 'stratené heslo?', 'new record inserted': 'nový záznam bol vložený', 'next 100 rows': 'ďalších 100 riadkov', 'or import from csv file': 'alebo naimportovať z csv súboru', 'password': 'heslo', 'previous 100 rows': 'predchádzajúcich 100 riadkov', 'record': 'záznam', 'record does not exist': 'záznam neexistuje', 'record id': 'id záznamu', 'register': 'registrovať', 'selected': 'označených', 'state': 'stav', 'table': 'tabuľka', 'unable to parse csv file': 'nedá sa načítať csv súbor', }
Python
response.title = settings.title response.subtitle = settings.subtitle response.meta.author = '%s <%s>' % (settings.author, settings.author_email) response.meta.keywords = settings.keywords response.meta.description = settings.description response.menu = [ (T('Add image'),URL('images','addimg')==URL(),URL('images','addimg'),[]), (T('App settings'),URL('admin','index')==URL(),URL('admin','index'),[]), ]
Python
from gluon.storage import Storage settings = Storage() settings.migrate = True settings.title = 'fb_fans' settings.subtitle = 'powered by web2py' settings.author = 'you' settings.author_email = 'you@example.com' settings.keywords = '' settings.description = '' settings.layout_theme = 'Default' settings.database_uri = 'sqlite://storage.sqlite' settings.security_key = '0cbb5175-483f-4a14-8087-cbdf13d68587' settings.email_server = 'localhost' settings.email_sender = 'you@example.com' settings.email_login = '' settings.login_method = 'local' settings.login_config = '' settings.plugins = []
Python
from gluon.contrib.populate import populate from app_settings import * if not db(db.auth_user).count(): db.auth_user.insert( username='admin', first_name='Admin', last_name='Admin', password='ae5be22d505db70b591e0aa5327671be2591e6426ef5579fb60d5152a507f58cc142b365a056bfbba4bd669f80bd7949d8182049cf985d9c495354b466968886') if not db(db.settings).count(): db.settings.insert( fb_app_id = APP_ID, fb_app_secret = APP_SECRET, fb_fan_page = FAN_PAGE, lander = LANDER, header = HEADER, footer = FOOTER, invite_title = INVITE_TITLE, invite_message = INVITE_MESSAGE, force_count_title = FORCE_HEADER, force_count_number= FORCE_COUNT_NUMBER, force_message_before = FORCE_MESSAGE_BEFORE, force_message_after = FORCE_MESSAGE_AFTER, )
Python
# -*- coding: utf-8 -*- # this file is released under public domain and you can use without limitations ######################################################################### ## This scaffolding model makes your app work on Google App Engine too ######################################################################### if request.env.web2py_runtime_gae: # if running on Google App Engine db = DAL('google:datastore') # connect to Google BigTable # optional DAL('gae://namespace') session.connect(request, response, db = db) # and store sessions and tickets there ### or use the following lines to store sessions in Memcache # from gluon.contrib.memdb import MEMDB # from google.appengine.api.memcache import Client # session.connect(request, response, db = MEMDB(Client())) else: # else use a normal relational database db = DAL('sqlite://storage.sqlite') # if not, use SQLite or other DB # by default give a view/generic.extension to all actions from localhost # none otherwise. a pattern can be 'controller/function.extension' response.generic_patterns = ['*'] if request.is_local else [] ######################################################################### ## Here is sample code if you need for ## - email capabilities ## - authentication (registration, login, logout, ... ) ## - authorization (role based authorization) ## - services (xml, csv, json, xmlrpc, jsonrpc, amf, rss) ## - crud actions ## (more options discussed in gluon/tools.py) ######################################################################### from gluon.tools import Mail, Auth, Crud, Service, PluginManager, prettydate mail = Mail() # mailer auth = Auth(db) # authentication/authorization crud = Crud(db) # for CRUD helpers using auth service = Service() # for json, xml, jsonrpc, xmlrpc, amfrpc plugins = PluginManager() # for configuring plugins mail.settings.server = 'logging' or 'smtp.gmail.com:587' # your SMTP server mail.settings.sender = 'you@gmail.com' # your email mail.settings.login = 'username:password' # your credentials or None auth.settings.hmac_key = 'sha512:0cbb5175-483f-4a14-8087-cbdf13d68587' # before define_tables() ######################################## db.define_table('auth_user', Field('id','id', represent=lambda id:SPAN(id,' ',A('view',_href=URL('auth_user_read',args=id)))), Field('username', type='string', label=T('Username')), Field('first_name', type='string', label=T('First Name')), Field('last_name', type='string', label=T('Last Name')), Field('email', type='string', label=T('Email')), Field('password', type='password', readable=False, label=T('Password')), Field('created_on','datetime',default=request.now, label=T('Created On'),writable=False,readable=False), Field('modified_on','datetime',default=request.now, label=T('Modified On'),writable=False,readable=False, update=request.now), Field('registration_key',default='', writable=False,readable=False), Field('reset_password_key',default='', writable=False,readable=False), Field('registration_id',default='', writable=False,readable=False), format='%(username)s', migrate=settings.migrate) db.auth_user.first_name.requires = IS_NOT_EMPTY(error_message=auth.messages.is_empty) db.auth_user.last_name.requires = IS_NOT_EMPTY(error_message=auth.messages.is_empty) db.auth_user.password.requires = CRYPT(key=auth.settings.hmac_key) db.auth_user.username.requires = IS_NOT_IN_DB(db, db.auth_user.username) db.auth_user.registration_id.requires = IS_NOT_IN_DB(db, db.auth_user.registration_id) db.auth_user.email.requires = (IS_EMAIL(error_message=auth.messages.invalid_email), IS_NOT_IN_DB(db, db.auth_user.email)) auth.define_tables(migrate = settings.migrate) # creates all needed tables auth.settings.mailer = mail # for user email verification auth.settings.registration_requires_verification = False auth.settings.registration_requires_approval = False auth.messages.verify_email = 'Click on the link http://'+request.env.http_host+URL('default','user',args=['verify_email'])+'/%(key)s to verify your email' auth.settings.reset_password_requires_verification = True auth.messages.reset_password = 'Click on the link http://'+request.env.http_host+URL('default','user',args=['reset_password'])+'/%(key)s to reset your password' ######################################################################### ## If you need to use OpenID, Facebook, MySpace, Twitter, Linkedin, etc. ## register with janrain.com, uncomment and customize following # from gluon.contrib.login_methods.rpx_account import RPXAccount # auth.settings.actions_disabled = \ # ['register','change_password','request_reset_password'] # auth.settings.login_form = RPXAccount(request, api_key='...',domain='...', # url = "http://localhost:8000/%s/default/user/login" % request.application) ## other login methods are in gluon/contrib/login_methods ######################################################################### crud.settings.auth = None # =auth to enforce authorization on crud auth.settings.actions_disabled = ['register'] ######################################################################### ## Define your tables below (or better in another model file) for example ## ## >>> db.define_table('mytable',Field('myfield','string')) ## ## Fields can be 'string','text','password','integer','double','boolean' ## 'date','time','datetime','blob','upload', 'reference TABLENAME' ## There is an implicit 'id integer autoincrement' field ## Consult manual for more options, validators, etc. ## ## More API examples for controllers: ## ## >>> db.mytable.insert(myfield='value') ## >>> rows=db(db.mytable.myfield=='value').select(db.mytable.ALL) ## >>> for row in rows: print row.id, row.myfield ######################################################################### mail.settings.server = settings.email_server mail.settings.sender = settings.email_sender mail.settings.login = settings.email_login db.define_table('app_items', Field('user_uid', 'string', length=30, requires=IS_NOT_EMPTY()), Field('img_location', 'string'), Field('image', 'upload', length=1, requires=IS_IMAGE()), Field('img_name', 'string', length=40, requires=IS_NOT_EMPTY()), Field('invite_message', 'string', requires=IS_NOT_EMPTY()), Field('redirect', 'string', requires=IS_NOT_EMPTY()), Field('times_posted_today', 'integer', default=0, requires=IS_NOT_EMPTY()), Field('times_posted', 'integer', default=0, requires=IS_NOT_EMPTY()), Field('times_reported', 'integer', default=0, requires=IS_NOT_EMPTY()), Field('reported_by', 'text', requires=IS_NOT_EMPTY()), Field('reported_time', 'string', requires=IS_NOT_EMPTY()), ) db.define_table('settings', Field('fb_app_id', 'string', requires = IS_NOT_EMPTY()), Field('fb_app_secret', 'string', requires = IS_NOT_EMPTY()), Field('fb_fan_page', 'string', requires = IS_NOT_EMPTY()), Field('use_lander', 'boolean', default=True), Field('lander', 'text', length=65535), Field('header', 'text', length=65535), Field('footer', 'text', length=65535), Field('invite_title', 'string', length=55), Field('invite_message', 'string', length=255), Field('force_count_title', 'string'), Field('force_count_number', 'integer', default=0), Field('force_message_before', 'text', length=65535), Field('force_message_after', 'text', length=65535), ) db.settings.id.readable = False current_settings = db(db.settings).select().first()
Python
### we prepend t_ to tablenames and f_ to fieldnames for disambiguity
Python
# -*- coding: utf-8 -*- # ########################################################## # ## make sure administrator is on localhost # ########################################################### import os import socket import datetime import copy import gluon.contenttype import gluon.fileutils # ## critical --- make a copy of the environment global_env = copy.copy(globals()) global_env['datetime'] = datetime http_host = request.env.http_host.split(':')[0] remote_addr = request.env.remote_addr try: hosts = (http_host, socket.gethostname(), socket.gethostbyname(http_host), '::1','127.0.0.1','::ffff:127.0.0.1') except: hosts = (http_host, ) if request.env.http_x_forwarded_for or request.env.wsgi_url_scheme\ in ['https', 'HTTPS']: session.secure() elif (remote_addr not in hosts) and (remote_addr != "127.0.0.1"): raise HTTP(200, T('appadmin is disabled because insecure channel')) if (request.application=='admin' and not session.authorized) or \ (request.application!='admin' and not gluon.fileutils.check_credentials(request)): redirect(URL('admin', 'default', 'index')) ignore_rw = True response.view = 'appadmin.html' response.menu = [[T('design'), False, URL('admin', 'default', 'design', args=[request.application])], [T('db'), False, URL('index')], [T('state'), False, URL('state')], [T('cache'), False, URL('ccache')]] # ########################################################## # ## auxiliary functions # ########################################################### def get_databases(request): dbs = {} for (key, value) in global_env.items(): cond = False try: cond = isinstance(value, GQLDB) except: cond = isinstance(value, SQLDB) if cond: dbs[key] = value return dbs databases = get_databases(None) def eval_in_global_env(text): exec ('_ret=%s' % text, {}, global_env) return global_env['_ret'] def get_database(request): if request.args and request.args[0] in databases: return eval_in_global_env(request.args[0]) else: session.flash = T('invalid request') redirect(URL('index')) def get_table(request): db = get_database(request) if len(request.args) > 1 and request.args[1] in db.tables: return (db, request.args[1]) else: session.flash = T('invalid request') redirect(URL('index')) def get_query(request): try: return eval_in_global_env(request.vars.query) except Exception: return None def query_by_table_type(tablename,db,request=request): keyed = hasattr(db[tablename],'_primarykey') if keyed: firstkey = db[tablename][db[tablename]._primarykey[0]] cond = '>0' if firstkey.type in ['string', 'text']: cond = '!=""' qry = '%s.%s.%s%s' % (request.args[0], request.args[1], firstkey.name, cond) else: qry = '%s.%s.id>0' % tuple(request.args[:2]) return qry # ########################################################## # ## list all databases and tables # ########################################################### def index(): return dict(databases=databases) # ########################################################## # ## insert a new record # ########################################################### def insert(): (db, table) = get_table(request) form = SQLFORM(db[table], ignore_rw=ignore_rw) if form.accepts(request.vars, session): response.flash = T('new record inserted') return dict(form=form,table=db[table]) # ########################################################## # ## list all records in table and insert new record # ########################################################### def download(): import os db = get_database(request) return response.download(request,db) def csv(): import gluon.contenttype response.headers['Content-Type'] = \ gluon.contenttype.contenttype('.csv') db = get_database(request) query = get_query(request) if not query: return None response.headers['Content-disposition'] = 'attachment; filename=%s_%s.csv'\ % tuple(request.vars.query.split('.')[:2]) return str(db(query).select()) def import_csv(table, file): table.import_from_csv_file(file) def select(): import re db = get_database(request) dbname = request.args[0] regex = re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>\d+)') if len(request.args)>1 and hasattr(db[request.args[1]],'_primarykey'): regex = re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>.+)') if request.vars.query: match = regex.match(request.vars.query) if match: request.vars.query = '%s.%s.%s==%s' % (request.args[0], match.group('table'), match.group('field'), match.group('value')) else: request.vars.query = session.last_query query = get_query(request) if request.vars.start: start = int(request.vars.start) else: start = 0 nrows = 0 stop = start + 100 table = None rows = [] orderby = request.vars.orderby if orderby: orderby = dbname + '.' + orderby if orderby == session.last_orderby: if orderby[0] == '~': orderby = orderby[1:] else: orderby = '~' + orderby session.last_orderby = orderby session.last_query = request.vars.query form = FORM(TABLE(TR(T('Query:'), '', INPUT(_style='width:400px', _name='query', _value=request.vars.query or '', requires=IS_NOT_EMPTY(error_message=T("Cannot be empty")))), TR(T('Update:'), INPUT(_name='update_check', _type='checkbox', value=False), INPUT(_style='width:400px', _name='update_fields', _value=request.vars.update_fields or '')), TR(T('Delete:'), INPUT(_name='delete_check', _class='delete', _type='checkbox', value=False), ''), TR('', '', INPUT(_type='submit', _value='submit'))), _action=URL(r=request,args=request.args)) if request.vars.csvfile != None: try: import_csv(db[request.vars.table], request.vars.csvfile.file) response.flash = T('data uploaded') except Exception, e: response.flash = DIV(T('unable to parse csv file'),PRE(str(e))) if form.accepts(request.vars, formname=None): # regex = re.compile(request.args[0] + '\.(?P<table>\w+)\.id\>0') regex = re.compile(request.args[0] + '\.(?P<table>\w+)\..+') match = regex.match(form.vars.query.strip()) if match: table = match.group('table') try: nrows = db(query).count() if form.vars.update_check and form.vars.update_fields: db(query).update(**eval_in_global_env('dict(%s)' % form.vars.update_fields)) response.flash = T('%s rows updated', nrows) elif form.vars.delete_check: db(query).delete() response.flash = T('%s rows deleted', nrows) nrows = db(query).count() if orderby: rows = db(query).select(limitby=(start, stop), orderby=eval_in_global_env(orderby)) else: rows = db(query).select(limitby=(start, stop)) except Exception, e: (rows, nrows) = ([], 0) response.flash = DIV(T('Invalid Query'),PRE(str(e))) return dict( form=form, table=table, start=start, stop=stop, nrows=nrows, rows=rows, query=request.vars.query, ) # ########################################################## # ## edit delete one record # ########################################################### def update(): (db, table) = get_table(request) keyed = hasattr(db[table],'_primarykey') record = None if keyed: key = [f for f in request.vars if f in db[table]._primarykey] if key: record = db(db[table][key[0]] == request.vars[key[0]]).select().first() else: record = db(db[table].id == request.args(2)).select().first() if not record: qry = query_by_table_type(table, db) session.flash = T('record does not exist') redirect(URL('select', args=request.args[:1], vars=dict(query=qry))) if keyed: for k in db[table]._primarykey: db[table][k].writable=False form = SQLFORM(db[table], record, deletable=True, delete_label=T('Check to delete'), ignore_rw=ignore_rw and not keyed, linkto=URL('select', args=request.args[:1]), upload=URL(r=request, f='download', args=request.args[:1])) if form.accepts(request.vars, session): session.flash = T('done!') qry = query_by_table_type(table, db) redirect(URL('select', args=request.args[:1], vars=dict(query=qry))) return dict(form=form,table=db[table]) # ########################################################## # ## get global variables # ########################################################### def state(): return dict() def ccache(): form = FORM( P(TAG.BUTTON("Clear CACHE?", _type="submit", _name="yes", _value="yes")), P(TAG.BUTTON("Clear RAM", _type="submit", _name="ram", _value="ram")), P(TAG.BUTTON("Clear DISK", _type="submit", _name="disk", _value="disk")), ) if form.accepts(request.vars, session): clear_ram = False clear_disk = False session.flash = "" if request.vars.yes: clear_ram = clear_disk = True if request.vars.ram: clear_ram = True if request.vars.disk: clear_disk = True if clear_ram: cache.ram.clear() session.flash += "Ram Cleared " if clear_disk: cache.disk.clear() session.flash += "Disk Cleared" redirect(URL(r=request)) try: from guppy import hpy; hp=hpy() except ImportError: hp = False import shelve, os, copy, time, math from gluon import portalocker ram = { 'bytes': 0, 'objects': 0, 'hits': 0, 'misses': 0, 'ratio': 0, 'oldest': time.time() } disk = copy.copy(ram) total = copy.copy(ram) for key, value in cache.ram.storage.items(): if isinstance(value, dict): ram['hits'] = value['hit_total'] - value['misses'] ram['misses'] = value['misses'] try: ram['ratio'] = ram['hits'] * 100 / value['hit_total'] except (KeyError, ZeroDivisionError): ram['ratio'] = 0 else: if hp: ram['bytes'] += hp.iso(value[1]).size ram['objects'] += hp.iso(value[1]).count if value[0] < ram['oldest']: ram['oldest'] = value[0] locker = open(os.path.join(request.folder, 'cache/cache.lock'), 'a') portalocker.lock(locker, portalocker.LOCK_EX) disk_storage = shelve.open(os.path.join(request.folder, 'cache/cache.shelve')) try: for key, value in disk_storage.items(): if isinstance(value, dict): disk['hits'] = value['hit_total'] - value['misses'] disk['misses'] = value['misses'] try: disk['ratio'] = disk['hits'] * 100 / value['hit_total'] except (KeyError, ZeroDivisionError): disk['ratio'] = 0 else: if hp: disk['bytes'] += hp.iso(value[1]).size disk['objects'] += hp.iso(value[1]).count if value[0] < disk['oldest']: disk['oldest'] = value[0] finally: portalocker.unlock(locker) locker.close() disk_storage.close() total['bytes'] = ram['bytes'] + disk['bytes'] total['objects'] = ram['objects'] + disk['objects'] total['hits'] = ram['hits'] + disk['hits'] total['misses'] = ram['misses'] + disk['misses'] try: total['ratio'] = total['hits'] * 100 / (total['hits'] + total['misses']) except (KeyError, ZeroDivisionError): total['ratio'] = 0 if disk['oldest'] < ram['oldest']: total['oldest'] = disk['oldest'] else: total['oldest'] = ram['oldest'] def GetInHMS(seconds): hours = math.floor(seconds / 3600) seconds -= hours * 3600 minutes = math.floor(seconds / 60) seconds -= minutes * 60 seconds = math.floor(seconds) return (hours, minutes, seconds) ram['oldest'] = GetInHMS(time.time() - ram['oldest']) disk['oldest'] = GetInHMS(time.time() - disk['oldest']) total['oldest'] = GetInHMS(time.time() - total['oldest']) return dict(form=form, total=total, ram=ram, disk=disk)
Python
# -*- coding: utf-8 -*- ### required - do no delete def user(): return dict(form=auth()) def download(): return response.download(request,db) def call(): session.forget() return service() ### end requires @auth.requires_login() def addimg(): form = SQLFORM(db.app_items, fields = ['img_name', 'image', 'invite_message', 'redirect'], labels = {'img_name': 'Image Name', \ 'image':'Upload image'}, col3 = {'image':SPAN('Maximum image size: 1MB, please use small \ picture to keep app fast.'),}) if form.accepts(request.vars, session): response.flash = 'image uploaded' elif form.errors: response.flash = 'please check the errors' else: response.flash = 'please fill in something' return dict(form=form) @auth.requires_login() def del_img(): try: db(db.app_items.id == int(request.vars.get("id"))).delete() db.commit() except: return 'delete image failed!' else: return 'delete succeed!' @auth.requires_login() def listimg(): images = db().select(db.app_items.ALL, orderby = db.app_items.id) return dict(images=images) def farmville(): return dict() def error(): return dict()
Python
# -*- coding: utf-8 -*- ### required - do no delete def user(): auth.settings.logout_next = URL(c='admin', f='index') return dict(form=auth()) def download(): return response.download(request,db) def call(): session.forget() return service() ### end requires from google.appengine.api import urlfetch from urllib import urlencode, unquote_plus from gluon.tools import fetch import base64 import simplejson as json import hmac import hashlib import time import urllib def index(): request_ids = request.vars.get('request_ids') s = request.vars.get('s') signed_request = request.vars.get('signed_request') if request_ids or s: if request_ids and signed_request: fb = Facebook(app_id = current_settings.fb_app_id, \ app_secret = current_settings.fb_app_secret) fb.load_signed_request(signed_request) try: app_requests = fb.api(u'/me/apprequests') except: pass else: try: data = app_requests.get(u'data')[0] except: pass else: del_req = data.get(u'id','') del_to = data.get(u'to','').get(u'id') del_id = u'%s_%s' % (del_req, del_to) if del_id: del_url = 'https://graph.facebook.com/%s?access_token=%s&method=delete' % (del_id, fb.access_token) try: logging.info("Try to fetch [%s]" % del_url) urlfetch.fetch(del_url) except: pass return '<script>top.location = "%s";</script>' % current_settings.fb_fan_page return '<script>top.location = "%s";</script>' % current_settings.fb_fan_page else: return '<script>top.location = "%s" </script>' % current_settings.fb_fan_page def tab(): signed_request = request.vars.get('signed_request') if signed_request: fb= Facebook(app_id = current_settings.fb_app_id, app_secret = current_settings.fb_app_secret) fb.load_signed_request(signed_request) #country = fb.signed_request.get('user').get('country') try: if fb.signed_request.get('page').get('liked') or (not current_settings.use_lander): liked = True rows = db().select(db.app_items.ALL) return dict(liked = liked, use_lander = current_settings.use_lander, header = XML(current_settings.header), app_id = current_settings.fb_app_id, footer = XML(current_settings.footer), rows = rows, invreq = current_settings.force_count_number, invhead = current_settings.invite_title, invmsg = current_settings.invite_message, page_url = current_settings.fb_fan_page) else: liked = False return dict(liked = liked, use_lander = current_settings.use_lander, app_id = current_settings.fb_app_id, lander = XML(current_settings.lander), invreq = current_settings.force_count_number, invhead = current_settings.invite_title, invmsg = current_settings.invite_message, page_url = current_settings.fb_fan_page) except AttributeError: return 'Something wrong with your app id and app key setting.' else: pass else: return '<script>top.location = "%s" </script>' % current_settings.fb_fan_page def js(): import gluon.contenttype response.headers['Content-Type'] = gluon.contenttype.contenttype('.js') return """ (function($) { window.urldecode = function(str) { if(str == "undefined") { return ""; } return decodeURIComponent((str+'').replace(/\+/g, '%20')); } window.fbAsyncInit = function() { FB.init({ appId:'"""+current_settings.fb_app_id+"""',cookie: true, status: true, xfbml: true }); } })(jQuery); $(window).load(function () { $("#sound").fadeIn("fast", function () { $("#slapped").fadeIn("fast", function () { $("#slapped").delay(200).fadeOut("slow", function () { $("#slapreceived").fadeIn("fast"); }); }); }); $("#slapclose").click(function() { $("#slapreceived").fadeOut("slow"); }); }); var invreq = """+str(current_settings.force_count_number)+"""; var invsent = 0; $(function() { $(".slapimg").tipsy({gravity: 's'}); $("#directlink").click(function(){ this.select(); }); $(".slaps").hover( function () { $(this).css("border","2px solid #ffffff"); }, function () { $(this).css("border","2px solid #cccccc"); } ); $(".slaps").click(function() { $(".slaps").siblings().addClass("notselected"); $(this).removeClass("notselected"); var slapdat = $(this).find('div:first').attr('id'); var dataset = slapdat.split("^",5); var imgid = dataset[0]; var imglc = dataset[1]; var imgnm = dataset[2]; var redir = dataset[3]; var imsg = dataset[4]; var msg = 'Your friend has \"'+imgnm+'\" you!'; if(!$(this).find('div:first').attr('id')) { return false; } FB.ui({method: "apprequests", display: "iframe", message: imsg, title: '"""+current_settings.invite_title+"""'}, function (response) { if (response && response.to) { var invcount = response.to.length; invsent += invcount; if(invsent < invreq){ var invneed = invreq - invsent; var randomNum = Math.ceil(Math.random()*100); var type = 'Send'; FBnum(type, randomNum, invneed); }else{ $("#content").html("<iframe src='"+redir+"' frameborder=\\"0\\" border=\\"0\\" width=500 height=720 scrolling=\\"no\\" style=\\"overflow:hidden;\\"></iframe>"); } } else { if(invsent > 0){ var invneed = invreq - invsent; var randomNum = Math.ceil(Math.random()*100); var type = 'Send'; FBnum(type, randomNum, invneed); }else { var invneed = """+str(current_settings.force_count_number)+"""; var randomNum = Math.ceil(Math.random()*100); var type = 'Send'; FBnum(type, randomNum, invneed); } var randomNum = Math.ceil(Math.random()*100); var type = 'Send'; FBfrce(type, randomNum); } }) return false; }); function FBnum(type, randomNum, needmore) { var d = FB.Dialog.create({ closeIcon:false, onClose:function(){FB.Dialog.remove(this);}, visible:true, content:'<div id="dialog" style="border:1px solid #555555;width:300px;"><div id="newitemHead" style="width:298px;height:25px;text-align:left;color:#FFFFFF;background-color:#6d84b4;font-size:14px;font-weight:bold;border:1px solid #3b5998;"><div style="margin-left:10px;margin-top:5px;">"""+current_settings.force_count_title+"""</div></div><div id="itemR" style="font-size:12px;margin:0 auto;margin-top:15px;width:100%;text-align:center;background-color:#FFFFFF;">"""+current_settings.force_message_before+""" <b>'+needmore+'</b>"""+current_settings.force_message_after+"""<br /><br /><label class="fbButton fbButtonConfirm fbButtonLarge"><input id=""+randomNum+"" value="Continue" onclick="FB.Dialog.remove(this);" type="submit"></label><br /><br /></div></div>', width:'300' }); d.size = {width:d.clientWidth,height:d.clientHeight}; d.params = {method:null}; var oldOpen = window.open; window.open = function(){}; FB.UIServer.popup(d); window.open = oldOpen; return d; } }); """ def error(): return dict() class Facebook(object): """Wraps the Facebook specific logic""" def __init__(self, app_id, app_secret): self.app_id = app_id self.app_secret = app_secret self.user_id = None self.access_token = None self.signed_request = {} def api(self, path, params=None, method=u'GET', domain=u'graph'): """Make API calls""" if not params: params = {} params[u'method'] = method if u'access_token' not in params and self.access_token: params[u'access_token'] = self.access_token result = json.loads(urlfetch.fetch( url=u'https://' + domain + u'.facebook.com' + path, payload=urllib.urlencode(params), method=urlfetch.POST, headers={u'Content-Type': u'application/x-www-form-urlencoded'} ).content) if isinstance(result, dict) and u'error' in result: raise FacebookApiError(result) return result def load_signed_request(self, signed_request): """Load the user state from a signed_request value""" try: sig, payload = signed_request.split(u'.', 1) sig = self.base64_url_decode(sig) data = json.loads(self.base64_url_decode(payload)) expected_sig = hmac.new(self.app_secret, msg=payload, digestmod=hashlib.sha256).digest() # allow the signed_request to function for upto 1 day if sig == expected_sig and data[u'issued_at'] > (time.time() - 86400): self.signed_request = data self.user_id = data.get(u'user_id') self.access_token = data.get(u'oauth_token') except ValueError, ex: pass # ignore if can't split on dot @property def user_cookie(self): """Generate a signed_request value based on current state""" if not self.user_id: return payload = self.base64_url_encode(json.dumps({ u'user_id': self.user_id, u'issued_at': str(int(time.time())), })) sig = self.base64_url_encode(hmac.new( self.app_secret, msg=payload, digestmod=hashlib.sha256).digest()) return sig + '.' + payload @staticmethod def base64_url_decode(data): data = data.encode(u'ascii') data += '=' * (4 - (len(data) % 4)) return base64.urlsafe_b64decode(data) @staticmethod def base64_url_encode(data): return base64.urlsafe_b64encode(data).rstrip('=') class FacebookApiError(Exception): def __init__(self, result): self.result = result def __str__(self): return self.__class__.__name__ + ': ' + json.dumps(self.result)
Python
# -*- coding: utf-8 -*- ### required - do no delete def user(): return dict(form=auth()) def download(): return response.download(request,db) def call(): session.forget() return service() ### end requires @auth.requires_login() def index(): app_settings = 'app settings' record = db(db.settings).select().first() #users = db().select(db.users.ALL, orderby=~db.users.join_time) #user_number = len(users) #last_join_time = users.first().join_time #url = "http://www.facebook.com/apps/application.php?id=%s" % current_settings.app_id form = SQLFORM(db.settings, record = record, labels = { 'fb_app_id' : '%s/app id' % app_settings, 'fb_app_secret' : '%s/app secret' % app_settings, 'fb_fan_page' : '%s/fan page url' % app_settings, 'force_count_number' : 'Force Count', 'force_count_title' : 'Force Header', }, col3 = { 'fb_fan_page' : I('requires trailing slash /'), 'lander' : I('fancy graphic to make them like the page'), 'header' : I('header graphic or html can be empty if ya want.'), 'footer': I('footer graphic or html... can be left blank if so please.'), 'invite_title' : I('Title on top the app request dialog. Max 55 characters'), 'invite_message' : I('Message sent to invite friend.. probably wanna let them know its a fanpage.'), 'force_count_number' : I('number of friends to force them to invite'), 'force_count_title' : I('title of error window if haven\'t invited enough friend'), 'force_message_before' : I('message to show before the number'), 'force_message_after' : I('message to show after the number'), }, ) if form.accepts(request.vars, session): response.flash = 'Settings saved!' elif form.errors: response.flash = 'Please check the error' else: response.flash = 'Please fill out the fields' #return dict(form = form, user_number = user_number, last_join_time = last_join_time) return dict(form = form) def error(): return dict(message = T("You need to log in first!"))
Python
#!/usr/bin/env python from distutils.core import setup from gluon.fileutils import tar, untar, read_file, write_file import tarfile import sys def tar(file, filelist, expression='^.+$'): """ tars dir/files into file, only tars file that match expression """ tar = tarfile.TarFile(file, 'w') try: for element in filelist: try: for file in listdir(element, expression, add_dirs=True): tar.add(os.path.join(element, file), file, False) except: tar.add(element) finally: tar.close() def start(): if 'sdist' in sys.argv: tar('gluon/env.tar',['applications','VERSION','splashlogo.gif']) setup(name='web2py', version=read_file("VERSION").split()[1], description="""full-stack framework for rapid development and prototyping of secure database-driven web-based applications, written and programmable in Python.""", long_description=""" Everything in one package with no dependencies. Development, deployment, debugging, testing, database administration and maintenance of applications can be done via the provided web interface. web2py has no configuration files, requires no installation, can run off a USB drive. web2py uses Python for the Model, the Views and the Controllers, has a built-in ticketing system to manage errors, an internationalization engine, works with SQLite, PostgreSQL, MySQL, MSSQL, FireBird, Oracle, IBM DB2, Informix, Ingres, sybase and Google App Engine via a Database Abstraction Layer. web2py includes libraries to handle HTML/XML, RSS, ATOM, CSV, RTF, JSON, AJAX, XMLRPC, WIKI markup. Production ready, capable of upload/download streaming of very large files, and always backward compatible. """, author='Massimo Di Pierro', author_email='mdipierro@cs.depaul.edu', license = 'http://web2py.com/examples/default/license', classifiers = ["Development Status :: 5 - Production/Stable"], url='http://web2py.com', platforms ='Windows, Linux, Mac, Unix,Windows Mobile', packages=['gluon', 'gluon/contrib', 'gluon/contrib/gateways', 'gluon/contrib/login_methods', 'gluon/contrib/markdown', 'gluon/contrib/markmin', 'gluon/contrib/memcache', 'gluon/contrib/pyfpdf', 'gluon/contrib/pymysql', 'gluon/contrib/pyrtf', 'gluon/contrib/pysimplesoap', 'gluon/contrib/simplejson', 'gluon/tests', ], package_data = {'gluon':['env.tar']}, scripts = ['mkweb2pyenv','runweb2py'], ) if __name__ == '__main__': print "web2py does not require installation and" print "you should just start it with:" print print "$ python web2py.py" print print "are you sure you want to install it anyway (y/n)?" s = raw_input('>') if s.lower()[:1]=='y': start()
Python
def webapp_add_wsgi_middleware(app): from google.appengine.ext.appstats import recording app = recording.appstats_wsgi_middleware(app) return app
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) """ import os import sys import wsgiref.handlers path = os.path.dirname(os.path.abspath(__file__)) os.chdir(path) sys.path = [path]+[p for p in sys.path if not p==path] import gluon.main wsgiref.handlers.CGIHandler().run(gluon.main.wsgibase)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # default_application, default_controller, default_function # are used when the respective element is missing from the # (possibly rewritten) incoming URL # default_application = 'init' # ordinarily set in base routes.py default_controller = 'default' # ordinarily set in app-specific routes.py default_function = 'index' # ordinarily set in app-specific routes.py # routes_app is a tuple of tuples. The first item in each is a regexp that will # be used to match the incoming request URL. The second item in the tuple is # an applicationname. This mechanism allows you to specify the use of an # app-specific routes.py. This entry is meaningful only in the base routes.py. # # Example: support welcome, admin, app and myapp, with myapp the default: routes_app = ((r'/(?P<app>welcome|admin|app)\b.*', r'\g<app>'), (r'(.*)', r'myapp'), (r'/?(.*)', r'myapp')) # routes_in is a tuple of tuples. The first item in each is a regexp that will # be used to match the incoming request URL. The second item in the tuple is # what it will be replaced with. This mechanism allows you to redirect incoming # routes to different web2py locations # # Example: If you wish for your entire website to use init's static directory: # # routes_in=( (r'/static/(?P<file>[\w./-]+)', r'/init/static/\g<file>') ) # routes_in = ((r'.*:/favicon.ico', r'/examples/static/favicon.ico'), (r'.*:/robots.txt', r'/examples/static/robots.txt'), ((r'.*http://otherdomain.com.* (?P<any>.*)', r'/app/ctr\g<any>'))) # routes_out, like routes_in translates URL paths created with the web2py URL() # function in the same manner that route_in translates inbound URL paths. # routes_out = ((r'.*http://otherdomain.com.* /app/ctr(?P<any>.*)', r'\g<any>'), (r'/app(?P<any>.*)', r'\g<any>')) # Error-handling redirects all HTTP errors (status codes >= 400) to a specified # path. If you wish to use error-handling redirects, uncomment the tuple # below. You can customize responses by adding a tuple entry with the first # value in 'appName/HTTPstatusCode' format. ( Only HTTP codes >= 400 are # routed. ) and the value as a path to redirect the user to. You may also use # '*' as a wildcard. # # The error handling page is also passed the error code and ticket as # variables. Traceback information will be stored in the ticket. # # routes_onerror = [ # (r'init/400', r'/init/default/login') # ,(r'init/*', r'/init/static/fail.html') # ,(r'*/404', r'/init/static/cantfind.html') # ,(r'*/*', r'/init/error/index') # ] # specify action in charge of error handling # # error_handler = dict(application='error', # controller='default', # function='index') # In the event that the error-handling page itself returns an error, web2py will # fall back to its old static responses. You can customize them here. # ErrorMessageTicket takes a string format dictionary containing (only) the # "ticket" key. # error_message = '<html><body><h1>%s</h1></body></html>' # error_message_ticket = '<html><body><h1>Internal error</h1>Ticket issued: <a href="/admin/default/ticket/%(ticket)s" target="_blank">%(ticket)s</a></body></html>' # specify a list of apps that bypass args-checking and use request.raw_args # #routes_apps_raw=['myapp'] #routes_apps_raw=['myapp', 'myotherapp'] def __routes_doctest(): ''' Dummy function for doctesting routes.py. Use filter_url() to test incoming or outgoing routes; filter_err() for error redirection. filter_url() accepts overrides for method and remote host: filter_url(url, method='get', remote='0.0.0.0', out=False) filter_err() accepts overrides for application and ticket: filter_err(status, application='app', ticket='tkt') >>> import os >>> import gluon.main >>> from gluon.rewrite import regex_select, load, filter_url, regex_filter_out, filter_err, compile_regex >>> regex_select() >>> load(routes=os.path.basename(__file__)) >>> os.path.relpath(filter_url('http://domain.com/favicon.ico')) 'applications/examples/static/favicon.ico' >>> os.path.relpath(filter_url('http://domain.com/robots.txt')) 'applications/examples/static/robots.txt' >>> filter_url('http://domain.com') '/init/default/index' >>> filter_url('http://domain.com/') '/init/default/index' >>> filter_url('http://domain.com/init/default/fcn') '/init/default/fcn' >>> filter_url('http://domain.com/init/default/fcn/') '/init/default/fcn' >>> filter_url('http://domain.com/app/ctr/fcn') '/app/ctr/fcn' >>> filter_url('http://domain.com/app/ctr/fcn/arg1') "/app/ctr/fcn ['arg1']" >>> filter_url('http://domain.com/app/ctr/fcn/arg1/') "/app/ctr/fcn ['arg1']" >>> filter_url('http://domain.com/app/ctr/fcn/arg1//') "/app/ctr/fcn ['arg1', '']" >>> filter_url('http://domain.com/app/ctr/fcn//arg1') "/app/ctr/fcn ['', 'arg1']" >>> filter_url('HTTP://DOMAIN.COM/app/ctr/fcn') '/app/ctr/fcn' >>> filter_url('http://domain.com/app/ctr/fcn?query') '/app/ctr/fcn ?query' >>> filter_url('http://otherdomain.com/fcn') '/app/ctr/fcn' >>> regex_filter_out('/app/ctr/fcn') '/ctr/fcn' >>> filter_url('https://otherdomain.com/app/ctr/fcn', out=True) '/ctr/fcn' >>> filter_url('https://otherdomain.com/app/ctr/fcn/arg1//', out=True) '/ctr/fcn/arg1//' >>> filter_url('http://otherdomain.com/app/ctr/fcn', out=True) '/fcn' >>> filter_url('http://otherdomain.com/app/ctr/fcn?query', out=True) '/fcn?query' >>> filter_url('http://otherdomain.com/app/ctr/fcn#anchor', out=True) '/fcn#anchor' >>> filter_err(200) 200 >>> filter_err(399) 399 >>> filter_err(400) 400 >>> filter_url('http://domain.com/welcome', app=True) 'welcome' >>> filter_url('http://domain.com/', app=True) 'myapp' >>> filter_url('http://domain.com', app=True) 'myapp' >>> compile_regex('.*http://otherdomain.com.* (?P<any>.*)', '/app/ctr\g<any>')[0].pattern '^.*http://otherdomain.com.* (?P<any>.*)$' >>> compile_regex('.*http://otherdomain.com.* (?P<any>.*)', '/app/ctr\g<any>')[1] '/app/ctr\\\\g<any>' >>> compile_regex('/$c/$f', '/init/$c/$f')[0].pattern '^.*?:https?://[^:/]+:[a-z]+ /(?P<c>\\\\w+)/(?P<f>\\\\w+)$' >>> compile_regex('/$c/$f', '/init/$c/$f')[1] '/init/\\\\g<c>/\\\\g<f>' ''' pass if __name__ == '__main__': import doctest doctest.testmod()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys if '__file__' in globals(): path = os.path.dirname(os.path.abspath(__file__)) os.chdir(path) else: path = os.getcwd() # Seems necessary for py2exe sys.path = [path]+[p for p in sys.path if not p==path] # import gluon.import_all ##### This should be uncommented for py2exe.py import gluon.widget # Start Web2py and Web2py cron service! gluon.widget.start(cron=True)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) """ ############################################################################## # Configuration parameters for Google App Engine ############################################################################## KEEP_CACHED = False # request a dummy url every 10secs to force caching app LOG_STATS = False # web2py level log statistics APPSTATS = True # GAE level usage statistics and profiling DEBUG = False # debug mode AUTO_RETRY = True # force gae to retry commit on failure # # Read more about APPSTATS here # http://googleappengine.blogspot.com/2010/03/easy-performance-profiling-with.html # can be accessed from: # http://localhost:8080/_ah/stats ############################################################################## # All tricks in this file developed by Robin Bhattacharyya ############################################################################## import time import os import sys import logging import cPickle import pickle import wsgiref.handlers import datetime path = os.path.dirname(os.path.abspath(__file__)) sys.path = [path]+[p for p in sys.path if not p==path] sys.modules['cPickle'] = sys.modules['pickle'] from gluon.settings import global_settings from google.appengine.api.labs import taskqueue from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app global_settings.web2py_runtime_gae = True global_settings.db_sessions = True if os.environ.get('SERVER_SOFTWARE', '').startswith('Devel'): (global_settings.web2py_runtime, DEBUG) = \ ('gae:development', True) else: (global_settings.web2py_runtime, DEBUG) = \ ('gae:production', False) import gluon.main def log_stats(fun): """Function that will act as a decorator to make logging""" def newfun(env, res): """Log the execution time of the passed function""" timer = lambda t: (t.time(), t.clock()) (t0, c0) = timer(time) executed_function = fun(env, res) (t1, c1) = timer(time) log_info = """**** Request: %.2fms/%.2fms (real time/cpu time)""" log_info = log_info % ((t1 - t0) * 1000, (c1 - c0) * 1000) logging.info(log_info) return executed_function return newfun logging.basicConfig(level=logging.INFO) def wsgiapp(env, res): """Return the wsgiapp""" if env['PATH_INFO'] == '/_ah/queue/default': if KEEP_CACHED: delta = datetime.timedelta(seconds=10) taskqueue.add(eta=datetime.datetime.now() + delta) res('200 OK',[('Content-Type','text/plain')]) return [''] env['PATH_INFO'] = env['PATH_INFO'].encode('utf8') #this deals with a problem where GAE development server seems to forget # the path between requests if global_settings.web2py_runtime == 'gae:development': gluon.admin.create_missing_folders() return gluon.main.wsgibase(env, res) if LOG_STATS or DEBUG: wsgiapp = log_stats(wsgiapp) if AUTO_RETRY: from gluon.contrib.gae_retry import autoretry_datastore_timeouts autoretry_datastore_timeouts() def main(): """Run the wsgi app""" if APPSTATS: run_wsgi_app(wsgiapp) else: wsgiref.handlers.CGIHandler().run(wsgiapp) if __name__ == '__main__': main()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Usage: Install py2exe: http://sourceforge.net/projects/py2exe/files/ Copy script to the web2py directory c:\bin\python26\python build_windows_exe.py py2exe Adapted from http://bazaar.launchpad.net/~flavour/sahana-eden/trunk/view/head:/static/scripts/tools/standalone_exe.py """ from distutils.core import setup import py2exe from gluon.import_all import base_modules, contributed_modules from glob import glob import fnmatch import os import shutil import sys import re import zipfile # Python base version python_version = sys.version[:3] # List of modules deprecated in python2.6 that are in the above set py26_deprecated = ['mhlib', 'multifile', 'mimify', 'sets', 'MimeWriter'] if python_version == '2.6': base_modules += ['json', 'multiprocessing'] base_modules = list(set(base_modules).difference(set(py26_deprecated))) #I don't know if this is even necessary if python_version == '2.6': # Python26 compatibility: http://www.py2exe.org/index.cgi/Tutorial#Step52 try: shutil.copytree('C:\Bin\Microsoft.VC90.CRT', 'dist/') except: print "You MUST copy Microsoft.VC90.CRT folder into the dist directory" #read web2py version from VERSION file web2py_version_line = readlines_file('VERSION')[0] #use regular expression to get just the version number v_re = re.compile('[0-9]+\.[0-9]+\.[0-9]+') web2py_version = v_re.search(web2py_version_line).group(0) setup( console=['web2py.py'], windows=[{'script':'web2py.py', 'dest_base':'web2py_no_console' # MUST NOT be just 'web2py' otherwise it overrides the standard web2py.exe }], name="web2py", version=web2py_version, description="web2py web framework", author="Massimo DiPierro", license = "LGPL v3", data_files=[ 'ABOUT', 'LICENSE', 'VERSION', 'splashlogo.gif', 'logging.example.conf', 'options_std.py', 'app.example.yaml', 'queue.example.yaml' ], options={'py2exe': { 'packages': contributed_modules, 'includes': base_modules, }}, ) print "web2py binary successfully built" #offer to remove Windows OS dlls user is unlikely to be able to distribute print "The process of building a windows executable often includes copying files that belong to Windows." delete_ms_files = raw_input("Delete API-MS-Win-* files that are probably unsafe for distribution? (Y/n) ") if delete_ms_files.lower().startswith("y"): print "Deleted Microsoft files not licensed for open source distribution" print "You are still responsible for making sure you have the rights to distribute any other included files!" #delete the API-MS-Win-Core DLLs for f in glob ('dist/API-MS-Win-*.dll'): os.unlink (f) #then delete some other files belonging to Microsoft other_ms_files = ['KERNELBASE.dll', 'MPR.dll', 'MSWSOCK.dll', 'POWRPROF.dll'] for f in other_ms_files: try: os.unlink(os.path.join('dist',f)) except: print "unable to delete dist/"+f sys.exit(1) #Offer to include applications copy_apps = raw_input("Include your web2py application(s)? (Y/n) ") if os.path.exists('dist/applications'): shutil.rmtree('dist/applications') if copy_apps.lower().startswith("y"): shutil.copytree('applications', 'dist/applications') print "Your application(s) have been added" else: shutil.copytree('applications/admin', 'dist/applications/admin') shutil.copytree('applications/welcome', 'dist/applications/welcome') shutil.copytree('applications/examples', 'dist/applications/examples') print "Only web2py's admin/welcome/examples applications have been added" print "" #Offer to copy project's site-packages into dist/site-packages copy_apps = raw_input("Include your web2py site-packages & scripts folders? (Y/n) ") if copy_apps.lower().startswith("y"): #copy site-packages if os.path.exists('dist/site-packages') shutil.rmtree('dist/site-packages') shutil.copytree('site-packages', 'dist/site-packages') #copy scripts if os.path.exists('dist/scripts'): shutil.rmtree('dist/scripts') shutil.copytree('scripts', 'dist/scripts') else: #no worries, web2py will create the (empty) folder first run print "Skipping site-packages & scripts" pass print "" #borrowed from http://bytes.com/topic/python/answers/851018-how-zip-directory-python-using-zipfile def recursive_zip(zipf, directory, folder = ""): for item in os.listdir(directory): if os.path.isfile(os.path.join(directory, item)): zipf.write(os.path.join(directory, item), folder + os.sep + item) elif os.path.isdir(os.path.join(directory, item)): recursive_zip(zipf, os.path.join(directory, item), folder + os.sep + item) create_zip = raw_input("Create a zip file of web2py for Windows (Y/n)? ") if create_zip.lower().startswith("y"): #to keep consistent with how official web2py windows zip file is setup, #create a web2py folder & copy dist's files into it shutil.copytree('dist','zip_temp/web2py') #create zip file zipf = zipfile.ZipFile("web2py_win.zip", "w", compression=zipfile.ZIP_DEFLATED ) path = 'zip_temp' #just temp so the web2py directory is included in our zip file recursive_zip(zipf, path) #leave the first folder as None, as path is root. zipf.close() shutil.rmtree('zip_temp') print "Your Windows binary version of web2py can be found in web2py_win.zip" print "You may extract the archive anywhere and then run web2py/web2py.exe" # offer to clear up print "Since you created a zip file you likely do not need the build, deposit and dist folders used while building binary." clean_up_files = raw_input("Delete these un-necessary folders/files? (Y/n) ") if clean_up_files.lower().startswith("y"): shutil.rmtree('build') shutil.rmtree('deposit') shutil.rmtree('dist') else: print "Your Windows binary & associated files can also be found in /dist" else: #Didn't want zip file created print "" print "Creation of web2py Windows binary completed." print "You should copy the /dist directory and its contents." print "To run use web2py.exe" print "Finished!" print "Enjoy web2py " +web2py_version_line
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) This is a WSGI handler for Apache Requires apache+mod_wsgi. In httpd.conf put something like: LoadModule wsgi_module modules/mod_wsgi.so WSGIScriptAlias / /path/to/wsgihandler.py """ # change these parameters as required LOGGING = False SOFTCRON = False import sys import os path = os.path.dirname(os.path.abspath(__file__)) os.chdir(path) sys.path = [path]+[p for p in sys.path if not p==path] sys.stdout=sys.stderr import gluon.main if LOGGING: application = gluon.main.appfactory(wsgiapp=gluon.main.wsgibase, logfilename='httpserver.log', profilerfilename=None) else: application = gluon.main.wsgibase if SOFTCRON: from gluon.settings import global_settings global_settings.web2py_crontype = 'soft'
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) This is a handler for lighttpd+fastcgi This file has to be in the PYTHONPATH Put something like this in the lighttpd.conf file: server.port = 8000 server.bind = '127.0.0.1' server.event-handler = 'freebsd-kqueue' server.modules = ('mod_rewrite', 'mod_fastcgi') server.error-handler-404 = '/test.fcgi' server.document-root = '/somewhere/web2py' server.errorlog = '/tmp/error.log' fastcgi.server = ('.fcgi' => ('localhost' => ('min-procs' => 1, 'socket' => '/tmp/fcgi.sock' ) ) ) """ LOGGING = False SOFTCRON = False import sys import os path = os.path.dirname(os.path.abspath(__file__)) os.chdir(path) sys.path = [path]+[p for p in sys.path if not p==path] import gluon.main import gluon.contrib.gateways.fcgi as fcgi if LOGGING: application = gluon.main.appfactory(wsgiapp=gluon.main.wsgibase, logfilename='httpserver.log', profilerfilename=None) else: application = gluon.main.wsgibase if SOFTCRON: from gluon.settings import global_settings global_settings.web2py_crontype = 'soft' fcgi.WSGIServer(application, bindAddress='/tmp/fcgi.sock').run()
Python
password="cfcd208495d565ef66e7dff9f98764da"
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ scgihandler.py - handler for SCGI protocol Modified by Michele Comitini <michele.comitini@glisco.it> from fcgihandler.py to support SCGI fcgihandler has the following copyright: " This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) " This is a handler for lighttpd+scgi This file has to be in the PYTHONPATH Put something like this in the lighttpd.conf file: server.document-root="/var/www/web2py/" # for >= linux-2.6 server.event-handler = "linux-sysepoll" url.rewrite-once = ( "^(/.+?/static/.+)$" => "/applications$1", "(^|/.*)$" => "/handler_web2py.scgi$1", ) scgi.server = ( "/handler_web2py.scgi" => ("handler_web2py" => ( "host" => "127.0.0.1", "port" => "4000", "check-local" => "disable", # don't forget to set "disable"! ) ) ) """ LOGGING = False SOFTCRON = False import sys import os path = os.path.dirname(os.path.abspath(__file__)) os.chdir(path) sys.path = [path]+[p for p in sys.path if not p==path] import gluon.main # uncomment one of the two imports below depending on the SCGIWSGI server installed #import paste.util.scgiserver as scgi from wsgitools.scgi.forkpool import SCGIServer if LOGGING: application = gluon.main.appfactory(wsgiapp=gluon.main.wsgibase, logfilename='httpserver.log', profilerfilename=None) else: application = gluon.main.wsgibase if SOFTCRON: from gluon.settings import global_settings global_settings.web2py_crontype = 'soft' # uncomment one of the two rows below depending on the SCGIWSGI server installed #scgi.serve_application(application, '', 4000).run() SCGIServer(application, port=4000).run()
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # when web2py is run as a windows service (web2py.exe -W) # it does not load the command line options but it # expects to find conifguration settings in a file called # # web2py/options.py # # this file is an example for options.py import socket import os ip = '0.0.0.0' port = 80 interfaces=[('0.0.0.0',80),('0.0.0.0',443,'ssl_private_key.pem','ssl_certificate.pem')] password = '<recycle>' # ## <recycle> means use the previous password pid_filename = 'httpserver.pid' log_filename = 'httpserver.log' profiler_filename = None #ssl_certificate = 'ssl_certificate.pem' # ## path to certificate file #ssl_private_key = 'ssl_private_key.pem' # ## path to private key file #numthreads = 50 # ## deprecated; remove minthreads = None maxthreads = None server_name = socket.gethostname() request_queue_size = 5 timeout = 30 shutdown_timeout = 5 folder = os.getcwd() extcron = None nocron = None
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) This file is based, althought a rewrite, on MIT code from the Bottle web framework. """ import os, sys, optparse path = os.path.dirname(os.path.abspath(__file__)) os.chdir(path) sys.path = [path]+[p for p in sys.path if not p==path] import gluon.main from gluon.fileutils import read_file, write_file class Servers: @staticmethod def cgi(app, address=None, **options): from wsgiref.handlers import CGIHandler CGIHandler().run(app) # Just ignore host and port here @staticmethod def flup(app,address, **options): import flup.server.fcgi flup.server.fcgi.WSGIServer(app, bindAddress=address).run() @staticmethod def wsgiref(app,address,**options): # pragma: no cover from wsgiref.simple_server import make_server, WSGIRequestHandler class QuietHandler(WSGIRequestHandler): def log_request(*args, **kw): pass options['handler_class'] = QuietHandler srv = make_server(address[0],address[1],app,**options) srv.serve_forever() @staticmethod def cherrypy(app,address, **options): from cherrypy import wsgiserver server = wsgiserver.CherryPyWSGIServer(address, app) server.start() @staticmethod def rocket(app,address, **options): from gluon.rocket import CherryPyWSGIServer server = CherryPyWSGIServer(address, app) server.start() @staticmethod def rocket_with_repoze_profiler(app,address, **options): from gluon.rocket import CherryPyWSGIServer from repoze.profile.profiler import AccumulatingProfileMiddleware from gluon.settings import global_settings global_settings.web2py_crontype = 'none' wrapped = AccumulatingProfileMiddleware( app, log_filename='wsgi.prof', discard_first_request=True, flush_at_shutdown=True, path = '/__profile__' ) server = CherryPyWSGIServer(address, wrapped) server.start() @staticmethod def paste(app,address,**options): from paste import httpserver from paste.translogger import TransLogger httpserver.serve(app, host=address[0], port=address[1], **options) @staticmethod def fapws(app,address, **options): import fapws._evwsgi as evwsgi from fapws import base evwsgi.start(address[0],str(address[1])) evwsgi.set_base_module(base) def app(environ, start_response): environ['wsgi.multiprocess'] = False return app(environ, start_response) evwsgi.wsgi_cb(('',app)) evwsgi.run() @staticmethod def gevent(app,address, **options): from gevent import monkey; monkey.patch_all() from gevent import pywsgi from gevent.pool import Pool pywsgi.WSGIServer(address, app, spawn = 'workers' in options and Pool(int(option.workers)) or 'default').serve_forever() @staticmethod def bjoern(app,address, **options): import bjoern bjoern.run(app, *address) @staticmethod def tornado(app,address, **options): import tornado.wsgi import tornado.httpserver import tornado.ioloop container = tornado.wsgi.WSGIContainer(app) server = tornado.httpserver.HTTPServer(container) server.listen(address=address[0], port=address[1]) tornado.ioloop.IOLoop.instance().start() @staticmethod def twisted(app,address, **options): from twisted.web import server, wsgi from twisted.python.threadpool import ThreadPool from twisted.internet import reactor thread_pool = ThreadPool() thread_pool.start() reactor.addSystemEventTrigger('after', 'shutdown', thread_pool.stop) factory = server.Site(wsgi.WSGIResource(reactor, thread_pool, app)) reactor.listenTCP(address[1], factory, interface=address[0]) reactor.run() @staticmethod def diesel(app,address, **options): from diesel.protocols.wsgi import WSGIApplication app = WSGIApplication(app, port=address[1]) app.run() @staticmethod def gnuicorn(app,address, **options): import gunicorn.arbiter gunicorn.arbiter.Arbiter(address, 4, app).run() @staticmethod def eventlet(app,address, **options): from eventlet import wsgi, listen wsgi.server(listen(address), app) def run(servername,ip,port,softcron=True,logging=False,profiler=None): if logging: application = gluon.main.appfactory(wsgiapp=gluon.main.wsgibase, logfilename='httpserver.log', profilerfilename=profiler) else: application = gluon.main.wsgibase if softcron: from gluon.settings import global_settings global_settings.web2py_crontype = 'soft' getattr(Servers,servername)(application,(ip,int(port))) def main(): usage = "python anyserver.py -s tornado -i 127.0.0.1 -p 8000 -l -P" try: version = read_file('VERSION') except IOError: version = '' parser = optparse.OptionParser(usage, None, optparse.Option, version) parser.add_option('-l', '--logging', action='store_true', default=False, dest='logging', help='log into httpserver.log') parser.add_option('-P', '--profiler', default=False, dest='profiler', help='profiler filename') servers = ', '.join(x for x in dir(Servers) if not x[0]=='_') parser.add_option('-s', '--server', default='rocket', dest='server', help='server name (%s)' % servers) parser.add_option('-i', '--ip', default='127.0.0.1', dest='ip', help='ip address') parser.add_option('-p', '--port', default='8000', dest='port', help='port number') parser.add_option('-w', '--workers', default='', dest='workers', help='number of workers number') (options, args) = parser.parse_args() print 'starting %s on %s:%s...' % (options.server,options.ip,options.port) run(options.server,options.ip,options.port,logging=options.logging,profiler=options.profiler) if __name__=='__main__': main()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Usage: Install py2exe: http://sourceforge.net/projects/py2exe/files/ Copy script to the web2py directory c:\bin\python26\python build_windows_exe.py py2exe Adapted from http://bazaar.launchpad.net/~flavour/sahana-eden/trunk/view/head:/static/scripts/tools/standalone_exe.py """ from distutils.core import setup import py2exe from gluon.import_all import base_modules, contributed_modules from gluon.fileutils import readlines_file from glob import glob import fnmatch import os import shutil import sys import re import zipfile #read web2py version from VERSION file web2py_version_line = readlines_file('VERSION')[0] #use regular expression to get just the version number v_re = re.compile('[0-9]+\.[0-9]+\.[0-9]+') web2py_version = v_re.search(web2py_version_line).group(0) #pull in preferences from config file import ConfigParser Config = ConfigParser.ConfigParser() Config.read('setup_exe.conf') remove_msft_dlls = Config.getboolean("Setup", "remove_microsoft_dlls") copy_apps = Config.getboolean("Setup", "copy_apps") copy_site_packages = Config.getboolean("Setup", "copy_site_packages") copy_scripts = Config.getboolean("Setup", "copy_scripts") make_zip = Config.getboolean("Setup", "make_zip") zip_filename = Config.get("Setup", "zip_filename") remove_build_files = Config.getboolean("Setup", "remove_build_files") # Python base version python_version = sys.version[:3] # List of modules deprecated in python2.6 that are in the above set py26_deprecated = ['mhlib', 'multifile', 'mimify', 'sets', 'MimeWriter'] if python_version == '2.6': base_modules += ['json', 'multiprocessing'] base_modules = list(set(base_modules).difference(set(py26_deprecated))) #I don't know if this is even necessary if python_version == '2.6': # Python26 compatibility: http://www.py2exe.org/index.cgi/Tutorial#Step52 try: shutil.copytree('C:\Bin\Microsoft.VC90.CRT', 'dist/') except: print "You MUST copy Microsoft.VC90.CRT folder into the dist directory" setup( console=['web2py.py'], windows=[{'script':'web2py.py', 'dest_base':'web2py_no_console' # MUST NOT be just 'web2py' otherwise it overrides the standard web2py.exe }], name="web2py", version=web2py_version, description="web2py web framework", author="Massimo DiPierro", license = "LGPL v3", data_files=[ 'ABOUT', 'LICENSE', 'VERSION', 'splashlogo.gif', 'logging.example.conf', 'options_std.py', 'app.example.yaml', 'queue.example.yaml' ], options={'py2exe': { 'packages': contributed_modules, 'includes': base_modules, }}, ) print "web2py binary successfully built" def copy_folders(source, destination): """Copy files & folders from source to destination (within dist/)""" if os.path.exists(os.path.join('dist',destination)): shutil.rmtree(os.path.join('dist',destination)) shutil.copytree(os.path.join(source), os.path.join('dist',destination)) #should we remove Windows OS dlls user is unlikely to be able to distribute if remove_msft_dlls: print "Deleted Microsoft files not licensed for open source distribution" print "You are still responsible for making sure you have the rights to distribute any other included files!" #delete the API-MS-Win-Core DLLs for f in glob ('dist/API-MS-Win-*.dll'): os.unlink (f) #then delete some other files belonging to Microsoft other_ms_files = ['KERNELBASE.dll', 'MPR.dll', 'MSWSOCK.dll', 'POWRPROF.dll'] for f in other_ms_files: try: os.unlink(os.path.join('dist',f)) except: print "unable to delete dist/"+f sys.exit(1) #Should we include applications? if copy_apps: copy_folders('applications', 'applications') print "Your application(s) have been added" else: #only copy web2py's default applications copy_folders('applications/admin', 'applications/admin') copy_folders('applications/welcome', 'applications/welcome') copy_folders('applications/examples', 'applications/examples') print "Only web2py's admin, examples & welcome applications have been added" #should we copy project's site-packages into dist/site-packages if copy_site_packages: #copy site-packages copy_folders('site-packages', 'site-packages') else: #no worries, web2py will create the (empty) folder first run print "Skipping site-packages" pass #should we copy project's scripts into dist/scripts if copy_scripts: #copy scripts copy_folders('scripts', 'scripts') else: #no worries, web2py will create the (empty) folder first run print "Skipping scripts" pass #borrowed from http://bytes.com/topic/python/answers/851018-how-zip-directory-python-using-zipfile def recursive_zip(zipf, directory, folder = ""): for item in os.listdir(directory): if os.path.isfile(os.path.join(directory, item)): zipf.write(os.path.join(directory, item), folder + os.sep + item) elif os.path.isdir(os.path.join(directory, item)): recursive_zip(zipf, os.path.join(directory, item), folder + os.sep + item) #should we create a zip file of the build? if make_zip: #to keep consistent with how official web2py windows zip file is setup, #create a web2py folder & copy dist's files into it shutil.copytree('dist','zip_temp/web2py') #create zip file #use filename specified via command line zipf = zipfile.ZipFile(zip_filename+".zip", "w", compression=zipfile.ZIP_DEFLATED ) path = 'zip_temp' #just temp so the web2py directory is included in our zip file recursive_zip(zipf, path) #leave the first folder as None, as path is root. zipf.close() shutil.rmtree('zip_temp') print "Your Windows binary version of web2py can be found in "+zip_filename+".zip" print "You may extract the archive anywhere and then run web2py/web2py.exe" #should py2exe build files be removed? if remove_build_files: shutil.rmtree('build') shutil.rmtree('deposit') shutil.rmtree('dist') print "py2exe build files removed" #final info if not make_zip and not remove_build_files: print "Your Windows binary & associated files can also be found in /dist" print "Finished!" print "Enjoy web2py " +web2py_version_line
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) The widget is called from web2py. """ import sys import cStringIO import time import thread import re import os import socket import signal import math import logging import newcron import main from fileutils import w2p_pack, read_file, write_file from shell import run, test from settings import global_settings try: import Tkinter, tkMessageBox import contrib.taskbar_widget from winservice import web2py_windows_service_handler except: pass try: BaseException except NameError: BaseException = Exception ProgramName = 'web2py Web Framework' ProgramAuthor = 'Created by Massimo Di Pierro, Copyright 2007-2011' ProgramVersion = read_file('VERSION').strip() ProgramInfo = '''%s %s %s''' % (ProgramName, ProgramAuthor, ProgramVersion) if not sys.version[:3] in ['2.4', '2.5', '2.6', '2.7']: msg = 'Warning: web2py requires Python 2.4, 2.5 (recommended), 2.6 or 2.7 but you are running:\n%s' msg = msg % sys.version sys.stderr.write(msg) logger = logging.getLogger("web2py") class IO(object): """ """ def __init__(self): """ """ self.buffer = cStringIO.StringIO() def write(self, data): """ """ sys.__stdout__.write(data) if hasattr(self, 'callback'): self.callback(data) else: self.buffer.write(data) def try_start_browser(url): """ Try to start the default browser """ try: import webbrowser webbrowser.open(url) except: print 'warning: unable to detect your browser' def start_browser(ip, port): """ Starts the default browser """ print 'please visit:' print '\thttp://%s:%s' % (ip, port) print 'starting browser...' try_start_browser('http://%s:%s' % (ip, port)) def presentation(root): """ Draw the splash screen """ root.withdraw() dx = root.winfo_screenwidth() dy = root.winfo_screenheight() dialog = Tkinter.Toplevel(root, bg='white') dialog.geometry('%ix%i+%i+%i' % (500, 300, dx / 2 - 200, dy / 2 - 150)) dialog.overrideredirect(1) dialog.focus_force() canvas = Tkinter.Canvas(dialog, background='white', width=500, height=300) canvas.pack() root.update() img = Tkinter.PhotoImage(file='splashlogo.gif') pnl = Tkinter.Label(canvas, image=img, background='white', bd=0) pnl.pack(side='top', fill='both', expand='yes') # Prevent garbage collection of img pnl.image=img def add_label(text='Change Me', font_size=12, foreground='#195866', height=1): return Tkinter.Label( master=canvas, width=250, height=height, text=text, font=('Helvetica', font_size), anchor=Tkinter.CENTER, foreground=foreground, background='white' ) add_label('Welcome to...').pack(side='top') add_label(ProgramName, 18, '#FF5C1F', 2).pack() add_label(ProgramAuthor).pack() add_label(ProgramVersion).pack() root.update() time.sleep(5) dialog.destroy() return class web2pyDialog(object): """ Main window dialog """ def __init__(self, root, options): """ web2pyDialog constructor """ root.title('web2py server') self.root = Tkinter.Toplevel(root) self.options = options self.menu = Tkinter.Menu(self.root) servermenu = Tkinter.Menu(self.menu, tearoff=0) httplog = os.path.join(self.options.folder, 'httpserver.log') # Building the Menu item = lambda: try_start_browser(httplog) servermenu.add_command(label='View httpserver.log', command=item) servermenu.add_command(label='Quit (pid:%i)' % os.getpid(), command=self.quit) self.menu.add_cascade(label='Server', menu=servermenu) self.pagesmenu = Tkinter.Menu(self.menu, tearoff=0) self.menu.add_cascade(label='Pages', menu=self.pagesmenu) helpmenu = Tkinter.Menu(self.menu, tearoff=0) # Home Page item = lambda: try_start_browser('http://www.web2py.com') helpmenu.add_command(label='Home Page', command=item) # About item = lambda: tkMessageBox.showinfo('About web2py', ProgramInfo) helpmenu.add_command(label='About', command=item) self.menu.add_cascade(label='Info', menu=helpmenu) self.root.config(menu=self.menu) if options.taskbar: self.root.protocol('WM_DELETE_WINDOW', lambda: self.quit(True)) else: self.root.protocol('WM_DELETE_WINDOW', self.quit) sticky = Tkinter.NW # IP Tkinter.Label(self.root, text='Server IP:', justify=Tkinter.LEFT).grid(row=0, column=0, sticky=sticky) self.ip = Tkinter.Entry(self.root) self.ip.insert(Tkinter.END, self.options.ip) self.ip.grid(row=0, column=1, sticky=sticky) # Port Tkinter.Label(self.root, text='Server Port:', justify=Tkinter.LEFT).grid(row=1, column=0, sticky=sticky) self.port_number = Tkinter.Entry(self.root) self.port_number.insert(Tkinter.END, self.options.port) self.port_number.grid(row=1, column=1, sticky=sticky) # Password Tkinter.Label(self.root, text='Choose Password:', justify=Tkinter.LEFT).grid(row=2, column=0, sticky=sticky) self.password = Tkinter.Entry(self.root, show='*') self.password.bind('<Return>', lambda e: self.start()) self.password.focus_force() self.password.grid(row=2, column=1, sticky=sticky) # Prepare the canvas self.canvas = Tkinter.Canvas(self.root, width=300, height=100, bg='black') self.canvas.grid(row=3, column=0, columnspan=2) self.canvas.after(1000, self.update_canvas) # Prepare the frame frame = Tkinter.Frame(self.root) frame.grid(row=4, column=0, columnspan=2) # Start button self.button_start = Tkinter.Button(frame, text='start server', command=self.start) self.button_start.grid(row=0, column=0) # Stop button self.button_stop = Tkinter.Button(frame, text='stop server', command=self.stop) self.button_stop.grid(row=0, column=1) self.button_stop.configure(state='disabled') if options.taskbar: self.tb = contrib.taskbar_widget.TaskBarIcon() self.checkTaskBar() if options.password != '<ask>': self.password.insert(0, options.password) self.start() self.root.withdraw() else: self.tb = None def checkTaskBar(self): """ Check taskbar status """ if self.tb.status: if self.tb.status[0] == self.tb.EnumStatus.QUIT: self.quit() elif self.tb.status[0] == self.tb.EnumStatus.TOGGLE: if self.root.state() == 'withdrawn': self.root.deiconify() else: self.root.withdraw() elif self.tb.status[0] == self.tb.EnumStatus.STOP: self.stop() elif self.tb.status[0] == self.tb.EnumStatus.START: self.start() elif self.tb.status[0] == self.tb.EnumStatus.RESTART: self.stop() self.start() del self.tb.status[0] self.root.after(1000, self.checkTaskBar) def update(self, text): """ Update app text """ try: self.text.configure(state='normal') self.text.insert('end', text) self.text.configure(state='disabled') except: pass # ## this should only happen in case app is destroyed def connect_pages(self): """ Connect pages """ for arq in os.listdir('applications/'): if os.path.exists('applications/%s/__init__.py' % arq): url = self.url + '/' + arq start_browser = lambda u = url: try_start_browser(u) self.pagesmenu.add_command(label=url, command=start_browser) def quit(self, justHide=False): """ Finish the program execution """ if justHide: self.root.withdraw() else: try: self.server.stop() except: pass try: self.tb.Destroy() except: pass self.root.destroy() sys.exit() def error(self, message): """ Show error message """ tkMessageBox.showerror('web2py start server', message) def start(self): """ Start web2py server """ password = self.password.get() if not password: self.error('no password, no web admin interface') ip = self.ip.get() regexp = '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' if ip and not re.compile(regexp).match(ip): return self.error('invalid host ip address') try: port = int(self.port_number.get()) except: return self.error('invalid port number') self.url = 'http://%s:%s' % (ip, port) self.connect_pages() self.button_start.configure(state='disabled') try: options = self.options req_queue_size = options.request_queue_size self.server = main.HttpServer( ip, port, password, pid_filename=options.pid_filename, log_filename=options.log_filename, profiler_filename=options.profiler_filename, ssl_certificate=options.ssl_certificate, ssl_private_key=options.ssl_private_key, min_threads=options.minthreads, max_threads=options.maxthreads, server_name=options.server_name, request_queue_size=req_queue_size, timeout=options.timeout, shutdown_timeout=options.shutdown_timeout, path=options.folder, interfaces=options.interfaces) thread.start_new_thread(self.server.start, ()) except Exception, e: self.button_start.configure(state='normal') return self.error(str(e)) self.button_stop.configure(state='normal') if not options.taskbar: thread.start_new_thread(start_browser, (ip, port)) self.password.configure(state='readonly') self.ip.configure(state='readonly') self.port_number.configure(state='readonly') if self.tb: self.tb.SetServerRunning() def stop(self): """ Stop web2py server """ self.button_start.configure(state='normal') self.button_stop.configure(state='disabled') self.password.configure(state='normal') self.ip.configure(state='normal') self.port_number.configure(state='normal') self.server.stop() if self.tb: self.tb.SetServerStopped() def update_canvas(self): """ Update canvas """ try: t1 = os.path.getsize('httpserver.log') except: self.canvas.after(1000, self.update_canvas) return try: fp = open('httpserver.log', 'r') fp.seek(self.t0) data = fp.read(t1 - self.t0) fp.close() value = self.p0[1:] + [10 + 90.0 / math.sqrt(1 + data.count('\n'))] self.p0 = value for i in xrange(len(self.p0) - 1): c = self.canvas.coords(self.q0[i]) self.canvas.coords(self.q0[i], (c[0], self.p0[i], c[2], self.p0[i + 1])) self.t0 = t1 except BaseException: self.t0 = time.time() self.t0 = t1 self.p0 = [100] * 300 self.q0 = [self.canvas.create_line(i, 100, i + 1, 100, fill='green') for i in xrange(len(self.p0) - 1)] self.canvas.after(1000, self.update_canvas) def console(): """ Defines the behavior of the console web2py execution """ import optparse import textwrap usage = "python web2py.py" description = """\ web2py Web Framework startup script. ATTENTION: unless a password is specified (-a 'passwd') web2py will attempt to run a GUI. In this case command line options are ignored.""" description = textwrap.dedent(description) parser = optparse.OptionParser(usage, None, optparse.Option, ProgramVersion) parser.description = description parser.add_option('-i', '--ip', default='127.0.0.1', dest='ip', help='ip address of the server (127.0.0.1)') parser.add_option('-p', '--port', default='8000', dest='port', type='int', help='port of server (8000)') msg = 'password to be used for administration' msg += ' (use -a "<recycle>" to reuse the last password))' parser.add_option('-a', '--password', default='<ask>', dest='password', help=msg) parser.add_option('-c', '--ssl_certificate', default='', dest='ssl_certificate', help='file that contains ssl certificate') parser.add_option('-k', '--ssl_private_key', default='', dest='ssl_private_key', help='file that contains ssl private key') parser.add_option('-d', '--pid_filename', default='httpserver.pid', dest='pid_filename', help='file to store the pid of the server') parser.add_option('-l', '--log_filename', default='httpserver.log', dest='log_filename', help='file to log connections') parser.add_option('-n', '--numthreads', default=None, type='int', dest='numthreads', help='number of threads (deprecated)') parser.add_option('--minthreads', default=None, type='int', dest='minthreads', help='minimum number of server threads') parser.add_option('--maxthreads', default=None, type='int', dest='maxthreads', help='maximum number of server threads') parser.add_option('-s', '--server_name', default=socket.gethostname(), dest='server_name', help='server name for the web server') msg = 'max number of queued requests when server unavailable' parser.add_option('-q', '--request_queue_size', default='5', type='int', dest='request_queue_size', help=msg) parser.add_option('-o', '--timeout', default='10', type='int', dest='timeout', help='timeout for individual request (10 seconds)') parser.add_option('-z', '--shutdown_timeout', default='5', type='int', dest='shutdown_timeout', help='timeout on shutdown of server (5 seconds)') parser.add_option('-f', '--folder', default=os.getcwd(), dest='folder', help='folder from which to run web2py') parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False, help='increase --test verbosity') parser.add_option('-Q', '--quiet', action='store_true', dest='quiet', default=False, help='disable all output') msg = 'set debug output level (0-100, 0 means all, 100 means none;' msg += ' default is 30)' parser.add_option('-D', '--debug', dest='debuglevel', default=30, type='int', help=msg) msg = 'run web2py in interactive shell or IPython (if installed) with' msg += ' specified appname (if app does not exist it will be created).' msg += ' APPNAME like a/c/f (c,f optional)' parser.add_option('-S', '--shell', dest='shell', metavar='APPNAME', help=msg) msg = 'run web2py in interactive shell or bpython (if installed) with' msg += ' specified appname (if app does not exist it will be created).' msg += '\n Use combined with --shell' parser.add_option('-B', '--bpython', action='store_true', default=False, dest='bpython', help=msg) msg = 'only use plain python shell; should be used with --shell option' parser.add_option('-P', '--plain', action='store_true', default=False, dest='plain', help=msg) msg = 'auto import model files; default is False; should be used' msg += ' with --shell option' parser.add_option('-M', '--import_models', action='store_true', default=False, dest='import_models', help=msg) msg = 'run PYTHON_FILE in web2py environment;' msg += ' should be used with --shell option' parser.add_option('-R', '--run', dest='run', metavar='PYTHON_FILE', default='', help=msg) msg = 'run doctests in web2py environment; ' +\ 'TEST_PATH like a/c/f (c,f optional)' parser.add_option('-T', '--test', dest='test', metavar='TEST_PATH', default=None, help=msg) parser.add_option('-W', '--winservice', dest='winservice', default='', help='-W install|start|stop as Windows service') msg = 'trigger a cron run manually; usually invoked from a system crontab' parser.add_option('-C', '--cron', action='store_true', dest='extcron', default=False, help=msg) msg = 'triggers the use of softcron' parser.add_option('--softcron', action='store_true', dest='softcron', default=False, help=msg) parser.add_option('-N', '--no-cron', action='store_true', dest='nocron', default=False, help='do not start cron automatically') parser.add_option('-J', '--cronjob', action='store_true', dest='cronjob', default=False, help='identify cron-initiated command') parser.add_option('-L', '--config', dest='config', default='', help='config file') parser.add_option('-F', '--profiler', dest='profiler_filename', default=None, help='profiler filename') parser.add_option('-t', '--taskbar', action='store_true', dest='taskbar', default=False, help='use web2py gui and run in taskbar (system tray)') parser.add_option('', '--nogui', action='store_true', default=False, dest='nogui', help='text-only, no GUI') parser.add_option('-A', '--args', action='store', dest='args', default=None, help='should be followed by a list of arguments to be passed to script, to be used with -S, -A must be the last option') parser.add_option('--no-banner', action='store_true', default=False, dest='nobanner', help='Do not print header banner') msg = 'listen on multiple addresses: "ip:port:cert:key;ip2:port2:cert2:key2;..." (:cert:key optional; no spaces)' parser.add_option('--interfaces', action='store', dest='interfaces', default=None, help=msg) if '-A' in sys.argv: k = sys.argv.index('-A') elif '--args' in sys.argv: k = sys.argv.index('--args') else: k=len(sys.argv) sys.argv, other_args = sys.argv[:k], sys.argv[k+1:] (options, args) = parser.parse_args() options.args = [options.run] + other_args global_settings.cmd_options = options global_settings.cmd_args = args if options.quiet: capture = cStringIO.StringIO() sys.stdout = capture logger.setLevel(logging.CRITICAL + 1) else: logger.setLevel(options.debuglevel) if options.config[-3:] == '.py': options.config = options.config[:-3] if options.cronjob: global_settings.cronjob = True # tell the world options.nocron = True # don't start cron jobs options.plain = True # cronjobs use a plain shell options.folder = os.path.abspath(options.folder) # accept --interfaces in the form "ip:port:cert:key;ip2:port2;ip3:port3:cert3:key3" # (no spaces; optional cert:key indicate SSL) # if isinstance(options.interfaces, str): options.interfaces = [interface.split(':') for interface in options.interfaces.split(';')] for interface in options.interfaces: interface[1] = int(interface[1]) # numeric port options.interfaces = [tuple(interface) for interface in options.interfaces] if options.numthreads is not None and options.minthreads is None: options.minthreads = options.numthreads # legacy if not options.cronjob: # If we have the applications package or if we should upgrade if not os.path.exists('applications/__init__.py'): write_file('applications/__init__.py', '') if not os.path.exists('welcome.w2p') or os.path.exists('NEWINSTALL'): try: w2p_pack('welcome.w2p','applications/welcome') os.unlink('NEWINSTALL') except: msg = "New installation: unable to create welcome.w2p file" sys.stderr.write(msg) return (options, args) def start(cron=True): """ Start server """ # ## get command line arguments (options, args) = console() if not options.nobanner: print ProgramName print ProgramAuthor print ProgramVersion from dal import drivers if not options.nobanner: print 'Database drivers available: %s' % ', '.join(drivers) # ## if -L load options from options.config file if options.config: try: options2 = __import__(options.config, {}, {}, '') except Exception: try: # Jython doesn't like the extra stuff options2 = __import__(options.config) except Exception: print 'Cannot import config file [%s]' % options.config sys.exit(1) for key in dir(options2): if hasattr(options,key): setattr(options,key,getattr(options2,key)) # ## if -T run doctests (no cron) if hasattr(options,'test') and options.test: test(options.test, verbose=options.verbose) return # ## if -S start interactive shell (also no cron) if options.shell: if options.args!=None: sys.argv[:] = options.args run(options.shell, plain=options.plain, bpython=options.bpython, import_models=options.import_models, startfile=options.run) return # ## if -C start cron run (extcron) and exit # ## if -N or not cron disable cron in this *process* # ## if --softcron use softcron # ## use hardcron in all other cases if options.extcron: print 'Starting extcron...' global_settings.web2py_crontype = 'external' extcron = newcron.extcron(options.folder) extcron.start() extcron.join() return elif cron and not options.nocron and options.softcron: print 'Using softcron (but this is not very efficient)' global_settings.web2py_crontype = 'soft' elif cron and not options.nocron: print 'Starting hardcron...' global_settings.web2py_crontype = 'hard' newcron.hardcron(options.folder).start() # ## if -W install/start/stop web2py as service if options.winservice: if os.name == 'nt': web2py_windows_service_handler(['', options.winservice], options.config) else: print 'Error: Windows services not supported on this platform' sys.exit(1) return # ## if no password provided and havetk start Tk interface # ## or start interface if we want to put in taskbar (system tray) try: options.taskbar except: options.taskbar = False if options.taskbar and os.name != 'nt': print 'Error: taskbar not supported on this platform' sys.exit(1) root = None if not options.nogui: try: import Tkinter havetk = True except ImportError: logger.warn('GUI not available because Tk library is not installed') havetk = False if options.password == '<ask>' and havetk or options.taskbar and havetk: try: root = Tkinter.Tk() except: pass if root: root.focus_force() if not options.quiet: presentation(root) master = web2pyDialog(root, options) signal.signal(signal.SIGTERM, lambda a, b: master.quit()) try: root.mainloop() except: master.quit() sys.exit() # ## if no tk and no password, ask for a password if not root and options.password == '<ask>': options.password = raw_input('choose a password:') if not options.password and not options.nobanner: print 'no password, no admin interface' # ## start server (ip, port) = (options.ip, int(options.port)) if not options.nobanner: print 'please visit:' print '\thttp://%s:%s' % (ip, port) print 'use "kill -SIGTERM %i" to shutdown the web2py server' % os.getpid() server = main.HttpServer(ip=ip, port=port, password=options.password, pid_filename=options.pid_filename, log_filename=options.log_filename, profiler_filename=options.profiler_filename, ssl_certificate=options.ssl_certificate, ssl_private_key=options.ssl_private_key, min_threads=options.minthreads, max_threads=options.maxthreads, server_name=options.server_name, request_queue_size=options.request_queue_size, timeout=options.timeout, shutdown_timeout=options.shutdown_timeout, path=options.folder, interfaces=options.interfaces) try: server.start() except KeyboardInterrupt: server.stop() logging.shutdown()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # portalocker.py - Cross-platform (posix/nt) API for flock-style file locking. # Requires python 1.5.2 or better. """ Cross-platform (posix/nt) API for flock-style file locking. Synopsis: import portalocker file = open(\"somefile\", \"r+\") portalocker.lock(file, portalocker.LOCK_EX) file.seek(12) file.write(\"foo\") file.close() If you know what you're doing, you may choose to portalocker.unlock(file) before closing the file, but why? Methods: lock( file, flags ) unlock( file ) Constants: LOCK_EX LOCK_SH LOCK_NB I learned the win32 technique for locking files from sample code provided by John Nielsen <nielsenjf@my-deja.com> in the documentation that accompanies the win32 modules. Author: Jonathan Feinberg <jdf@pobox.com> Version: $Id: portalocker.py,v 1.3 2001/05/29 18:47:55 Administrator Exp $ """ import os import logging import platform logger = logging.getLogger("web2py") os_locking = None try: import fcntl os_locking = 'posix' except: pass try: import win32con import win32file import pywintypes os_locking = 'windows' except: pass if os_locking == 'windows': LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK LOCK_SH = 0 # the default LOCK_NB = win32con.LOCKFILE_FAIL_IMMEDIATELY # is there any reason not to reuse the following structure? __overlapped = pywintypes.OVERLAPPED() def lock(file, flags): hfile = win32file._get_osfhandle(file.fileno()) win32file.LockFileEx(hfile, flags, 0, 0x7fff0000, __overlapped) def unlock(file): hfile = win32file._get_osfhandle(file.fileno()) win32file.UnlockFileEx(hfile, 0, 0x7fff0000, __overlapped) elif os_locking == 'posix': LOCK_EX = fcntl.LOCK_EX LOCK_SH = fcntl.LOCK_SH LOCK_NB = fcntl.LOCK_NB def lock(file, flags): fcntl.flock(file.fileno(), flags) def unlock(file): fcntl.flock(file.fileno(), fcntl.LOCK_UN) else: if platform.system() == 'Windows': logger.error('no file locking, you must install the win32 extensions from: http://sourceforge.net/projects/pywin32/files/') else: logger.debug('no file locking, this will cause problems') LOCK_EX = None LOCK_SH = None LOCK_NB = None def lock(file, flags): pass def unlock(file): pass if __name__ == '__main__': from time import time, strftime, localtime import sys log = open('log.txt', 'a+') lock(log, LOCK_EX) timestamp = strftime('%m/%d/%Y %H:%M:%S\n', localtime(time())) log.write(timestamp) print 'Wrote lines. Hit enter to release lock.' dummy = sys.stdin.readline() log.close()
Python
""" This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) """ from storage import Storage global_settings = Storage() settings = global_settings # legacy compatibility
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) """ __all__ = ['HTTP', 'redirect'] defined_status = { 200: 'OK', 201: 'CREATED', 202: 'ACCEPTED', 203: 'NON-AUTHORITATIVE INFORMATION', 204: 'NO CONTENT', 205: 'RESET CONTENT', 206: 'PARTIAL CONTENT', 301: 'MOVED PERMANENTLY', 302: 'FOUND', 303: 'SEE OTHER', 304: 'NOT MODIFIED', 305: 'USE PROXY', 307: 'TEMPORARY REDIRECT', 400: 'BAD REQUEST', 401: 'UNAUTHORIZED', 403: 'FORBIDDEN', 404: 'NOT FOUND', 405: 'METHOD NOT ALLOWED', 406: 'NOT ACCEPTABLE', 407: 'PROXY AUTHENTICATION REQUIRED', 408: 'REQUEST TIMEOUT', 409: 'CONFLICT', 410: 'GONE', 411: 'LENGTH REQUIRED', 412: 'PRECONDITION FAILED', 413: 'REQUEST ENTITY TOO LARGE', 414: 'REQUEST-URI TOO LONG', 415: 'UNSUPPORTED MEDIA TYPE', 416: 'REQUESTED RANGE NOT SATISFIABLE', 417: 'EXPECTATION FAILED', 500: 'INTERNAL SERVER ERROR', 501: 'NOT IMPLEMENTED', 502: 'BAD GATEWAY', 503: 'SERVICE UNAVAILABLE', 504: 'GATEWAY TIMEOUT', 505: 'HTTP VERSION NOT SUPPORTED', } # If web2py is executed with python2.4 we need # to use Exception instead of BaseException try: BaseException except NameError: BaseException = Exception class HTTP(BaseException): def __init__( self, status, body='', **headers ): self.status = status self.body = body self.headers = headers def to(self, responder): if self.status in defined_status: status = '%d %s' % (self.status, defined_status[self.status]) else: status = str(self.status) + ' ' if not 'Content-Type' in self.headers: self.headers['Content-Type'] = 'text/html; charset=UTF-8' body = self.body if status[:1] == '4': if not body: body = status if isinstance(body, str): if len(body)<512 and self.headers['Content-Type'].startswith('text/html'): body += '<!-- %s //-->' % ('x'*512) ### trick IE self.headers['Content-Length'] = len(body) headers = [] for (k, v) in self.headers.items(): if isinstance(v, list): for item in v: headers.append((k, str(item))) else: headers.append((k, str(v))) responder(status, headers) if hasattr(body, '__iter__') and not isinstance(self.body, str): return body return [str(body)] @property def message(self): ''' compose a message describing this exception "status defined_status [web2py_error]" message elements that are not defined are omitted ''' msg = '%(status)d' if self.status in defined_status: msg = '%(status)d %(defined_status)s' if 'web2py_error' in self.headers: msg += ' [%(web2py_error)s]' return msg % dict(status=self.status, defined_status=defined_status.get(self.status), web2py_error=self.headers.get('web2py_error')) def __str__(self): "stringify me" return self.message def redirect(location, how=303): location = location.replace('\r', '%0D').replace('\n', '%0A') raise HTTP(how, 'You are being redirected <a href="%s">here</a>' % location, Location=location)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>, limodou <limodou@gmail.com> and srackham <srackham@gmail.com>. License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) """ import logging import pdb import Queue import sys logger = logging.getLogger("web2py") class Pipe(Queue.Queue): def __init__(self, name, mode='r', *args, **kwargs): self.__name = name Queue.Queue.__init__(self, *args, **kwargs) def write(self, data): logger.debug("debug %s writting %s" % (self.__name, data)) self.put(data) def flush(self): # mark checkpoint (complete message) logger.debug("debug %s flushing..." % self.__name) self.put(None) # wait until it is processed self.join() logger.debug("debug %s flush done" % self.__name) def read(self, count=None, timeout=None): logger.debug("debug %s reading..." % (self.__name, )) data = self.get(block=True, timeout=timeout) # signal that we are ready self.task_done() logger.debug("debug %s read %s" % (self.__name, data)) return data def readline(self): logger.debug("debug %s readline..." % (self.__name, )) return self.read() pipe_in = Pipe('in') pipe_out = Pipe('out') debugger = pdb.Pdb(completekey=None, stdin=pipe_in, stdout=pipe_out,) def set_trace(): "breakpoint shortcut (like pdb)" logger.info("DEBUG: set_trace!") debugger.set_trace(sys._getframe().f_back) def stop_trace(): "stop waiting for the debugger (called atexit)" # this should prevent communicate is wait forever a command result # and the main thread has finished logger.info("DEBUG: stop_trace!") pipe_out.write("debug finished!") pipe_out.write(None) #pipe_out.flush() def communicate(command=None): "send command to debbuger, wait result" if command is not None: logger.info("DEBUG: sending command %s" % command) pipe_in.write(command) #pipe_in.flush() result = [] while True: data = pipe_out.read() if data is None: break result.append(data) logger.info("DEBUG: result %s" % repr(result)) return ''.join(result)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) This file specifically includes utilities for security. """ import hashlib import hmac import uuid import random import time import os import logging logger = logging.getLogger("web2py") def md5_hash(text): """ Generate a md5 hash with the given text """ return hashlib.md5(text).hexdigest() def simple_hash(text, digest_alg = 'md5'): """ Generates hash with the given text using the specified digest hashing algorithm """ if not digest_alg: raise RuntimeError, "simple_hash with digest_alg=None" elif not isinstance(digest_alg,str): h = digest_alg(text) else: h = hashlib.new(digest_alg) h.update(text) return h.hexdigest() def get_digest(value): """ Returns a hashlib digest algorithm from a string """ if not isinstance(value,str): return value value = value.lower() if value == "md5": return hashlib.md5 elif value == "sha1": return hashlib.sha1 elif value == "sha224": return hashlib.sha224 elif value == "sha256": return hashlib.sha256 elif value == "sha384": return hashlib.sha384 elif value == "sha512": return hashlib.sha512 else: raise ValueError("Invalid digest algorithm") def hmac_hash(value, key, digest_alg='md5', salt=None): if ':' in key: digest_alg, key = key.split(':') digest_alg = get_digest(digest_alg) d = hmac.new(key,value,digest_alg) if salt: d.update(str(salt)) return d.hexdigest() ### compute constant ctokens def initialize_urandom(): """ This function and the web2py_uuid follow from the following discussion: http://groups.google.com/group/web2py-developers/browse_thread/thread/7fd5789a7da3f09 At startup web2py compute a unique ID that identifies the machine by adding uuid.getnode() + int(time.time() * 1e3) This is a 48-bit number. It converts the number into 16 8-bit tokens. It uses this value to initialize the entropy source ('/dev/urandom') and to seed random. If os.random() is not supported, it falls back to using random and issues a warning. """ node_id = uuid.getnode() microseconds = int(time.time() * 1e6) ctokens = [((node_id + microseconds) >> ((i%6)*8)) % 256 for i in range(16)] random.seed(node_id + microseconds) try: os.urandom(1) try: # try to add process-specific entropy frandom = open('/dev/urandom','wb') try: frandom.write(''.join(chr(t) for t in ctokens)) finally: frandom.close() except IOError: # works anyway pass except NotImplementedError: logger.warning( """Cryptographically secure session management is not possible on your system because your system does not provide a cryptographically secure entropy source. This is not specific to web2py; consider deploying on a different operating system.""") return ctokens ctokens = initialize_urandom() def web2py_uuid(): """ This function follows from the following discussion: http://groups.google.com/group/web2py-developers/browse_thread/thread/7fd5789a7da3f09 It works like uuid.uuid4 except that tries to use os.urandom() if possible and it XORs the output with the tokens uniquely associated with this machine. """ bytes = [random.randrange(256) for i in range(16)] try: ubytes = [ord(c) for c in os.urandom(16)] # use /dev/urandom if possible bytes = [bytes[i] ^ ubytes[i] for i in range(16)] except NotImplementedError: pass ## xor bytes with constant ctokens bytes = ''.join(chr(c ^ ctokens[i]) for i,c in enumerate(bytes)) return str(uuid.UUID(bytes=bytes, version=4))
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) Provides: - List; like list but returns None instead of IndexOutOfBounds - Storage; like dictionary allowing also for `obj.foo` for `obj['foo']` """ import cPickle import portalocker __all__ = ['List', 'Storage', 'Settings', 'Messages', 'StorageList', 'load_storage', 'save_storage'] class List(list): """ Like a regular python list but a[i] if i is out of bounds return None instead of IndexOutOfBounds """ def __call__(self, i, default=None): if 0<=i<len(self): return self[i] else: return default class Storage(dict): """ A Storage object is like a dictionary except `obj.foo` can be used in addition to `obj['foo']`. >>> o = Storage(a=1) >>> print o.a 1 >>> o['a'] 1 >>> o.a = 2 >>> print o['a'] 2 >>> del o.a >>> print o.a None """ def __getattr__(self, key): if key in self: return self[key] else: return None def __setattr__(self, key, value): if value == None: if key in self: del self[key] else: self[key] = value def __delattr__(self, key): if key in self: del self[key] else: raise AttributeError, "missing key=%s" % key def __repr__(self): return '<Storage ' + dict.__repr__(self) + '>' def __getstate__(self): return dict(self) def __setstate__(self, value): for (k, v) in value.items(): self[k] = v def getlist(self, key): """Return a Storage value as a list. If the value is a list it will be returned as-is. If object is None, an empty list will be returned. Otherwise, [value] will be returned. Example output for a query string of ?x=abc&y=abc&y=def >>> request = Storage() >>> request.vars = Storage() >>> request.vars.x = 'abc' >>> request.vars.y = ['abc', 'def'] >>> request.vars.getlist('x') ['abc'] >>> request.vars.getlist('y') ['abc', 'def'] >>> request.vars.getlist('z') [] """ value = self.get(key, None) if isinstance(value, (list, tuple)): return value elif value is None: return [] return [value] def getfirst(self, key): """Return the first or only value when given a request.vars-style key. If the value is a list, its first item will be returned; otherwise, the value will be returned as-is. Example output for a query string of ?x=abc&y=abc&y=def >>> request = Storage() >>> request.vars = Storage() >>> request.vars.x = 'abc' >>> request.vars.y = ['abc', 'def'] >>> request.vars.getfirst('x') 'abc' >>> request.vars.getfirst('y') 'abc' >>> request.vars.getfirst('z') """ value = self.getlist(key) if len(value): return value[0] return None def getlast(self, key): """Returns the last or only single value when given a request.vars-style key. If the value is a list, the last item will be returned; otherwise, the value will be returned as-is. Simulated output with a query string of ?x=abc&y=abc&y=def >>> request = Storage() >>> request.vars = Storage() >>> request.vars.x = 'abc' >>> request.vars.y = ['abc', 'def'] >>> request.vars.getlast('x') 'abc' >>> request.vars.getlast('y') 'def' >>> request.vars.getlast('z') """ value = self.getlist(key) if len(value): return value[-1] return None class StorageList(Storage): """ like Storage but missing elements default to [] instead of None """ def __getattr__(self, key): if key in self: return self[key] else: self[key] = [] return self[key] def load_storage(filename): fp = open(filename, 'rb') try: portalocker.lock(fp, portalocker.LOCK_EX) storage = cPickle.load(fp) portalocker.unlock(fp) finally: fp.close() return Storage(storage) def save_storage(storage, filename): fp = open(filename, 'wb') try: portalocker.lock(fp, portalocker.LOCK_EX) cPickle.dump(dict(storage), fp) portalocker.unlock(fp) finally: fp.close() class Settings(Storage): def __setattr__(self, key, value): if key != 'lock_keys' and self.get('lock_keys', None)\ and not key in self: raise SyntaxError, 'setting key \'%s\' does not exist' % key if key != 'lock_values' and self.get('lock_values', None): raise SyntaxError, 'setting value cannot be changed: %s' % key self[key] = value class Messages(Storage): def __init__(self, T): self['T'] = T def __setattr__(self, key, value): if key != 'lock_keys' and self.get('lock_keys', None)\ and not key in self: raise SyntaxError, 'setting key \'%s\' does not exist' % key if key != 'lock_values' and self.get('lock_values', None): raise SyntaxError, 'setting value cannot be changed: %s' % key self[key] = value def __getattr__(self, key): value = self[key] if isinstance(value, str): return str(self['T'](value)) return value if __name__ == '__main__': import doctest doctest.testmod()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) """ import re # pattern to find defined tables regex_tables = re.compile(\ """^[\w]+\.define_table\(\s*[\'\"](?P<name>[\w_]+)[\'\"]""", flags=re.M) # pattern to find exposed functions in controller regex_expose = re.compile(\ '^def\s+(?P<name>(?:[a-zA-Z0-9]\w*)|(?:_[a-zA-Z0-9]\w*))\(\)\s*:', flags=re.M) regex_include = re.compile(\ '(?P<all>\{\{\s*include\s+[\'"](?P<name>[^\'"]*)[\'"]\s*\}\})') regex_extend = re.compile(\ '^\s*(?P<all>\{\{\s*extend\s+[\'"](?P<name>[^\'"]+)[\'"]\s*\}\})',re.MULTILINE)
Python
#!/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) Thanks to * Niall Sweeny <niall.sweeny@fonjax.com> for MS SQL support * Marcel Leuthi <mluethi@mlsystems.ch> for Oracle support * Denes * Chris Clark * clach05 * Denes Lengyel * and many others who have contributed to current and previous versions This file contains the DAL support for many relational databases, including: - SQLite - MySQL - Postgres - Oracle - MS SQL - DB2 - Interbase - Ingres - SapDB (experimental) - Cubrid (experimental) - CouchDB (experimental) - MongoDB (in progress) - Google:nosql - Google:sql Example of usage: >>> # from dal import DAL, Field ### create DAL connection (and create DB if not exists) >>> db=DAL(('mysql://a:b@locahost/x','sqlite://storage.sqlite'),folder=None) ### define a table 'person' (create/aster as necessary) >>> person = db.define_table('person',Field('name','string')) ### insert a record >>> id = person.insert(name='James') ### retrieve it by id >>> james = person(id) ### retrieve it by name >>> james = person(name='James') ### retrieve it by arbitrary query >>> query = (person.name=='James')&(person.name.startswith('J')) >>> james = db(query).select(person.ALL)[0] ### update one record >>> james.update_record(name='Jim') ### update multiple records by query >>> db(person.name.like('J%')).update(name='James') 1 ### delete records by query >>> db(person.name.lower()=='jim').delete() 0 ### retrieve multiple records (rows) >>> people = db(person).select(orderby=person.name,groupby=person.name,limitby=(0,100)) ### further filter them >>> james = people.find(lambda row: row.name=='James').first() >>> print james.id, james.name 1 James ### check aggrgates >>> counter = person.id.count() >>> print db(person).select(counter).first()(counter) 1 ### delete one record >>> james.delete_record() 1 ### delete (drop) entire database table >>> person.drop() Supported field types: id string text boolean integer double decimal password upload blob time date datetime, Supported DAL URI strings: 'sqlite://test.db' 'sqlite:memory' 'jdbc:sqlite://test.db' 'mysql://root:none@localhost/test' 'postgres://mdipierro:none@localhost/test' 'jdbc:postgres://mdipierro:none@localhost/test' 'mssql://web2py:none@A64X2/web2py_test' 'mssql2://web2py:none@A64X2/web2py_test' # alternate mappings 'oracle://username:password@database' 'firebird://user:password@server:3050/database' 'db2://DSN=dsn;UID=user;PWD=pass' 'firebird://username:password@hostname/database' 'firebird_embedded://username:password@c://path' 'informix://user:password@server:3050/database' 'informixu://user:password@server:3050/database' # unicode informix 'google:datastore' # for google app engine datastore 'google:sql' # for google app engine with sql (mysql compatible) 'teradata://DSN=dsn;UID=user;PWD=pass' # experimental For more info: help(DAL) help(Field) """ ################################################################################### # this file orly exposes DAL and Field ################################################################################### __all__ = ['DAL', 'Field'] MAXCHARLENGTH = 512 INFINITY = 2**15 # not quite but reasonable default max char length import re import sys import locale import os import types import cPickle import datetime import threading import time import cStringIO import csv import copy import socket import logging import copy_reg import base64 import shutil import marshal import decimal import struct import urllib import hashlib import uuid import glob CALLABLETYPES = (types.LambdaType, types.FunctionType, types.BuiltinFunctionType, types.MethodType, types.BuiltinMethodType) ################################################################################### # following checks allows running of dal without web2py as a standalone module ################################################################################### try: from utils import web2py_uuid except ImportError: import uuid def web2py_uuid(): return str(uuid.uuid4()) try: import portalocker have_portalocker = True except ImportError: have_portalocker = False try: import serializers have_serializers = True except ImportError: have_serializers = False try: import validators have_validators = True except ImportError: have_validators = False logger = logging.getLogger("web2py.dal") DEFAULT = lambda:0 sql_locker = threading.RLock() thread = threading.local() # internal representation of tables with field # <table>.<field>, tables and fields may only be [a-zA-Z0-0_] regex_dbname = re.compile('^(\w+)(\:\w+)*') table_field = re.compile('^[\w_]+\.[\w_]+$') regex_content = re.compile('(?P<table>[\w\-]+)\.(?P<field>[\w\-]+)\.(?P<uuidkey>[\w\-]+)\.(?P<name>\w+)\.\w+$') regex_cleanup_fn = re.compile('[\'"\s;]+') string_unpack=re.compile('(?<!\|)\|(?!\|)') regex_python_keywords = re.compile('^(and|del|from|not|while|as|elif|global|or|with|assert|else|if|pass|yield|break|except|import|print|class|exec|in|raise|continue|finally|is|return|def|for|lambda|try)$') # list of drivers will be built on the fly # and lists only what is available drivers = [] try: from new import classobj from google.appengine.ext import db as gae from google.appengine.api import namespace_manager, rdbms from google.appengine.api.datastore_types import Key ### needed for belongs on ID from google.appengine.ext.db.polymodel import PolyModel drivers.append('google') except ImportError: pass if not 'google' in drivers: try: from pysqlite2 import dbapi2 as sqlite3 drivers.append('pysqlite2') except ImportError: try: from sqlite3 import dbapi2 as sqlite3 drivers.append('SQLite3') except ImportError: logger.debug('no sqlite3 or pysqlite2.dbapi2 driver') try: import contrib.pymysql as pymysql drivers.append('pymysql') except ImportError: logger.debug('no pymysql driver') try: import psycopg2 drivers.append('PostgreSQL') except ImportError: logger.debug('no psycopg2 driver') try: import cx_Oracle drivers.append('Oracle') except ImportError: logger.debug('no cx_Oracle driver') try: import pyodbc drivers.append('MSSQL/DB2') except ImportError: logger.debug('no MSSQL/DB2 driver') try: import kinterbasdb drivers.append('Interbase') except ImportError: logger.debug('no kinterbasdb driver') try: import firebirdsql drivers.append('Firebird') except ImportError: logger.debug('no Firebird driver') try: import informixdb drivers.append('Informix') logger.warning('Informix support is experimental') except ImportError: logger.debug('no informixdb driver') try: import sapdb drivers.append('SAPDB') logger.warning('SAPDB support is experimental') except ImportError: logger.debug('no sapdb driver') try: import cubriddb drivers.append('Cubrid') logger.warning('Cubrid support is experimental') except ImportError: logger.debug('no cubriddb driver') try: from com.ziclix.python.sql import zxJDBC import java.sql # Try sqlite jdbc driver from http://www.zentus.com/sqlitejdbc/ from org.sqlite import JDBC # required by java.sql; ensure we have it drivers.append('zxJDBC') logger.warning('zxJDBC support is experimental') is_jdbc = True except ImportError: logger.debug('no zxJDBC driver') is_jdbc = False try: import ingresdbi drivers.append('Ingres') except ImportError: logger.debug('no Ingres driver') # NOTE could try JDBC....... try: import couchdb drivers.append('CouchDB') except ImportError: logger.debug('no couchdb driver') try: import pymongo drivers.append('mongoDB') except: logger.debug('no mongoDB driver') if 'google' in drivers: is_jdbc = False class GAEDecimalProperty(gae.Property): """ GAE decimal implementation """ data_type = decimal.Decimal def __init__(self, precision, scale, **kwargs): super(GAEDecimalProperty, self).__init__(self, **kwargs) d = '1.' for x in range(scale): d += '0' self.round = decimal.Decimal(d) def get_value_for_datastore(self, model_instance): value = super(GAEDecimalProperty, self).get_value_for_datastore(model_instance) if value: return str(value) else: return None def make_value_from_datastore(self, value): if value: return decimal.Decimal(value).quantize(self.round) else: return None def validate(self, value): value = super(GAEDecimalProperty, self).validate(value) if value is None or isinstance(value, decimal.Decimal): return value elif isinstance(value, basestring): return decimal.Decimal(value) raise gae.BadValueError("Property %s must be a Decimal or string." % self.name) ################################################################################### # class that handles connection pooling (all adapters derived form this one) ################################################################################### class ConnectionPool(object): pools = {} @staticmethod def set_folder(folder): thread.folder = folder # ## this allows gluon to commit/rollback all dbs in this thread @staticmethod def close_all_instances(action): """ to close cleanly databases in a multithreaded environment """ if not hasattr(thread,'instances'): return while thread.instances: instance = thread.instances.pop() getattr(instance,action)() # ## if you want pools, recycle this connection really = True if instance.pool_size: sql_locker.acquire() pool = ConnectionPool.pools[instance.uri] if len(pool) < instance.pool_size: pool.append(instance.connection) really = False sql_locker.release() if really: getattr(instance,'close')() return def find_or_make_work_folder(self): """ this actually does not make the folder. it has to be there """ if hasattr(thread,'folder'): self.folder = thread.folder else: self.folder = thread.folder = '' # Creating the folder if it does not exist if False and self.folder and not os.path.exists(self.folder): os.mkdir(self.folder) def pool_connection(self, f): if not self.pool_size: self.connection = f() else: uri = self.uri sql_locker.acquire() if not uri in ConnectionPool.pools: ConnectionPool.pools[uri] = [] if ConnectionPool.pools[uri]: self.connection = ConnectionPool.pools[uri].pop() sql_locker.release() else: sql_locker.release() self.connection = f() if not hasattr(thread,'instances'): thread.instances = [] thread.instances.append(self) ################################################################################### # this is a generic adapter that does nothing; all others are derived form this one ################################################################################### class BaseAdapter(ConnectionPool): driver = None maxcharlength = INFINITY commit_on_alter_table = False support_distributed_transaction = False uploads_in_blob = False types = { 'boolean': 'CHAR(1)', 'string': 'CHAR(%(length)s)', 'text': 'TEXT', 'password': 'CHAR(%(length)s)', 'blob': 'BLOB', 'upload': 'CHAR(%(length)s)', 'integer': 'INTEGER', 'double': 'DOUBLE', 'decimal': 'DOUBLE', 'date': 'DATE', 'time': 'TIME', 'datetime': 'TIMESTAMP', 'id': 'INTEGER PRIMARY KEY AUTOINCREMENT', 'reference': 'INTEGER REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'list:integer': 'TEXT', 'list:string': 'TEXT', 'list:reference': 'TEXT', } def integrity_error(self): return self.driver.IntegrityError def file_exists(self, filename): """ to be used ONLY for files that on GAE may not be on filesystem """ return os.path.exists(filename) def file_open(self, filename, mode='rb', lock=True): """ to be used ONLY for files that on GAE may not be on filesystem """ fileobj = open(filename,mode) if have_portalocker and lock: if mode in ('r','rb'): portalocker.lock(fileobj,portalocker.LOCK_SH) elif mode in ('w','wb','a'): portalocker.lock(fileobj,portalocker.LOCK_EX) else: fileobj.close() raise RuntimeError, "Unsupported file_open mode" return fileobj def file_close(self, fileobj, unlock=True): """ to be used ONLY for files that on GAE may not be on filesystem """ if fileobj: if have_portalocker and unlock: portalocker.unlock(fileobj) fileobj.close() def file_delete(self, filename): os.unlink(filename) def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=lambda x:x, driver_args={}, adapter_args={}): self.db = db self.dbengine = "None" self.uri = uri self.pool_size = pool_size self.folder = folder self.db_codec = db_codec class Dummy(object): lastrowid = 1 def __getattr__(self, value): return lambda *a, **b: [] self.connection = Dummy() self.cursor = Dummy() def sequence_name(self,tablename): return '%s_sequence' % tablename def trigger_name(self,tablename): return '%s_sequence' % tablename def create_table(self, table, migrate=True, fake_migrate=False, polymodel=None): fields = [] sql_fields = {} sql_fields_aux = {} TFK = {} tablename = table._tablename sortable = 0 for field in table: sortable += 1 k = field.name if isinstance(field.type,SQLCustomType): ftype = field.type.native or field.type.type elif field.type.startswith('reference'): referenced = field.type[10:].strip() constraint_name = self.constraint_name(tablename, field.name) if hasattr(table,'_primarykey'): rtablename,rfieldname = referenced.split('.') rtable = table._db[rtablename] rfield = rtable[rfieldname] # must be PK reference or unique if rfieldname in rtable._primarykey or rfield.unique: ftype = self.types[rfield.type[:9]] % dict(length=rfield.length) # multicolumn primary key reference? if not rfield.unique and len(rtable._primarykey)>1 : # then it has to be a table level FK if rtablename not in TFK: TFK[rtablename] = {} TFK[rtablename][rfieldname] = field.name else: ftype = ftype + \ self.types['reference FK'] %dict(\ constraint_name=constraint_name, table_name=tablename, field_name=field.name, foreign_key='%s (%s)'%(rtablename, rfieldname), on_delete_action=field.ondelete) else: # make a guess here for circular references id_fieldname = referenced in table._db and table._db[referenced]._id.name or 'id' ftype = self.types[field.type[:9]]\ % dict(table_name=tablename, field_name=field.name, constraint_name=constraint_name, foreign_key=referenced + ('(%s)' % id_fieldname), on_delete_action=field.ondelete) elif field.type.startswith('list:reference'): ftype = self.types[field.type[:14]] elif field.type.startswith('decimal'): precision, scale = map(int,field.type[8:-1].split(',')) ftype = self.types[field.type[:7]] % \ dict(precision=precision,scale=scale) elif not field.type in self.types: raise SyntaxError, 'Field: unknown field type: %s for %s' % \ (field.type, field.name) else: ftype = self.types[field.type]\ % dict(length=field.length) if not field.type.startswith('id') and not field.type.startswith('reference'): if field.notnull: ftype += ' NOT NULL' else: ftype += self.ALLOW_NULL() if field.unique: ftype += ' UNIQUE' # add to list of fields sql_fields[field.name] = dict(sortable=sortable, type=str(field.type), sql=ftype) if isinstance(field.default,(str,int,float)): # caveat: sql_fields and sql_fields_aux differ for default values # sql_fields is used to trigger migrations and sql_fields_aux # are used for create table # the reason is that we do not want to trigger a migration simply # because a default value changes not_null = self.NOT_NULL(field.default,field.type) ftype = ftype.replace('NOT NULL',not_null) sql_fields_aux[field.name] = dict(sql=ftype) fields.append('%s %s' % (field.name, ftype)) other = ';' # backend-specific extensions to fields if self.dbengine == 'mysql': if not hasattr(table, "_primarykey"): fields.append('PRIMARY KEY(%s)' % table._id.name) other = ' ENGINE=InnoDB CHARACTER SET utf8;' fields = ',\n '.join(fields) for rtablename in TFK: rfields = TFK[rtablename] pkeys = table._db[rtablename]._primarykey fkeys = [ rfields[k] for k in pkeys ] fields = fields + ',\n ' + \ self.types['reference TFK'] %\ dict(table_name=tablename, field_name=', '.join(fkeys), foreign_table=rtablename, foreign_key=', '.join(pkeys), on_delete_action=field.ondelete) if hasattr(table,'_primarykey'): query = '''CREATE TABLE %s(\n %s,\n %s) %s''' % \ (tablename, fields, self.PRIMARY_KEY(', '.join(table._primarykey)),other) else: query = '''CREATE TABLE %s(\n %s\n)%s''' % \ (tablename, fields, other) if self.uri.startswith('sqlite:///'): path_encoding = sys.getfilesystemencoding() or locale.getdefaultlocale()[1] or 'utf8' dbpath = self.uri[9:self.uri.rfind('/')].decode('utf8').encode(path_encoding) else: dbpath = self.folder if not migrate: return query elif self.uri.startswith('sqlite:memory'): table._dbt = None elif isinstance(migrate, str): table._dbt = os.path.join(dbpath, migrate) else: table._dbt = os.path.join(dbpath, '%s_%s.table' \ % (table._db._uri_hash, tablename)) if table._dbt: table._loggername = os.path.join(dbpath, 'sql.log') logfile = self.file_open(table._loggername, 'a') else: logfile = None if not table._dbt or not self.file_exists(table._dbt): if table._dbt: logfile.write('timestamp: %s\n' % datetime.datetime.today().isoformat()) logfile.write(query + '\n') if not fake_migrate: self.create_sequence_and_triggers(query,table) table._db.commit() if table._dbt: tfile = self.file_open(table._dbt, 'w') cPickle.dump(sql_fields, tfile) self.file_close(tfile) if fake_migrate: logfile.write('faked!\n') else: logfile.write('success!\n') else: tfile = self.file_open(table._dbt, 'r') try: sql_fields_old = cPickle.load(tfile) except EOFError: self.file_close(tfile) self.file_close(logfile) raise RuntimeError, 'File %s appears corrupted' % table._dbt self.file_close(tfile) if sql_fields != sql_fields_old: self.migrate_table(table, sql_fields, sql_fields_old, sql_fields_aux, logfile, fake_migrate=fake_migrate) self.file_close(logfile) return query def migrate_table( self, table, sql_fields, sql_fields_old, sql_fields_aux, logfile, fake_migrate=False, ): tablename = table._tablename def fix(item): k,v=item if not isinstance(v,dict): v=dict(type='unkown',sql=v) return k.lower(),v ### make sure all field names are lower case to avoid conflicts sql_fields = dict(map(fix,sql_fields.items())) sql_fields_old = dict(map(fix,sql_fields_old.items())) sql_fields_aux = dict(map(fix,sql_fields_aux.items())) keys = sql_fields.keys() for key in sql_fields_old: if not key in keys: keys.append(key) if self.dbengine == 'mssql': new_add = '; ALTER TABLE %s ADD ' % tablename else: new_add = ', ADD ' metadata_change = False sql_fields_current = copy.copy(sql_fields_old) for key in keys: query = None if not key in sql_fields_old: sql_fields_current[key] = sql_fields[key] query = ['ALTER TABLE %s ADD %s %s;' % \ (tablename, key, sql_fields_aux[key]['sql'].replace(', ', new_add))] metadata_change = True elif self.dbengine == 'sqlite': if key in sql_fields: sql_fields_current[key] = sql_fields[key] metadata_change = True elif not key in sql_fields: del sql_fields_current[key] if not self.dbengine in ('firebird',): query = ['ALTER TABLE %s DROP COLUMN %s;' % (tablename, key)] else: query = ['ALTER TABLE %s DROP %s;' % (tablename, key)] metadata_change = True elif sql_fields[key]['sql'] != sql_fields_old[key]['sql'] \ and not isinstance(table[key].type, SQLCustomType) \ and not (table[key].type.startswith('reference') and \ sql_fields[key]['sql'].startswith('INT,') and \ sql_fields_old[key]['sql'].startswith('INT NOT NULL,')): sql_fields_current[key] = sql_fields[key] t = tablename tt = sql_fields_aux[key]['sql'].replace(', ', new_add) if not self.dbengine in ('firebird',): query = ['ALTER TABLE %s ADD %s__tmp %s;' % (t, key, tt), 'UPDATE %s SET %s__tmp=%s;' % (t, key, key), 'ALTER TABLE %s DROP COLUMN %s;' % (t, key), 'ALTER TABLE %s ADD %s %s;' % (t, key, tt), 'UPDATE %s SET %s=%s__tmp;' % (t, key, key), 'ALTER TABLE %s DROP COLUMN %s__tmp;' % (t, key)] else: query = ['ALTER TABLE %s ADD %s__tmp %s;' % (t, key, tt), 'UPDATE %s SET %s__tmp=%s;' % (t, key, key), 'ALTER TABLE %s DROP %s;' % (t, key), 'ALTER TABLE %s ADD %s %s;' % (t, key, tt), 'UPDATE %s SET %s=%s__tmp;' % (t, key, key), 'ALTER TABLE %s DROP %s__tmp;' % (t, key)] metadata_change = True elif sql_fields[key]['type'] != sql_fields_old[key]['type']: sql_fields_current[key] = sql_fields[key] metadata_change = True if query: logfile.write('timestamp: %s\n' % datetime.datetime.today().isoformat()) table._db['_lastsql'] = '\n'.join(query) for sub_query in query: logfile.write(sub_query + '\n') if not fake_migrate: self.execute(sub_query) # caveat. mysql, oracle and firebird do not allow multiple alter table # in one transaction so we must commit partial transactions and # update table._dbt after alter table. if table._db._adapter.commit_on_alter_table: table._db.commit() tfile = self.file_open(table._dbt, 'w') cPickle.dump(sql_fields_current, tfile) self.file_close(tfile) logfile.write('success!\n') else: logfile.write('faked!\n') elif metadata_change: tfile = self.file_open(table._dbt, 'w') cPickle.dump(sql_fields_current, tfile) self.file_close(tfile) if metadata_change and \ not (query and self.dbengine in ('mysql','oracle','firebird')): table._db.commit() tfile = self.file_open(table._dbt, 'w') cPickle.dump(sql_fields_current, tfile) self.file_close(tfile) def LOWER(self,first): return 'LOWER(%s)' % self.expand(first) def UPPER(self,first): return 'UPPER(%s)' % self.expand(first) def EXTRACT(self,first,what): return "EXTRACT(%s FROM %s)" % (what, self.expand(first)) def AGGREGATE(self,first,what): return "%s(%s)" % (what,self.expand(first)) def JOIN(self): return 'JOIN' def LEFT_JOIN(self): return 'LEFT JOIN' def RANDOM(self): return 'Random()' def NOT_NULL(self,default,field_type): return 'NOT NULL DEFAULT %s' % self.represent(default,field_type) def COALESCE_ZERO(self,first): return 'COALESCE(%s,0)' % self.expand(first) def ALLOW_NULL(self): return '' def SUBSTRING(self,field,parameters): return 'SUBSTR(%s,%s,%s)' % (self.expand(field), parameters[0], parameters[1]) def PRIMARY_KEY(self,key): return 'PRIMARY KEY(%s)' % key def _drop(self,table,mode): return ['DROP TABLE %s;' % table] def drop(self, table, mode=''): if table._dbt: logfile = self.file_open(table._loggername, 'a') queries = self._drop(table, mode) for query in queries: if table._dbt: logfile.write(query + '\n') self.execute(query) table._db.commit() del table._db[table._tablename] del table._db.tables[table._db.tables.index(table._tablename)] table._db._update_referenced_by(table._tablename) if table._dbt: self.file_delete(table._dbt) logfile.write('success!\n') def _insert(self,table,fields): keys = ','.join(f.name for f,v in fields) values = ','.join(self.expand(v,f.type) for f,v in fields) return 'INSERT INTO %s(%s) VALUES (%s);' % (table, keys, values) def insert(self,table,fields): query = self._insert(table,fields) try: self.execute(query) except Exception, e: if isinstance(e,self.integrity_error_class()): return None raise e if hasattr(table,'_primarykey'): return dict([(k[0].name, k[1]) for k in fields \ if k[0].name in table._primarykey]) id = self.lastrowid(table) if not isinstance(id,int): return id rid = Reference(id) (rid._table, rid._record) = (table, None) return rid def bulk_insert(self,table,items): return [self.insert(table,item) for item in items] def NOT(self,first): return '(NOT %s)' % self.expand(first) def AND(self,first,second): return '(%s AND %s)' % (self.expand(first),self.expand(second)) def OR(self,first,second): return '(%s OR %s)' % (self.expand(first),self.expand(second)) def BELONGS(self,first,second): if isinstance(second,str): return '(%s IN (%s))' % (self.expand(first),second[:-1]) elif second==[] or second==(): return '(0)' items =','.join(self.expand(item,first.type) for item in second) return '(%s IN (%s))' % (self.expand(first),items) def LIKE(self,first,second): return '(%s LIKE %s)' % (self.expand(first),self.expand(second,'string')) def STARTSWITH(self,first,second): return '(%s LIKE %s)' % (self.expand(first),self.expand(second+'%','string')) def ENDSWITH(self,first,second): return '(%s LIKE %s)' % (self.expand(first),self.expand('%'+second,'string')) def CONTAINS(self,first,second): if first.type in ('string','text'): key = '%'+str(second).replace('%','%%')+'%' elif first.type.startswith('list:'): key = '%|'+str(second).replace('|','||').replace('%','%%')+'|%' return '(%s LIKE %s)' % (self.expand(first),self.expand(key,'string')) def EQ(self,first,second=None): if second is None: return '(%s IS NULL)' % self.expand(first) return '(%s = %s)' % (self.expand(first),self.expand(second,first.type)) def NE(self,first,second=None): if second is None: return '(%s IS NOT NULL)' % self.expand(first) return '(%s <> %s)' % (self.expand(first),self.expand(second,first.type)) def LT(self,first,second=None): return '(%s < %s)' % (self.expand(first),self.expand(second,first.type)) def LE(self,first,second=None): return '(%s <= %s)' % (self.expand(first),self.expand(second,first.type)) def GT(self,first,second=None): return '(%s > %s)' % (self.expand(first),self.expand(second,first.type)) def GE(self,first,second=None): return '(%s >= %s)' % (self.expand(first),self.expand(second,first.type)) def ADD(self,first,second): return '(%s + %s)' % (self.expand(first),self.expand(second,first.type)) def SUB(self,first,second): return '(%s - %s)' % (self.expand(first),self.expand(second,first.type)) def MUL(self,first,second): return '(%s * %s)' % (self.expand(first),self.expand(second,first.type)) def DIV(self,first,second): return '(%s / %s)' % (self.expand(first),self.expand(second,first.type)) def MOD(self,first,second): return '(%s %% %s)' % (self.expand(first),self.expand(second,first.type)) def AS(self,first,second): return '%s AS %s' % (self.expand(first),second) def ON(self,first,second): return '%s ON %s' % (self.expand(first),self.expand(second)) def INVERT(self,first): return '%s DESC' % self.expand(first) def COMMA(self,first,second): return '%s, %s' % (self.expand(first),self.expand(second)) def expand(self,expression,field_type=None): if isinstance(expression,Field): return str(expression) elif isinstance(expression, (Expression, Query)): if not expression.second is None: return expression.op(expression.first, expression.second) elif not expression.first is None: return expression.op(expression.first) else: return expression.op() elif field_type: return self.represent(expression,field_type) elif isinstance(expression,(list,tuple)): return ','.join([self.represent(item,field_type) for item in expression]) else: return str(expression) def alias(self,table,alias): """ given a table object, makes a new table object with alias name. """ other = copy.copy(table) other['_ot'] = other._tablename other['ALL'] = SQLALL(other) other['_tablename'] = alias for fieldname in other.fields: other[fieldname] = copy.copy(other[fieldname]) other[fieldname]._tablename = alias other[fieldname].tablename = alias other[fieldname].table = other table._db[alias] = other return other def _truncate(self,table,mode = ''): tablename = table._tablename return ['TRUNCATE TABLE %s %s;' % (tablename, mode or '')] def truncate(self,table,mode= ' '): # Prepare functions "write_to_logfile" and "close_logfile" if table._dbt: logfile = self.file_open(table._loggername, 'a') else: class Logfile(object): def write(self, value): pass def close(self): pass logfile = Logfile() try: queries = table._db._adapter._truncate(table, mode) for query in queries: logfile.write(query + '\n') self.execute(query) table._db.commit() logfile.write('success!\n') finally: logfile.close() def _update(self,tablename,query,fields): if query: sql_w = ' WHERE ' + self.expand(query) else: sql_w = '' sql_v = ','.join(['%s=%s' % (field.name, self.expand(value,field.type)) for (field,value) in fields]) return 'UPDATE %s SET %s%s;' % (tablename, sql_v, sql_w) def update(self,tablename,query,fields): sql = self._update(tablename,query,fields) self.execute(sql) try: return self.cursor.rowcount except: return None def _delete(self,tablename, query): if query: sql_w = ' WHERE ' + self.expand(query) else: sql_w = '' return 'DELETE FROM %s%s;' % (tablename, sql_w) def delete(self,tablename,query): sql = self._delete(tablename,query) ### special code to handle CASCADE in SQLite db = self.db table = db[tablename] if self.dbengine=='sqlite' and table._referenced_by: deleted = [x[table._id.name] for x in db(query).select(table._id)] ### end special code to handle CASCADE in SQLite self.execute(sql) try: counter = self.cursor.rowcount except: counter = None ### special code to handle CASCADE in SQLite if self.dbengine=='sqlite' and counter: for tablename,fieldname in table._referenced_by: f = db[tablename][fieldname] if f.type=='reference '+table._tablename and f.ondelete=='CASCADE': db(db[tablename][fieldname].belongs(deleted)).delete() ### end special code to handle CASCADE in SQLite return counter def get_table(self,query): tablenames = self.tables(query) if len(tablenames)==1: return tablenames[0] elif len(tablenames)<1: raise RuntimeError, "No table selected" else: raise RuntimeError, "Too many tables selected" def _select(self, query, fields, attributes): for key in set(attributes.keys())-set(('orderby','groupby','limitby', 'required','cache','left', 'distinct','having', 'join')): raise SyntaxError, 'invalid select attribute: %s' % key # ## if not fields specified take them all from the requested tables new_fields = [] for item in fields: if isinstance(item,SQLALL): new_fields += item.table else: new_fields.append(item) fields = new_fields tablenames = self.tables(query) query = self.filter_tenant(query,tablenames) if not fields: for table in tablenames: for field in self.db[table]: fields.append(field) else: for field in fields: if isinstance(field,basestring) and table_field.match(field): tn,fn = field.split('.') field = self.db[tn][fn] for tablename in self.tables(field): if not tablename in tablenames: tablenames.append(tablename) if len(tablenames) < 1: raise SyntaxError, 'Set: no tables selected' sql_f = ', '.join(map(self.expand,fields)) self._colnames = [c.strip() for c in sql_f.split(', ')] if query: sql_w = ' WHERE ' + self.expand(query) else: sql_w = '' sql_o = '' sql_s = '' left = attributes.get('left', False) inner_join = attributes.get('join', False) distinct = attributes.get('distinct', False) groupby = attributes.get('groupby', False) orderby = attributes.get('orderby', False) having = attributes.get('having', False) limitby = attributes.get('limitby', False) if distinct is True: sql_s += 'DISTINCT' elif distinct: sql_s += 'DISTINCT ON (%s)' % distinct if inner_join: icommand = self.JOIN() if not isinstance(inner_join, (tuple, list)): inner_join = [inner_join] ijoint = [t._tablename for t in inner_join if not isinstance(t,Expression)] ijoinon = [t for t in inner_join if isinstance(t, Expression)] ijoinont = [t.first._tablename for t in ijoinon] iexcluded = [t for t in tablenames if not t in ijoint + ijoinont] if left: join = attributes['left'] command = self.LEFT_JOIN() if not isinstance(join, (tuple, list)): join = [join] joint = [t._tablename for t in join if not isinstance(t,Expression)] joinon = [t for t in join if isinstance(t, Expression)] #patch join+left patch (solves problem with ordering in left joins) tables_to_merge={} [tables_to_merge.update(dict.fromkeys(self.tables(t))) for t in joinon] joinont = [t.first._tablename for t in joinon] [tables_to_merge.pop(t) for t in joinont if t in tables_to_merge] important_tablenames = joint + joinont + tables_to_merge.keys() excluded = [t for t in tablenames if not t in important_tablenames ] def alias(t): return str(self.db[t]) if inner_join and not left: sql_t = ', '.join(alias(t) for t in iexcluded) for t in ijoinon: sql_t += ' %s %s' % (icommand, str(t)) elif not inner_join and left: sql_t = ', '.join([alias(t) for t in excluded + tables_to_merge.keys()]) if joint: sql_t += ' %s %s' % (command, ','.join([t for t in joint])) for t in joinon: sql_t += ' %s %s' % (command, str(t)) elif inner_join and left: sql_t = ','.join([alias(t) for t in excluded + \ tables_to_merge.keys() if t in iexcluded ]) for t in ijoinon: sql_t += ' %s %s' % (icommand, str(t)) if joint: sql_t += ' %s %s' % (command, ','.join([t for t in joint])) for t in joinon: sql_t += ' %s %s' % (command, str(t)) else: sql_t = ', '.join(alias(t) for t in tablenames) if groupby: if isinstance(groupby, (list, tuple)): groupby = xorify(groupby) sql_o += ' GROUP BY %s' % self.expand(groupby) if having: sql_o += ' HAVING %s' % attributes['having'] if orderby: if isinstance(orderby, (list, tuple)): orderby = xorify(orderby) if str(orderby) == '<random>': sql_o += ' ORDER BY %s' % self.RANDOM() else: sql_o += ' ORDER BY %s' % self.expand(orderby) if limitby: if not orderby and tablenames: sql_o += ' ORDER BY %s' % ', '.join(['%s.%s'%(t,x) for t in tablenames for x in ((hasattr(self.db[t],'_primarykey') and self.db[t]._primarykey) or [self.db[t]._id.name])]) # oracle does not support limitby return self.select_limitby(sql_s, sql_f, sql_t, sql_w, sql_o, limitby) def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby): if limitby: (lmin, lmax) = limitby sql_o += ' LIMIT %i OFFSET %i' % (lmax - lmin, lmin) return 'SELECT %s %s FROM %s%s%s;' % (sql_s, sql_f, sql_t, sql_w, sql_o) def select(self,query,fields,attributes): """ Always returns a Rows object, even if it may be empty """ def response(sql): self.execute(sql) return self.cursor.fetchall() sql = self._select(query,fields,attributes) if attributes.get('cache', None): (cache_model, time_expire) = attributes['cache'] del attributes['cache'] key = self.uri + '/' + sql key = (key<=200) and key or hashlib.md5(key).hexdigest() rows = cache_model(key, lambda: response(sql), time_expire) else: rows = response(sql) if isinstance(rows,tuple): rows = list(rows) limitby = attributes.get('limitby',None) or (0,) rows = self.rowslice(rows,limitby[0],None) return self.parse(rows,self._colnames) def _count(self,query,distinct=None): tablenames = self.tables(query) if query: sql_w = ' WHERE ' + self.expand(query) else: sql_w = '' sql_t = ','.join(tablenames) if distinct: if isinstance(distinct,(list,tuple)): distinct = xorify(distinct) sql_d = self.expand(distinct) return 'SELECT count(DISTINCT %s) FROM %s%s' % (sql_d, sql_t, sql_w) return 'SELECT count(*) FROM %s%s' % (sql_t, sql_w) def count(self,query,distinct=None): self.execute(self._count(query,distinct)) return self.cursor.fetchone()[0] def tables(self,query): tables = set() if isinstance(query, Field): tables.add(query.tablename) elif isinstance(query, (Expression, Query)): if query.first!=None: tables = tables.union(self.tables(query.first)) if query.second!=None: tables = tables.union(self.tables(query.second)) return list(tables) def commit(self): return self.connection.commit() def rollback(self): return self.connection.rollback() def close(self): return self.connection.close() def distributed_transaction_begin(self,key): return def prepare(self,key): self.connection.prepare() def commit_prepared(self,key): self.connection.commit() def rollback_prepared(self,key): self.connection.rollback() def concat_add(self,table): return ', ADD ' def constraint_name(self, table, fieldname): return '%s_%s__constraint' % (table,fieldname) def create_sequence_and_triggers(self, query, table, **args): self.execute(query) def log_execute(self,*a,**b): self.db._lastsql = a[0] t0 = time.time() ret = self.cursor.execute(*a,**b) self.db._timings.append((a[0],time.time()-t0)) return ret def execute(self,*a,**b): return self.log_execute(*a, **b) def represent(self, obj, fieldtype): if isinstance(obj,CALLABLETYPES): obj = obj() if isinstance(fieldtype, SQLCustomType): return fieldtype.encoder(obj) if isinstance(obj, (Expression, Field)): return str(obj) if fieldtype.startswith('list:'): if not obj: obj = [] if not isinstance(obj, (list, tuple)): obj = [obj] if isinstance(obj, (list, tuple)): obj = bar_encode(obj) if obj is None: return 'NULL' if obj == '' and not fieldtype[:2] in ['st', 'te', 'pa', 'up']: return 'NULL' r = self.represent_exceptions(obj,fieldtype) if r != None: return r if fieldtype == 'boolean': if obj and not str(obj)[:1].upper() in ['F', '0']: return "'T'" else: return "'F'" if fieldtype == 'id' or fieldtype == 'integer': return str(int(obj)) if fieldtype.startswith('decimal'): return str(obj) elif fieldtype.startswith('reference'): # reference if fieldtype.find('.')>0: return repr(obj) elif isinstance(obj, (Row, Reference)): return str(obj['id']) return str(int(obj)) elif fieldtype == 'double': return repr(float(obj)) if isinstance(obj, unicode): obj = obj.encode(self.db_codec) if fieldtype == 'blob': obj = base64.b64encode(str(obj)) elif fieldtype == 'date': if isinstance(obj, (datetime.date, datetime.datetime)): obj = obj.isoformat()[:10] else: obj = str(obj) elif fieldtype == 'datetime': if isinstance(obj, datetime.datetime): obj = obj.isoformat()[:19].replace('T',' ') elif isinstance(obj, datetime.date): obj = obj.isoformat()[:10]+' 00:00:00' else: obj = str(obj) elif fieldtype == 'time': if isinstance(obj, datetime.time): obj = obj.isoformat()[:10] else: obj = str(obj) if not isinstance(obj,str): obj = str(obj) try: obj.decode(self.db_codec) except: obj = obj.decode('latin1').encode(self.db_codec) return "'%s'" % obj.replace("'", "''") def represent_exceptions(self, obj, fieldtype): return None def lastrowid(self,table): return None def integrity_error_class(self): return type(None) def rowslice(self,rows,minimum=0,maximum=None): """ by default this function does nothing, overload when db does not do slicing """ return rows def parse(self, rows, colnames, blob_decode=True): db = self.db virtualtables = [] new_rows = [] for (i,row) in enumerate(rows): new_row = Row() for j,colname in enumerate(colnames): value = row[j] if not table_field.match(colnames[j]): if not '_extra' in new_row: new_row['_extra'] = Row() new_row['_extra'][colnames[j]] = value select_as_parser = re.compile("\s+AS\s+(\S+)") new_column_name = select_as_parser.search(colnames[j]) if not new_column_name is None: column_name = new_column_name.groups(0) setattr(new_row,column_name[0],value) continue (tablename, fieldname) = colname.split('.') table = db[tablename] field = table[fieldname] field_type = field.type if field.type != 'blob' and isinstance(value, str): try: value = value.decode(db._db_codec) except Exception: pass if isinstance(value, unicode): value = value.encode('utf-8') if not tablename in new_row: colset = new_row[tablename] = Row() if tablename not in virtualtables: virtualtables.append(tablename) else: colset = new_row[tablename] if isinstance(field_type, SQLCustomType): colset[fieldname] = field_type.decoder(value) # field_type = field_type.type elif not isinstance(field_type, str) or value is None: colset[fieldname] = value elif isinstance(field_type, str) and \ field_type.startswith('reference'): referee = field_type[10:].strip() if not '.' in referee: colset[fieldname] = rid = Reference(value) (rid._table, rid._record) = (db[referee], None) else: ### reference not by id colset[fieldname] = value elif field_type == 'boolean': if value == True or str(value)[:1].lower() == 't': colset[fieldname] = True else: colset[fieldname] = False elif field_type == 'date' \ and (not isinstance(value, datetime.date)\ or isinstance(value, datetime.datetime)): (y, m, d) = map(int, str(value)[:10].strip().split('-')) colset[fieldname] = datetime.date(y, m, d) elif field_type == 'time' \ and not isinstance(value, datetime.time): time_items = map(int,str(value)[:8].strip().split(':')[:3]) if len(time_items) == 3: (h, mi, s) = time_items else: (h, mi, s) = time_items + [0] colset[fieldname] = datetime.time(h, mi, s) elif field_type == 'datetime'\ and not isinstance(value, datetime.datetime): (y, m, d) = map(int,str(value)[:10].strip().split('-')) time_items = map(int,str(value)[11:19].strip().split(':')[:3]) if len(time_items) == 3: (h, mi, s) = time_items else: (h, mi, s) = time_items + [0] colset[fieldname] = datetime.datetime(y, m, d, h, mi, s) elif field_type == 'blob' and blob_decode: colset[fieldname] = base64.b64decode(str(value)) elif field_type.startswith('decimal'): decimals = int(field_type[8:-1].split(',')[-1]) if self.dbengine == 'sqlite': value = ('%.' + str(decimals) + 'f') % value if not isinstance(value, decimal.Decimal): value = decimal.Decimal(str(value)) colset[fieldname] = value elif field_type.startswith('list:integer'): if not self.dbengine=='google:datastore': colset[fieldname] = bar_decode_integer(value) else: colset[fieldname] = value elif field_type.startswith('list:reference'): if not self.dbengine=='google:datastore': colset[fieldname] = bar_decode_integer(value) else: colset[fieldname] = value elif field_type.startswith('list:string'): if not self.dbengine=='google:datastore': colset[fieldname] = bar_decode_string(value) else: colset[fieldname] = value else: colset[fieldname] = value if field_type == 'id': id = colset[field.name] colset.update_record = lambda _ = (colset, table, id), **a: update_record(_, a) colset.delete_record = lambda t = table, i = id: t._db(t._id==i).delete() for (referee_table, referee_name) in \ table._referenced_by: s = db[referee_table][referee_name] if not referee_table in colset: # for backward compatibility colset[referee_table] = Set(db, s == id) ### add new feature? ### colset[referee_table+'_by_'+refree_name] = Set(db, s == id) colset['id'] = id new_rows.append(new_row) rowsobj = Rows(db, new_rows, colnames, rawrows=rows) for tablename in virtualtables: for item in db[tablename].virtualfields: try: rowsobj = rowsobj.setvirtualfields(**{tablename:item}) except KeyError: # to avoid breaking virtualfields when partial select pass return rowsobj def filter_tenant(self,query,tablenames): fieldname = self.db._request_tenant for tablename in tablenames: table = self.db[tablename] if fieldname in table: default = table[fieldname].default if default!=None: query = query&(table[fieldname]==default) return query ################################################################################### # List of all the available adapters, they all extend BaseAdapter ################################################################################### class SQLiteAdapter(BaseAdapter): driver = globals().get('sqlite3',None) def EXTRACT(self,field,what): return "web2py_extract('%s',%s)" % (what,self.expand(field)) @staticmethod def web2py_extract(lookup, s): table = { 'year': (0, 4), 'month': (5, 7), 'day': (8, 10), 'hour': (11, 13), 'minute': (14, 16), 'second': (17, 19), } try: (i, j) = table[lookup] return int(s[i:j]) except: return None def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=lambda x:x, driver_args={}, adapter_args={}): self.db = db self.dbengine = "sqlite" self.uri = uri self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self.find_or_make_work_folder() path_encoding = sys.getfilesystemencoding() or locale.getdefaultlocale()[1] or 'utf8' if uri.startswith('sqlite:memory'): dbpath = ':memory:' else: dbpath = uri.split('://')[1] if dbpath[0] != '/': dbpath = os.path.join(self.folder.decode(path_encoding).encode('utf8'),dbpath) if not 'check_same_thread' in driver_args: driver_args['check_same_thread'] = False def connect(dbpath=dbpath, driver_args=driver_args): return self.driver.Connection(dbpath, **driver_args) self.pool_connection(connect) self.cursor = self.connection.cursor() self.connection.create_function('web2py_extract', 2, SQLiteAdapter.web2py_extract) def _truncate(self,table,mode = ''): tablename = table._tablename return ['DELETE FROM %s;' % tablename, "DELETE FROM sqlite_sequence WHERE name='%s';" % tablename] def lastrowid(self,table): return self.cursor.lastrowid class JDBCSQLiteAdapter(SQLiteAdapter): driver = globals().get('zxJDBC',None) def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=lambda x:x, driver_args={}, adapter_args={}): self.db = db self.dbengine = "sqlite" self.uri = uri self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self.find_or_make_work_folder() path_encoding = sys.getfilesystemencoding() or locale.getdefaultlocale()[1] or 'utf8' if uri.startswith('sqlite:memory'): dbpath = ':memory:' else: dbpath = uri.split('://')[1] if dbpath[0] != '/': dbpath = os.path.join(self.folder.decode(path_encoding).encode('utf8'),dbpath) def connect(dbpath=dbpath,driver_args=driver_args): return self.driver.connect(java.sql.DriverManager.getConnection('jdbc:sqlite:'+dbpath),**driver_args) self.pool_connection(connect) self.cursor = self.connection.cursor() # FIXME http://www.zentus.com/sqlitejdbc/custom_functions.html for UDFs # self.connection.create_function('web2py_extract', 2, SQLiteAdapter.web2py_extract) def execute(self,a): return self.log_execute(a[:-1]) class MySQLAdapter(BaseAdapter): driver = globals().get('pymysql',None) maxcharlength = 255 commit_on_alter_table = True support_distributed_transaction = True types = { 'boolean': 'CHAR(1)', 'string': 'VARCHAR(%(length)s)', 'text': 'LONGTEXT', 'password': 'VARCHAR(%(length)s)', 'blob': 'LONGBLOB', 'upload': 'VARCHAR(%(length)s)', 'integer': 'INT', 'double': 'DOUBLE', 'decimal': 'NUMERIC(%(precision)s,%(scale)s)', 'date': 'DATE', 'time': 'TIME', 'datetime': 'DATETIME', 'id': 'INT AUTO_INCREMENT NOT NULL', 'reference': 'INT, INDEX %(field_name)s__idx (%(field_name)s), FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'list:integer': 'LONGTEXT', 'list:string': 'LONGTEXT', 'list:reference': 'LONGTEXT', } def RANDOM(self): return 'RAND()' def SUBSTRING(self,field,parameters): return 'SUBSTRING(%s,%s,%s)' % (self.expand(field), parameters[0], parameters[1]) def _drop(self,table,mode): # breaks db integrity but without this mysql does not drop table return ['SET FOREIGN_KEY_CHECKS=0;','DROP TABLE %s;' % table,'SET FOREIGN_KEY_CHECKS=1;'] def distributed_transaction_begin(self,key): self.execute('XA START;') def prepare(self,key): self.execute("XA END;") self.execute("XA PREPARE;") def commit_prepared(self,ley): self.execute("XA COMMIT;") def rollback_prepared(self,key): self.execute("XA ROLLBACK;") def concat_add(self,table): return '; ALTER TABLE %s ADD ' % table def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=lambda x:x, driver_args={}, adapter_args={}): self.db = db self.dbengine = "mysql" self.uri = uri self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self.find_or_make_work_folder() uri = uri.split('://')[1] m = re.compile('^(?P<user>[^:@]+)(\:(?P<password>[^@]*))?@(?P<host>[^\:/]+)(\:(?P<port>[0-9]+))?/(?P<db>[^?]+)(\?set_encoding=(?P<charset>\w+))?$').match(uri) if not m: raise SyntaxError, \ "Invalid URI string in DAL: %s" % self.uri user = credential_decoder(m.group('user')) if not user: raise SyntaxError, 'User required' password = credential_decoder(m.group('password')) if not password: password = '' host = m.group('host') if not host: raise SyntaxError, 'Host name required' db = m.group('db') if not db: raise SyntaxError, 'Database name required' port = int(m.group('port') or '3306') charset = m.group('charset') or 'utf8' driver_args.update(dict(db=db, user=credential_decoder(user), passwd=credential_decoder(password), host=host, port=port, charset=charset)) def connect(driver_args=driver_args): return self.driver.connect(**driver_args) self.pool_connection(connect) self.cursor = self.connection.cursor() self.execute('SET FOREIGN_KEY_CHECKS=1;') self.execute("SET sql_mode='NO_BACKSLASH_ESCAPES';") def lastrowid(self,table): self.execute('select last_insert_id();') return int(self.cursor.fetchone()[0]) class PostgreSQLAdapter(BaseAdapter): driver = globals().get('psycopg2',None) support_distributed_transaction = True types = { 'boolean': 'CHAR(1)', 'string': 'VARCHAR(%(length)s)', 'text': 'TEXT', 'password': 'VARCHAR(%(length)s)', 'blob': 'BYTEA', 'upload': 'VARCHAR(%(length)s)', 'integer': 'INTEGER', 'double': 'FLOAT8', 'decimal': 'NUMERIC(%(precision)s,%(scale)s)', 'date': 'DATE', 'time': 'TIME', 'datetime': 'TIMESTAMP', 'id': 'SERIAL PRIMARY KEY', 'reference': 'INTEGER REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'list:integer': 'TEXT', 'list:string': 'TEXT', 'list:reference': 'TEXT', } def sequence_name(self,table): return '%s_id_Seq' % table def RANDOM(self): return 'RANDOM()' def distributed_transaction_begin(self,key): return def prepare(self,key): self.execute("PREPARE TRANSACTION '%s';" % key) def commit_prepared(self,key): self.execute("COMMIT PREPARED '%s';" % key) def rollback_prepared(self,key): self.execute("ROLLBACK PREPARED '%s';" % key) def create_sequence_and_triggers(self, query, table, **args): # following lines should only be executed if table._sequence_name does not exist # self.execute('CREATE SEQUENCE %s;' % table._sequence_name) # self.execute("ALTER TABLE %s ALTER COLUMN %s SET DEFAULT NEXTVAL('%s');" \ # % (table._tablename, table._fieldname, table._sequence_name)) self.execute(query) def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=lambda x:x, driver_args={}, adapter_args={}): self.db = db self.dbengine = "postgres" self.uri = uri self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self.find_or_make_work_folder() uri = uri.split('://')[1] m = re.compile('^(?P<user>[^:@]+)(\:(?P<password>[^@]*))?@(?P<host>[^\:@/]+)(\:(?P<port>[0-9]+))?/(?P<db>[^\?]+)(\?sslmode=(?P<sslmode>.+))?$').match(uri) if not m: raise SyntaxError, "Invalid URI string in DAL" user = credential_decoder(m.group('user')) if not user: raise SyntaxError, 'User required' password = credential_decoder(m.group('password')) if not password: password = '' host = m.group('host') if not host: raise SyntaxError, 'Host name required' db = m.group('db') if not db: raise SyntaxError, 'Database name required' port = m.group('port') or '5432' sslmode = m.group('sslmode') if sslmode: msg = ("dbname='%s' user='%s' host='%s'" "port=%s password='%s' sslmode='%s'") \ % (db, user, host, port, password, sslmode) else: msg = ("dbname='%s' user='%s' host='%s'" "port=%s password='%s'") \ % (db, user, host, port, password) def connect(msg=msg,driver_args=driver_args): return self.driver.connect(msg,**driver_args) self.pool_connection(connect) self.connection.set_client_encoding('UTF8') self.cursor = self.connection.cursor() self.execute('BEGIN;') self.execute("SET CLIENT_ENCODING TO 'UNICODE';") self.execute("SET standard_conforming_strings=on;") def lastrowid(self,table): self.execute("select currval('%s')" % table._sequence_name) return int(self.cursor.fetchone()[0]) def LIKE(self,first,second): return '(%s ILIKE %s)' % (self.expand(first),self.expand(second,'string')) def STARTSWITH(self,first,second): return '(%s ILIKE %s)' % (self.expand(first),self.expand(second+'%','string')) def ENDSWITH(self,first,second): return '(%s ILIKE %s)' % (self.expand(first),self.expand('%'+second,'string')) def CONTAINS(self,first,second): if first.type in ('string','text'): key = '%'+str(second).replace('%','%%')+'%' elif first.type.startswith('list:'): key = '%|'+str(second).replace('|','||').replace('%','%%')+'|%' return '(%s ILIKE %s)' % (self.expand(first),self.expand(key,'string')) class JDBCPostgreSQLAdapter(PostgreSQLAdapter): def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=lambda x:x, driver_args={}, adapter_args={}): self.db = db self.dbengine = "postgres" self.uri = uri self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self.find_or_make_work_folder() uri = uri.split('://')[1] m = re.compile('^(?P<user>[^:@]+)(\:(?P<password>[^@]*))?@(?P<host>[^\:/]+)(\:(?P<port>[0-9]+))?/(?P<db>.+)$').match(uri) if not m: raise SyntaxError, "Invalid URI string in DAL" user = credential_decoder(m.group('user')) if not user: raise SyntaxError, 'User required' password = credential_decoder(m.group('password')) if not password: password = '' host = m.group('host') if not host: raise SyntaxError, 'Host name required' db = m.group('db') if not db: raise SyntaxError, 'Database name required' port = m.group('port') or '5432' msg = ('jdbc:postgresql://%s:%s/%s' % (host, port, db), user, password) def connect(msg=msg,driver_args=driver_args): return self.driver.connect(*msg,**driver_args) self.pool_connection(connect) self.connection.set_client_encoding('UTF8') self.cursor = self.connection.cursor() self.execute('BEGIN;') self.execute("SET CLIENT_ENCODING TO 'UNICODE';") class OracleAdapter(BaseAdapter): driver = globals().get('cx_Oracle',None) commit_on_alter_table = False types = { 'boolean': 'CHAR(1)', 'string': 'VARCHAR2(%(length)s)', 'text': 'CLOB', 'password': 'VARCHAR2(%(length)s)', 'blob': 'CLOB', 'upload': 'VARCHAR2(%(length)s)', 'integer': 'INT', 'double': 'FLOAT', 'decimal': 'NUMERIC(%(precision)s,%(scale)s)', 'date': 'DATE', 'time': 'CHAR(8)', 'datetime': 'DATE', 'id': 'NUMBER PRIMARY KEY', 'reference': 'NUMBER, CONSTRAINT %(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'list:integer': 'CLOB', 'list:string': 'CLOB', 'list:reference': 'CLOB', } def sequence_name(self,tablename): return '%s_sequence' % tablename def trigger_name(self,tablename): return '%s_trigger' % tablename def LEFT_JOIN(self): return 'LEFT OUTER JOIN' def RANDOM(self): return 'dbms_random.value' def NOT_NULL(self,default,field_type): return 'DEFAULT %s NOT NULL' % self.represent(default,field_type) def _drop(self,table,mode): sequence_name = table._sequence_name return ['DROP TABLE %s %s;' % (table, mode), 'DROP SEQUENCE %s;' % sequence_name] def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby): if limitby: (lmin, lmax) = limitby if len(sql_w) > 1: sql_w_row = sql_w + ' AND w_row > %i' % lmin else: sql_w_row = 'WHERE w_row > %i' % lmin return 'SELECT %s %s FROM (SELECT w_tmp.*, ROWNUM w_row FROM (SELECT %s FROM %s%s%s) w_tmp WHERE ROWNUM<=%i) %s %s %s;' % (sql_s, sql_f, sql_f, sql_t, sql_w, sql_o, lmax, sql_t, sql_w_row, sql_o) return 'SELECT %s %s FROM %s%s%s;' % (sql_s, sql_f, sql_t, sql_w, sql_o) def constraint_name(self, tablename, fieldname): constraint_name = BaseAdapter.constraint_name(self, tablename, fieldname) if len(constraint_name)>30: constraint_name = '%s_%s__constraint' % (tablename[:10], fieldname[:7]) return constraint_name def represent_exceptions(self, obj, fieldtype): if fieldtype == 'blob': obj = base64.b64encode(str(obj)) return ":CLOB('%s')" % obj elif fieldtype == 'date': if isinstance(obj, (datetime.date, datetime.datetime)): obj = obj.isoformat()[:10] else: obj = str(obj) return "to_date('%s','yyyy-mm-dd')" % obj elif fieldtype == 'datetime': if isinstance(obj, datetime.datetime): obj = obj.isoformat()[:19].replace('T',' ') elif isinstance(obj, datetime.date): obj = obj.isoformat()[:10]+' 00:00:00' else: obj = str(obj) return "to_date('%s','yyyy-mm-dd hh24:mi:ss')" % obj return None def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=lambda x:x, driver_args={}, adapter_args={}): self.db = db self.dbengine = "oracle" self.uri = uri self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self.find_or_make_work_folder() uri = uri.split('://')[1] if not 'threaded' in driver_args: driver_args['threaded']=True def connect(uri=uri,driver_args=driver_args): return self.driver.connect(uri,**driver_args) self.pool_connection(connect) self.cursor = self.connection.cursor() self.execute("ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS';") self.execute("ALTER SESSION SET NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS';") oracle_fix = re.compile("[^']*('[^']*'[^']*)*\:(?P<clob>CLOB\('([^']+|'')*'\))") def execute(self, command): args = [] i = 1 while True: m = self.oracle_fix.match(command) if not m: break command = command[:m.start('clob')] + str(i) + command[m.end('clob'):] args.append(m.group('clob')[6:-2].replace("''", "'")) i += 1 return self.log_execute(command[:-1], args) def create_sequence_and_triggers(self, query, table, **args): tablename = table._tablename sequence_name = table._sequence_name trigger_name = table._trigger_name self.execute(query) self.execute('CREATE SEQUENCE %s START WITH 1 INCREMENT BY 1 NOMAXVALUE;' % sequence_name) self.execute('CREATE OR REPLACE TRIGGER %s BEFORE INSERT ON %s FOR EACH ROW BEGIN SELECT %s.nextval INTO :NEW.id FROM DUAL; END;\n' % (trigger_name, tablename, sequence_name)) def lastrowid(self,table): sequence_name = table._sequence_name self.execute('SELECT %s.currval FROM dual;' % sequence_name) return int(self.cursor.fetchone()[0]) class MSSQLAdapter(BaseAdapter): driver = globals().get('pyodbc',None) types = { 'boolean': 'BIT', 'string': 'VARCHAR(%(length)s)', 'text': 'TEXT', 'password': 'VARCHAR(%(length)s)', 'blob': 'IMAGE', 'upload': 'VARCHAR(%(length)s)', 'integer': 'INT', 'double': 'FLOAT', 'decimal': 'NUMERIC(%(precision)s,%(scale)s)', 'date': 'DATETIME', 'time': 'CHAR(8)', 'datetime': 'DATETIME', 'id': 'INT IDENTITY PRIMARY KEY', 'reference': 'INT NULL, CONSTRAINT %(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference FK': ', CONSTRAINT FK_%(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference TFK': ' CONSTRAINT FK_%(foreign_table)s_PK FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_table)s (%(foreign_key)s) ON DELETE %(on_delete_action)s', 'list:integer': 'TEXT', 'list:string': 'TEXT', 'list:reference': 'TEXT', } def EXTRACT(self,field,what): return "DATEPART(%s,%s)" % (what, self.expand(field)) def LEFT_JOIN(self): return 'LEFT OUTER JOIN' def RANDOM(self): return 'NEWID()' def ALLOW_NULL(self): return ' NULL' def SUBSTRING(self,field,parameters): return 'SUBSTRING(%s,%s,%s)' % (self.expand(field), parameters[0], parameters[1]) def PRIMARY_KEY(self,key): return 'PRIMARY KEY CLUSTERED (%s)' % key def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby): if limitby: (lmin, lmax) = limitby sql_s += ' TOP %i' % lmax return 'SELECT %s %s FROM %s%s%s;' % (sql_s, sql_f, sql_t, sql_w, sql_o) def represent_exceptions(self, obj, fieldtype): if fieldtype == 'boolean': if obj and not str(obj)[0].upper() == 'F': return '1' else: return '0' return None def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=lambda x:x, driver_args={}, adapter_args={}, fake_connect=False): self.db = db self.dbengine = "mssql" self.uri = uri self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self.find_or_make_work_folder() # ## read: http://bytes.com/groups/python/460325-cx_oracle-utf8 uri = uri.split('://')[1] if '@' not in uri: try: m = re.compile('^(?P<dsn>.+)$').match(uri) if not m: raise SyntaxError, \ 'Parsing uri string(%s) has no result' % self.uri dsn = m.group('dsn') if not dsn: raise SyntaxError, 'DSN required' except SyntaxError, e: logger.error('NdGpatch error') raise e cnxn = 'DSN=%s' % dsn else: m = re.compile('^(?P<user>[^:@]+)(\:(?P<password>[^@]*))?@(?P<host>[^\:/]+)(\:(?P<port>[0-9]+))?/(?P<db>[^\?]+)(\?(?P<urlargs>.*))?$').match(uri) if not m: raise SyntaxError, \ "Invalid URI string in DAL: %s" % uri user = credential_decoder(m.group('user')) if not user: raise SyntaxError, 'User required' password = credential_decoder(m.group('password')) if not password: password = '' host = m.group('host') if not host: raise SyntaxError, 'Host name required' db = m.group('db') if not db: raise SyntaxError, 'Database name required' port = m.group('port') or '1433' # Parse the optional url name-value arg pairs after the '?' # (in the form of arg1=value1&arg2=value2&...) # Default values (drivers like FreeTDS insist on uppercase parameter keys) argsdict = { 'DRIVER':'{SQL Server}' } urlargs = m.group('urlargs') or '' argpattern = re.compile('(?P<argkey>[^=]+)=(?P<argvalue>[^&]*)') for argmatch in argpattern.finditer(urlargs): argsdict[str(argmatch.group('argkey')).upper()] = argmatch.group('argvalue') urlargs = ';'.join(['%s=%s' % (ak, av) for (ak, av) in argsdict.items()]) cnxn = 'SERVER=%s;PORT=%s;DATABASE=%s;UID=%s;PWD=%s;%s' \ % (host, port, db, user, password, urlargs) def connect(cnxn=cnxn,driver_args=driver_args): return self.driver.connect(cnxn,**driver_args) if not fake_connect: self.pool_connection(connect) self.cursor = self.connection.cursor() def lastrowid(self,table): #self.execute('SELECT @@IDENTITY;') self.execute('SELECT SCOPE_IDENTITY();') return int(self.cursor.fetchone()[0]) def integrity_error_class(self): return pyodbc.IntegrityError def rowslice(self,rows,minimum=0,maximum=None): if maximum is None: return rows[minimum:] return rows[minimum:maximum] class MSSQL2Adapter(MSSQLAdapter): types = { 'boolean': 'CHAR(1)', 'string': 'NVARCHAR(%(length)s)', 'text': 'NTEXT', 'password': 'NVARCHAR(%(length)s)', 'blob': 'IMAGE', 'upload': 'NVARCHAR(%(length)s)', 'integer': 'INT', 'double': 'FLOAT', 'decimal': 'NUMERIC(%(precision)s,%(scale)s)', 'date': 'DATETIME', 'time': 'CHAR(8)', 'datetime': 'DATETIME', 'id': 'INT IDENTITY PRIMARY KEY', 'reference': 'INT, CONSTRAINT %(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference FK': ', CONSTRAINT FK_%(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference TFK': ' CONSTRAINT FK_%(foreign_table)s_PK FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_table)s (%(foreign_key)s) ON DELETE %(on_delete_action)s', 'list:integer': 'NTEXT', 'list:string': 'NTEXT', 'list:reference': 'NTEXT', } def represent(self, obj, fieldtype): value = BaseAdapter.represent(self, obj, fieldtype) if (fieldtype == 'string' or fieldtype == 'text') and value[:1]=="'": value = 'N'+value return value def execute(self,a): return self.log_execute(a.decode('utf8')) class FireBirdAdapter(BaseAdapter): driver = globals().get('pyodbc',None) commit_on_alter_table = False support_distributed_transaction = True types = { 'boolean': 'CHAR(1)', 'string': 'VARCHAR(%(length)s)', 'text': 'BLOB SUB_TYPE 1', 'password': 'VARCHAR(%(length)s)', 'blob': 'BLOB SUB_TYPE 0', 'upload': 'VARCHAR(%(length)s)', 'integer': 'INTEGER', 'double': 'DOUBLE PRECISION', 'decimal': 'DECIMAL(%(precision)s,%(scale)s)', 'date': 'DATE', 'time': 'TIME', 'datetime': 'TIMESTAMP', 'id': 'INTEGER PRIMARY KEY', 'reference': 'INTEGER REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'list:integer': 'BLOB SUB_TYPE 1', 'list:string': 'BLOB SUB_TYPE 1', 'list:reference': 'BLOB SUB_TYPE 1', } def sequence_name(self,tablename): return 'genid_%s' % tablename def trigger_name(self,tablename): return 'trg_id_%s' % tablename def RANDOM(self): return 'RAND()' def NOT_NULL(self,default,field_type): return 'DEFAULT %s NOT NULL' % self.represent(default,field_type) def SUBSTRING(self,field,parameters): return 'SUBSTRING(%s from %s for %s)' % (self.expand(field), parameters[0], parameters[1]) def _drop(self,table,mode): sequence_name = table._sequence_name return ['DROP TABLE %s %s;' % (table, mode), 'DROP GENERATOR %s;' % sequence_name] def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby): if limitby: (lmin, lmax) = limitby sql_s += ' FIRST %i SKIP %i' % (lmax - lmin, lmin) return 'SELECT %s %s FROM %s%s%s;' % (sql_s, sql_f, sql_t, sql_w, sql_o) def _truncate(self,table,mode = ''): return ['DELETE FROM %s;' % table._tablename, 'SET GENERATOR %s TO 0;' % table._sequence_name] def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=lambda x:x, driver_args={}, adapter_args={}): self.db = db self.dbengine = "firebird" self.uri = uri self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self.find_or_make_work_folder() uri = uri.split('://')[1] m = re.compile('^(?P<user>[^:@]+)(\:(?P<password>[^@]*))?@(?P<host>[^\:/]+)(\:(?P<port>[0-9]+))?/(?P<db>.+?)(\?set_encoding=(?P<charset>\w+))?$').match(uri) if not m: raise SyntaxError, "Invalid URI string in DAL: %s" % uri user = credential_decoder(m.group('user')) if not user: raise SyntaxError, 'User required' password = credential_decoder(m.group('password')) if not password: password = '' host = m.group('host') if not host: raise SyntaxError, 'Host name required' port = int(m.group('port') or 3050) db = m.group('db') if not db: raise SyntaxError, 'Database name required' charset = m.group('charset') or 'UTF8' driver_args.update(dict(dsn='%s/%s:%s' % (host,port,db), user = credential_decoder(user), password = credential_decoder(password), charset = charset)) if adapter_args.has_key('driver_name'): if adapter_args['driver_name'] == 'kinterbasdb': self.driver = kinterbasdb elif adapter_args['driver_name'] == 'firebirdsql': self.driver = firebirdsql else: self.driver = kinterbasdb def connect(driver_args=driver_args): return self.driver.connect(**driver_args) self.pool_connection(connect) self.cursor = self.connection.cursor() def create_sequence_and_triggers(self, query, table, **args): tablename = table._tablename sequence_name = table._sequence_name trigger_name = table._trigger_name self.execute(query) self.execute('create generator %s;' % sequence_name) self.execute('set generator %s to 0;' % sequence_name) self.execute('create trigger %s for %s active before insert position 0 as\nbegin\nif(new.id is null) then\nbegin\nnew.id = gen_id(%s, 1);\nend\nend;' % (trigger_name, tablename, sequence_name)) def lastrowid(self,table): sequence_name = table._sequence_name self.execute('SELECT gen_id(%s, 0) FROM rdb$database' % sequence_name) return int(self.cursor.fetchone()[0]) class FireBirdEmbeddedAdapter(FireBirdAdapter): def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=lambda x:x, driver_args={}, adapter_args={}): self.db = db self.dbengine = "firebird" self.uri = uri self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self.find_or_make_work_folder() uri = uri.split('://')[1] m = re.compile('^(?P<user>[^:@]+)(\:(?P<password>[^@]*))?@(?P<path>[^\?]+)(\?set_encoding=(?P<charset>\w+))?$').match(uri) if not m: raise SyntaxError, \ "Invalid URI string in DAL: %s" % self.uri user = credential_decoder(m.group('user')) if not user: raise SyntaxError, 'User required' password = credential_decoder(m.group('password')) if not password: password = '' pathdb = m.group('path') if not pathdb: raise SyntaxError, 'Path required' charset = m.group('charset') if not charset: charset = 'UTF8' host = '' driver_args.update(dict(host=host, database=pathdb, user=credential_decoder(user), password=credential_decoder(password), charset=charset)) #def connect(driver_args=driver_args): # return kinterbasdb.connect(**driver_args) if adapter_args.has_key('driver_name'): if adapter_args['driver_name'] == 'kinterbasdb': self.driver = kinterbasdb elif adapter_args['driver_name'] == 'firebirdsql': self.driver = firebirdsql else: self.driver = kinterbasdb def connect(driver_args=driver_args): return self.driver.connect(**driver_args) self.pool_connection(connect) self.cursor = self.connection.cursor() class InformixAdapter(BaseAdapter): driver = globals().get('informixdb',None) types = { 'boolean': 'CHAR(1)', 'string': 'VARCHAR(%(length)s)', 'text': 'BLOB SUB_TYPE 1', 'password': 'VARCHAR(%(length)s)', 'blob': 'BLOB SUB_TYPE 0', 'upload': 'VARCHAR(%(length)s)', 'integer': 'INTEGER', 'double': 'FLOAT', 'decimal': 'NUMERIC(%(precision)s,%(scale)s)', 'date': 'DATE', 'time': 'CHAR(8)', 'datetime': 'DATETIME', 'id': 'SERIAL', 'reference': 'INTEGER REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference FK': 'REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s CONSTRAINT FK_%(table_name)s_%(field_name)s', 'reference TFK': 'FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_table)s (%(foreign_key)s) ON DELETE %(on_delete_action)s CONSTRAINT TFK_%(table_name)s_%(field_name)s', 'list:integer': 'BLOB SUB_TYPE 1', 'list:string': 'BLOB SUB_TYPE 1', 'list:reference': 'BLOB SUB_TYPE 1', } def RANDOM(self): return 'Random()' def NOT_NULL(self,default,field_type): return 'DEFAULT %s NOT NULL' % self.represent(default,field_type) def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby): if limitby: (lmin, lmax) = limitby fetch_amt = lmax - lmin dbms_version = int(self.connection.dbms_version.split('.')[0]) if lmin and (dbms_version >= 10): # Requires Informix 10.0+ sql_s += ' SKIP %d' % (lmin, ) if fetch_amt and (dbms_version >= 9): # Requires Informix 9.0+ sql_s += ' FIRST %d' % (fetch_amt, ) return 'SELECT %s %s FROM %s%s%s;' % (sql_s, sql_f, sql_t, sql_w, sql_o) def represent_exceptions(self, obj, fieldtype): if fieldtype == 'date': if isinstance(obj, (datetime.date, datetime.datetime)): obj = obj.isoformat()[:10] else: obj = str(obj) return "to_date('%s','yyyy-mm-dd')" % obj elif fieldtype == 'datetime': if isinstance(obj, datetime.datetime): obj = obj.isoformat()[:19].replace('T',' ') elif isinstance(obj, datetime.date): obj = obj.isoformat()[:10]+' 00:00:00' else: obj = str(obj) return "to_date('%s','yyyy-mm-dd hh24:mi:ss')" % obj return None def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=lambda x:x, driver_args={}, adapter_args={}): self.db = db self.dbengine = "informix" self.uri = uri self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self.find_or_make_work_folder() uri = uri.split('://')[1] m = re.compile('^(?P<user>[^:@]+)(\:(?P<password>[^@]*))?@(?P<host>[^\:/]+)(\:(?P<port>[0-9]+))?/(?P<db>.+)$').match(uri) if not m: raise SyntaxError, \ "Invalid URI string in DAL: %s" % self.uri user = credential_decoder(m.group('user')) if not user: raise SyntaxError, 'User required' password = credential_decoder(m.group('password')) if not password: password = '' host = m.group('host') if not host: raise SyntaxError, 'Host name required' db = m.group('db') if not db: raise SyntaxError, 'Database name required' user = credential_decoder(user) password = credential_decoder(password) dsn = '%s@%s' % (db,host) driver_args.update(dict(user=user,password=password,autocommit=True)) def connect(dsn=dsn,driver_args=driver_args): return self.driver.connect(dsn,**driver_args) self.pool_connection(connect) self.cursor = self.connection.cursor() def execute(self,command): if command[-1:]==';': command = command[:-1] return self.log_execute(command) def lastrowid(self,table): return self.cursor.sqlerrd[1] def integrity_error_class(self): return informixdb.IntegrityError class DB2Adapter(BaseAdapter): driver = globals().get('pyodbc',None) types = { 'boolean': 'CHAR(1)', 'string': 'VARCHAR(%(length)s)', 'text': 'CLOB', 'password': 'VARCHAR(%(length)s)', 'blob': 'BLOB', 'upload': 'VARCHAR(%(length)s)', 'integer': 'INT', 'double': 'DOUBLE', 'decimal': 'NUMERIC(%(precision)s,%(scale)s)', 'date': 'DATE', 'time': 'TIME', 'datetime': 'TIMESTAMP', 'id': 'INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY NOT NULL', 'reference': 'INT, FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference FK': ', CONSTRAINT FK_%(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference TFK': ' CONSTRAINT FK_%(foreign_table)s_PK FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_table)s (%(foreign_key)s) ON DELETE %(on_delete_action)s', 'list:integer': 'CLOB', 'list:string': 'CLOB', 'list:reference': 'CLOB', } def LEFT_JOIN(self): return 'LEFT OUTER JOIN' def RANDOM(self): return 'RAND()' def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby): if limitby: (lmin, lmax) = limitby sql_o += ' FETCH FIRST %i ROWS ONLY' % lmax return 'SELECT %s %s FROM %s%s%s;' % (sql_s, sql_f, sql_t, sql_w, sql_o) def represent_exceptions(self, obj, fieldtype): if fieldtype == 'blob': obj = base64.b64encode(str(obj)) return "BLOB('%s')" % obj elif fieldtype == 'datetime': if isinstance(obj, datetime.datetime): obj = obj.isoformat()[:19].replace('T','-').replace(':','.') elif isinstance(obj, datetime.date): obj = obj.isoformat()[:10]+'-00.00.00' return "'%s'" % obj return None def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=lambda x:x, driver_args={}, adapter_args={}): self.db = db self.dbengine = "db2" self.uri = uri self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self.find_or_make_work_folder() cnxn = uri.split('://', 1)[1] def connect(cnxn=cnxn,driver_args=driver_args): return self.driver.connect(cnxn,**driver_args) self.pool_connection(connect) self.cursor = self.connection.cursor() def execute(self,command): if command[-1:]==';': command = command[:-1] return self.log_execute(command) def lastrowid(self,table): self.execute('SELECT DISTINCT IDENTITY_VAL_LOCAL() FROM %s;' % table) return int(self.cursor.fetchone()[0]) def rowslice(self,rows,minimum=0,maximum=None): if maximum is None: return rows[minimum:] return rows[minimum:maximum] class TeradataAdapter(DB2Adapter): driver = globals().get('pyodbc',None) types = { 'boolean': 'CHAR(1)', 'string': 'VARCHAR(%(length)s)', 'text': 'CLOB', 'password': 'VARCHAR(%(length)s)', 'blob': 'BLOB', 'upload': 'VARCHAR(%(length)s)', 'integer': 'INT', 'double': 'DOUBLE', 'decimal': 'NUMERIC(%(precision)s,%(scale)s)', 'date': 'DATE', 'time': 'TIME', 'datetime': 'TIMESTAMP', 'id': 'INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY NOT NULL', 'reference': 'INT, FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference FK': ', CONSTRAINT FK_%(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference TFK': ' CONSTRAINT FK_%(foreign_table)s_PK FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_table)s (%(foreign_key)s) ON DELETE %(on_delete_action)s', 'list:integer': 'CLOB', 'list:string': 'CLOB', 'list:reference': 'CLOB', } def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=lambda x:x, driver_args={}, adapter_args={}): self.db = db self.dbengine = "teradata" self.uri = uri self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self.find_or_make_work_folder() cnxn = uri.split('://', 1)[1] def connect(cnxn=cnxn,driver_args=driver_args): return self.driver.connect(cnxn,**driver_args) self.pool_connection(connect) self.cursor = self.connection.cursor() INGRES_SEQNAME='ii***lineitemsequence' # NOTE invalid database object name # (ANSI-SQL wants this form of name # to be a delimited identifier) class IngresAdapter(BaseAdapter): driver = globals().get('ingresdbi',None) types = { 'boolean': 'CHAR(1)', 'string': 'VARCHAR(%(length)s)', 'text': 'CLOB', 'password': 'VARCHAR(%(length)s)', ## Not sure what this contains utf8 or nvarchar. Or even bytes? 'blob': 'BLOB', 'upload': 'VARCHAR(%(length)s)', ## FIXME utf8 or nvarchar... or blob? what is this type? 'integer': 'INTEGER4', # or int8... 'double': 'FLOAT8', 'decimal': 'NUMERIC(%(precision)s,%(scale)s)', 'date': 'ANSIDATE', 'time': 'TIME WITHOUT TIME ZONE', 'datetime': 'TIMESTAMP WITHOUT TIME ZONE', 'id': 'integer4 not null unique with default next value for %s' % INGRES_SEQNAME, 'reference': 'integer4, FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference FK': ', CONSTRAINT FK_%(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference TFK': ' CONSTRAINT FK_%(foreign_table)s_PK FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_table)s (%(foreign_key)s) ON DELETE %(on_delete_action)s', ## FIXME TODO 'list:integer': 'CLOB', 'list:string': 'CLOB', 'list:reference': 'CLOB', } def LEFT_JOIN(self): return 'LEFT OUTER JOIN' def RANDOM(self): return 'RANDOM()' def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby): if limitby: (lmin, lmax) = limitby fetch_amt = lmax - lmin if fetch_amt: sql_s += ' FIRST %d ' % (fetch_amt, ) if lmin: # Requires Ingres 9.2+ sql_o += ' OFFSET %d' % (lmin, ) return 'SELECT %s %s FROM %s%s%s;' % (sql_s, sql_f, sql_t, sql_w, sql_o) def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=lambda x:x, driver_args={}, adapter_args={}): self.db = db self.dbengine = "ingres" self.uri = uri self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self.find_or_make_work_folder() connstr = self._uri.split(':', 1)[1] # Simple URI processing connstr = connstr.lstrip() while connstr.startswith('/'): connstr = connstr[1:] database_name=connstr # Assume only (local) dbname is passed in vnode = '(local)' servertype = 'ingres' trace = (0, None) # No tracing driver_args.update(dict(database=database_name, vnode=vnode, servertype=servertype, trace=trace)) def connect(driver_args=driver_args): return self.driver.connect(**driver_args) self.pool_connection(connect) self.cursor = self.connection.cursor() def create_sequence_and_triggers(self, query, table, **args): # post create table auto inc code (if needed) # modify table to btree for performance.... # Older Ingres releases could use rule/trigger like Oracle above. if hasattr(table,'_primarykey'): modify_tbl_sql = 'modify %s to btree unique on %s' % \ (table._tablename, ', '.join(["'%s'" % x for x in table.primarykey])) self.execute(modify_tbl_sql) else: tmp_seqname='%s_iisq' % table._tablename query=query.replace(INGRES_SEQNAME, tmp_seqname) self.execute('create sequence %s' % tmp_seqname) self.execute(query) self.execute('modify %s to btree unique on %s' % (table._tablename, 'id')) def lastrowid(self,table): tmp_seqname='%s_iisq' % table self.execute('select current value for %s' % tmp_seqname) return int(self.cursor.fetchone()[0]) # don't really need int type cast here... def integrity_error_class(self): return ingresdbi.IntegrityError class IngresUnicodeAdapter(IngresAdapter): types = { 'boolean': 'CHAR(1)', 'string': 'NVARCHAR(%(length)s)', 'text': 'NCLOB', 'password': 'NVARCHAR(%(length)s)', ## Not sure what this contains utf8 or nvarchar. Or even bytes? 'blob': 'BLOB', 'upload': 'VARCHAR(%(length)s)', ## FIXME utf8 or nvarchar... or blob? what is this type? 'integer': 'INTEGER4', # or int8... 'double': 'FLOAT8', 'decimal': 'NUMERIC(%(precision)s,%(scale)s)', 'date': 'ANSIDATE', 'time': 'TIME WITHOUT TIME ZONE', 'datetime': 'TIMESTAMP WITHOUT TIME ZONE', 'id': 'integer4 not null unique with default next value for %s'% INGRES_SEQNAME, 'reference': 'integer4, FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference FK': ', CONSTRAINT FK_%(constraint_name)s FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'reference TFK': ' CONSTRAINT FK_%(foreign_table)s_PK FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_table)s (%(foreign_key)s) ON DELETE %(on_delete_action)s', ## FIXME TODO 'list:integer': 'NCLOB', 'list:string': 'NCLOB', 'list:reference': 'NCLOB', } class SAPDBAdapter(BaseAdapter): driver = globals().get('sapdb',None) support_distributed_transaction = False types = { 'boolean': 'CHAR(1)', 'string': 'VARCHAR(%(length)s)', 'text': 'LONG', 'password': 'VARCHAR(%(length)s)', 'blob': 'LONG', 'upload': 'VARCHAR(%(length)s)', 'integer': 'INT', 'double': 'FLOAT', 'decimal': 'FIXED(%(precision)s,%(scale)s)', 'date': 'DATE', 'time': 'TIME', 'datetime': 'TIMESTAMP', 'id': 'INT PRIMARY KEY', 'reference': 'INT, FOREIGN KEY (%(field_name)s) REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s', 'list:integer': 'LONG', 'list:string': 'LONG', 'list:reference': 'LONG', } def sequence_name(self,table): return '%s_id_Seq' % table def select_limitby(self, sql_s, sql_f, sql_t, sql_w, sql_o, limitby): if limitby: (lmin, lmax) = limitby if len(sql_w) > 1: sql_w_row = sql_w + ' AND w_row > %i' % lmin else: sql_w_row = 'WHERE w_row > %i' % lmin return '%s %s FROM (SELECT w_tmp.*, ROWNO w_row FROM (SELECT %s FROM %s%s%s) w_tmp WHERE ROWNO=%i) %s %s %s;' % (sql_s, sql_f, sql_f, sql_t, sql_w, sql_o, lmax, sql_t, sql_w_row, sql_o) return 'SELECT %s %s FROM %s%s%s;' % (sql_s, sql_f, sql_t, sql_w, sql_o) def create_sequence_and_triggers(self, query, table, **args): # following lines should only be executed if table._sequence_name does not exist self.execute('CREATE SEQUENCE %s;' % table._sequence_name) self.execute("ALTER TABLE %s ALTER COLUMN %s SET DEFAULT NEXTVAL('%s');" \ % (table._tablename, table._id.name, table._sequence_name)) self.execute(query) def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=lambda x:x, driver_args={}, adapter_args={}): self.db = db self.dbengine = "sapdb" self.uri = uri self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self.find_or_make_work_folder() uri = uri.split('://')[1] m = re.compile('^(?P<user>[^:@]+)(\:(?P<password>[^@]*))?@(?P<host>[^\:@/]+)(\:(?P<port>[0-9]+))?/(?P<db>[^\?]+)(\?sslmode=(?P<sslmode>.+))?$').match(uri) if not m: raise SyntaxError, "Invalid URI string in DAL" user = credential_decoder(m.group('user')) if not user: raise SyntaxError, 'User required' password = credential_decoder(m.group('password')) if not password: password = '' host = m.group('host') if not host: raise SyntaxError, 'Host name required' db = m.group('db') if not db: raise SyntaxError, 'Database name required' def connect(user=user,password=password,database=db, host=host,driver_args=driver_args): return self.driver.Connection(user,password,database, host,**driver_args) self.pool_connection(connect) # self.connection.set_client_encoding('UTF8') self.cursor = self.connection.cursor() def lastrowid(self,table): self.execute("select %s.NEXTVAL from dual" % table._sequence_name) return int(self.cursor.fetchone()[0]) class CubridAdapter(MySQLAdapter): driver = globals().get('cubriddb',None) def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=lambda x:x, driver_args={}, adapter_args={}): self.db = db self.dbengine = "cubrid" self.uri = uri self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self.find_or_make_work_folder() uri = uri.split('://')[1] m = re.compile('^(?P<user>[^:@]+)(\:(?P<password>[^@]*))?@(?P<host>[^\:/]+)(\:(?P<port>[0-9]+))?/(?P<db>[^?]+)(\?set_encoding=(?P<charset>\w+))?$').match(uri) if not m: raise SyntaxError, \ "Invalid URI string in DAL: %s" % self.uri user = credential_decoder(m.group('user')) if not user: raise SyntaxError, 'User required' password = credential_decoder(m.group('password')) if not password: password = '' host = m.group('host') if not host: raise SyntaxError, 'Host name required' db = m.group('db') if not db: raise SyntaxError, 'Database name required' port = int(m.group('port') or '30000') charset = m.group('charset') or 'utf8' user=credential_decoder(user), passwd=credential_decoder(password), def connect(host,port,db,user,passwd,driver_args=driver_args): return self.driver.connect(host,port,db,user,passwd,**driver_args) self.pool_connection(connect) self.cursor = self.connection.cursor() self.execute('SET FOREIGN_KEY_CHECKS=1;') self.execute("SET sql_mode='NO_BACKSLASH_ESCAPES';") ######## GAE MySQL ########## class DatabaseStoredFile: web2py_filesystem = False def __init__(self,db,filename,mode): if db._adapter.dbengine != 'mysql': raise RuntimeError, "only MySQL can store metadata .table files in database for now" self.db = db self.filename = filename self.mode = mode if not self.web2py_filesystem: self.db.executesql("CREATE TABLE IF NOT EXISTS web2py_filesystem (path VARCHAR(512), content LONGTEXT, PRIMARY KEY(path) ) ENGINE=InnoDB;") DatabaseStoredFile.web2py_filesystem = True self.p=0 self.data = '' if mode in ('r','rw','a'): query = "SELECT content FROM web2py_filesystem WHERE path='%s'" % filename rows = self.db.executesql(query) if rows: self.data = rows[0][0] elif os.path.exists(filename): datafile = open(filename, 'r') try: self.data = datafile.read() finally: datafile.close() elif mode in ('r','rw'): raise RuntimeError, "File %s does not exist" % filename def read(self, bytes): data = self.data[self.p:self.p+bytes] self.p += len(data) return data def readline(self): i = self.data.find('\n',self.p)+1 if i>0: data, self.p = self.data[self.p:i], i else: data, self.p = self.data[self.p:], len(self.data) return data def write(self,data): self.data += data def close(self): self.db.executesql("DELETE FROM web2py_filesystem WHERE path='%s'" % self.filename) query = "INSERT INTO web2py_filesystem(path,content) VALUES ('%s','%s')" % \ (self.filename, self.data.replace("'","''")) self.db.executesql(query) self.db.commit() @staticmethod def exists(db,filename): if os.path.exists(filename): return True query = "SELECT path FROM web2py_filesystem WHERE path='%s'" % filename if db.executesql(query): return True return False class UseDatabaseStoredFile: def file_exists(self, filename): return DatabaseStoredFile.exists(self.db,filename) def file_open(self, filename, mode='rb', lock=True): return DatabaseStoredFile(self.db,filename,mode) def file_close(self, fileobj, unlock=True): fileobj.close() def file_delete(self,filename): query = "DELETE FROM web2py_filesystem WHERE path='%s'" % filename self.db.executesql(query) self.db.commit() class GoogleSQLAdapter(UseDatabaseStoredFile,MySQLAdapter): def __init__(self, db, uri='google:sql://realm:domain/database', pool_size=0, folder=None, db_codec='UTF-8', check_reserved=None, migrate=True, fake_migrate=False, credential_decoder = lambda x:x, driver_args={}, adapter_args={}): self.db = db self.dbengine = "mysql" self.uri = uri self.pool_size = pool_size self.folder = folder self.db_codec = db_codec self.folder = folder or '$HOME/'+thread.folder.split('/applications/',1)[1] m = re.compile('^(?P<instance>.*)/(?P<db>.*)$').match(self.uri[len('google:sql://'):]) if not m: raise SyntaxError, "Invalid URI string in SQLDB: %s" % self._uri instance = credential_decoder(m.group('instance')) db = credential_decoder(m.group('db')) driver_args['instance'] = instance if not migrate: driver_args['database'] = db def connect(driver_args=driver_args): return rdbms.connect(**driver_args) self.pool_connection(connect) self.cursor = self.connection.cursor() if migrate: # self.execute('DROP DATABASE %s' % db) self.execute('CREATE DATABASE IF NOT EXISTS %s' % db) self.execute('USE %s' % db) self.execute("SET FOREIGN_KEY_CHECKS=1;") self.execute("SET sql_mode='NO_BACKSLASH_ESCAPES';") class NoSQLAdapter(BaseAdapter): @staticmethod def to_unicode(obj): if isinstance(obj, str): return obj.decode('utf8') elif not isinstance(obj, unicode): return unicode(obj) return obj def represent(self, obj, fieldtype): if isinstance(obj,CALLABLETYPES): obj = obj() if isinstance(fieldtype, SQLCustomType): return fieldtype.encoder(obj) if isinstance(obj, (Expression, Field)): raise SyntaxError, "non supported on GAE" if self.dbengine=='google:datastore' in globals(): if isinstance(fieldtype, gae.Property): return obj if fieldtype.startswith('list:'): if not obj: obj = [] if not isinstance(obj, (list, tuple)): obj = [obj] if obj == '' and not fieldtype[:2] in ['st','te','pa','up']: return None if obj != None: if isinstance(obj, list) and not fieldtype.startswith('list'): obj = [self.represent(o, fieldtype) for o in obj] elif fieldtype in ('integer','id'): obj = long(obj) elif fieldtype == 'double': obj = float(obj) elif fieldtype.startswith('reference'): if isinstance(obj, (Row, Reference)): obj = obj['id'] obj = long(obj) elif fieldtype == 'boolean': if obj and not str(obj)[0].upper() == 'F': obj = True else: obj = False elif fieldtype == 'date': if not isinstance(obj, datetime.date): (y, m, d) = map(int,str(obj).strip().split('-')) obj = datetime.date(y, m, d) elif isinstance(obj,datetime.datetime): (y, m, d) = (obj.year, obj.month, obj.day) obj = datetime.date(y, m, d) elif fieldtype == 'time': if not isinstance(obj, datetime.time): time_items = map(int,str(obj).strip().split(':')[:3]) if len(time_items) == 3: (h, mi, s) = time_items else: (h, mi, s) = time_items + [0] obj = datetime.time(h, mi, s) elif fieldtype == 'datetime': if not isinstance(obj, datetime.datetime): (y, m, d) = map(int,str(obj)[:10].strip().split('-')) time_items = map(int,str(obj)[11:].strip().split(':')[:3]) while len(time_items)<3: time_items.append(0) (h, mi, s) = time_items obj = datetime.datetime(y, m, d, h, mi, s) elif fieldtype == 'blob': pass elif fieldtype.startswith('list:string'): return map(self.to_unicode,obj) elif fieldtype.startswith('list:'): return map(int,obj) else: obj = self.to_unicode(obj) return obj def _insert(self,table,fields): return 'insert %s in %s' % (fields, table) def _count(self,query,distinct=None): return 'count %s' % repr(query) def _select(self,query,fields,attributes): return 'select %s where %s' % (repr(fields), repr(query)) def _delete(self,tablename, query): return 'delete %s where %s' % (repr(tablename),repr(query)) def _update(self,tablename,query,fields): return 'update %s (%s) where %s' % (repr(tablename), repr(fields),repr(query)) def commit(self): """ remember: no transactions on many NoSQL """ pass def rollback(self): """ remember: no transactions on many NoSQL """ pass def close(self): """ remember: no transactions on many NoSQL """ pass # these functions should never be called! def OR(self,first,second): raise SyntaxError, "Not supported" def AND(self,first,second): raise SyntaxError, "Not supported" def AS(self,first,second): raise SyntaxError, "Not supported" def ON(self,first,second): raise SyntaxError, "Not supported" def STARTSWITH(self,first,second=None): raise SyntaxError, "Not supported" def ENDSWITH(self,first,second=None): raise SyntaxError, "Not supported" def ADD(self,first,second): raise SyntaxError, "Not supported" def SUB(self,first,second): raise SyntaxError, "Not supported" def MUL(self,first,second): raise SyntaxError, "Not supported" def DIV(self,first,second): raise SyntaxError, "Not supported" def LOWER(self,first): raise SyntaxError, "Not supported" def UPPER(self,first): raise SyntaxError, "Not supported" def EXTRACT(self,first,what): raise SyntaxError, "Not supported" def AGGREGATE(self,first,what): raise SyntaxError, "Not supported" def LEFT_JOIN(self): raise SyntaxError, "Not supported" def RANDOM(self): raise SyntaxError, "Not supported" def SUBSTRING(self,field,parameters): raise SyntaxError, "Not supported" def PRIMARY_KEY(self,key): raise SyntaxError, "Not supported" def LIKE(self,first,second): raise SyntaxError, "Not supported" def drop(self,table,mode): raise SyntaxError, "Not supported" def alias(self,table,alias): raise SyntaxError, "Not supported" def migrate_table(self,*a,**b): raise SyntaxError, "Not supported" def distributed_transaction_begin(self,key): raise SyntaxError, "Not supported" def prepare(self,key): raise SyntaxError, "Not supported" def commit_prepared(self,key): raise SyntaxError, "Not supported" def rollback_prepared(self,key): raise SyntaxError, "Not supported" def concat_add(self,table): raise SyntaxError, "Not supported" def constraint_name(self, table, fieldname): raise SyntaxError, "Not supported" def create_sequence_and_triggers(self, query, table, **args): pass def log_execute(self,*a,**b): raise SyntaxError, "Not supported" def execute(self,*a,**b): raise SyntaxError, "Not supported" def represent_exceptions(self, obj, fieldtype): raise SyntaxError, "Not supported" def lastrowid(self,table): raise SyntaxError, "Not supported" def integrity_error_class(self): raise SyntaxError, "Not supported" def rowslice(self,rows,minimum=0,maximum=None): raise SyntaxError, "Not supported" class GAEF(object): def __init__(self,name,op,value,apply): self.name=name=='id' and '__key__' or name self.op=op self.value=value self.apply=apply def __repr__(self): return '(%s %s %s:%s)' % (self.name, self.op, repr(self.value), type(self.value)) class GoogleDatastoreAdapter(NoSQLAdapter): uploads_in_blob = True types = {} def file_exists(self, filename): pass def file_open(self, filename, mode='rb', lock=True): pass def file_close(self, fileobj, unlock=True): pass def __init__(self,db,uri,pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=lambda x:x, driver_args={}, adapter_args={}): self.types.update({ 'boolean': gae.BooleanProperty, 'string': (lambda: gae.StringProperty(multiline=True)), 'text': gae.TextProperty, 'password': gae.StringProperty, 'blob': gae.BlobProperty, 'upload': gae.StringProperty, 'integer': gae.IntegerProperty, 'double': gae.FloatProperty, 'decimal': GAEDecimalProperty, 'date': gae.DateProperty, 'time': gae.TimeProperty, 'datetime': gae.DateTimeProperty, 'id': None, 'reference': gae.IntegerProperty, 'list:string': (lambda: gae.StringListProperty(default=None)), 'list:integer': (lambda: gae.ListProperty(int,default=None)), 'list:reference': (lambda: gae.ListProperty(int,default=None)), }) self.db = db self.uri = uri self.dbengine = 'google:datastore' self.folder = folder db['_lastsql'] = '' self.db_codec = 'UTF-8' self.pool_size = 0 match = re.compile('.*://(?P<namespace>.+)').match(uri) if match: namespace_manager.set_namespace(match.group('namespace')) def create_table(self,table,migrate=True,fake_migrate=False, polymodel=None): myfields = {} for k in table.fields: if isinstance(polymodel,Table) and k in polymodel.fields(): continue field = table[k] attr = {} if isinstance(field.type, SQLCustomType): ftype = self.types[field.type.native or field.type.type](**attr) elif isinstance(field.type, gae.Property): ftype = field.type elif field.type.startswith('id'): continue elif field.type.startswith('decimal'): precision, scale = field.type[7:].strip('()').split(',') precision = int(precision) scale = int(scale) ftype = GAEDecimalProperty(precision, scale, **attr) elif field.type.startswith('reference'): if field.notnull: attr = dict(required=True) referenced = field.type[10:].strip() ftype = self.types[field.type[:9]](table._db[referenced]) elif field.type.startswith('list:reference'): if field.notnull: attr = dict(required=True) referenced = field.type[15:].strip() ftype = self.types[field.type[:14]](**attr) elif field.type.startswith('list:'): ftype = self.types[field.type](**attr) elif not field.type in self.types\ or not self.types[field.type]: raise SyntaxError, 'Field: unknown field type: %s' % field.type else: ftype = self.types[field.type](**attr) myfields[field.name] = ftype if not polymodel: table._tableobj = classobj(table._tablename, (gae.Model, ), myfields) elif polymodel==True: table._tableobj = classobj(table._tablename, (PolyModel, ), myfields) elif isinstance(polymodel,Table): table._tableobj = classobj(table._tablename, (polymodel._tableobj, ), myfields) else: raise SyntaxError, "polymodel must be None, True, a table or a tablename" return None def expand(self,expression,field_type=None): if isinstance(expression,Field): if expression.type in ('text','blob'): raise SyntaxError, 'AppEngine does not index by: %s' % expression.type return expression.name elif isinstance(expression, (Expression, Query)): if not expression.second is None: return expression.op(expression.first, expression.second) elif not expression.first is None: return expression.op(expression.first) else: return expression.op() elif field_type: return self.represent(expression,field_type) elif isinstance(expression,(list,tuple)): return ','.join([self.represent(item,field_type) for item in expression]) else: return str(expression) ### TODO from gql.py Expression def AND(self,first,second): a = self.expand(first) b = self.expand(second) if b[0].name=='__key__' and a[0].name!='__key__': return b+a return a+b def EQ(self,first,second=None): if isinstance(second, Key): return [GAEF(first.name,'=',second,lambda a,b:a==b)] return [GAEF(first.name,'=',self.represent(second,first.type),lambda a,b:a==b)] def NE(self,first,second=None): if first.type != 'id': return [GAEF(first.name,'!=',self.represent(second,first.type),lambda a,b:a!=b)] else: second = Key.from_path(first._tablename, long(second)) return [GAEF(first.name,'!=',second,lambda a,b:a!=b)] def LT(self,first,second=None): if first.type != 'id': return [GAEF(first.name,'<',self.represent(second,first.type),lambda a,b:a<b)] else: second = Key.from_path(first._tablename, long(second)) return [GAEF(first.name,'<',second,lambda a,b:a<b)] def LE(self,first,second=None): if first.type != 'id': return [GAEF(first.name,'<=',self.represent(second,first.type),lambda a,b:a<=b)] else: second = Key.from_path(first._tablename, long(second)) return [GAEF(first.name,'<=',second,lambda a,b:a<=b)] def GT(self,first,second=None): if first.type != 'id' or second==0 or second == '0': return [GAEF(first.name,'>',self.represent(second,first.type),lambda a,b:a>b)] else: second = Key.from_path(first._tablename, long(second)) return [GAEF(first.name,'>',second,lambda a,b:a>b)] def GE(self,first,second=None): if first.type != 'id': return [GAEF(first.name,'>=',self.represent(second,first.type),lambda a,b:a>=b)] else: second = Key.from_path(first._tablename, long(second)) return [GAEF(first.name,'>=',second,lambda a,b:a>=b)] def INVERT(self,first): return '-%s' % first.name def COMMA(self,first,second): return '%s, %s' % (self.expand(first),self.expand(second)) def BELONGS(self,first,second=None): if not isinstance(second,(list, tuple)): raise SyntaxError, "Not supported" if first.type != 'id': return [GAEF(first.name,'in',self.represent(second,first.type),lambda a,b:a in b)] else: second = [Key.from_path(first._tablename, i) for i in second] return [GAEF(first.name,'in',second,lambda a,b:a in b)] def CONTAINS(self,first,second): if not first.type.startswith('list:'): raise SyntaxError, "Not supported" return [GAEF(first.name,'=',self.expand(second,first.type[5:]),lambda a,b:a in b)] def NOT(self,first): nops = { self.EQ: self.NE, self.NE: self.EQ, self.LT: self.GE, self.GT: self.LE, self.LE: self.GT, self.GE: self.LT} if not isinstance(first,Query): raise SyntaxError, "Not suported" nop = nops.get(first.op,None) if not nop: raise SyntaxError, "Not suported %s" % first.op.__name__ first.op = nop return self.expand(first) def truncate(self,table,mode): self.db(table._id > 0).delete() def select_raw(self,query,fields=[],attributes={}): new_fields = [] for item in fields: if isinstance(item,SQLALL): new_fields += item.table else: new_fields.append(item) fields = new_fields if query: tablename = self.get_table(query) elif fields: tablename = fields[0].tablename query = fields[0].table._id>0 else: raise SyntaxError, "Unable to determine a tablename" query = self.filter_tenant(query,[tablename]) tableobj = self.db[tablename]._tableobj items = tableobj.all() filters = self.expand(query) for filter in filters: if filter.name=='__key__' and filter.op=='>' and filter.value==0: continue elif filter.name=='__key__' and filter.op=='=': if filter.value==0: items = [] elif isinstance(filter.value, Key): item = tableobj.get(filter.value) items = (item and [item]) or [] else: item = tableobj.get_by_id(filter.value) items = (item and [item]) or [] elif isinstance(items,list): # i.e. there is a single record! items = [i for i in items if filter.apply(getattr(item,filter.name), filter.value)] else: if filter.name=='__key__': items.order('__key__') items = items.filter('%s %s' % (filter.name,filter.op),filter.value) if not isinstance(items,list): if attributes.get('left', None): raise SyntaxError, 'Set: no left join in appengine' if attributes.get('groupby', None): raise SyntaxError, 'Set: no groupby in appengine' orderby = attributes.get('orderby', False) if orderby: ### THIS REALLY NEEDS IMPROVEMENT !!! if isinstance(orderby, (list, tuple)): orderby = xorify(orderby) if isinstance(orderby,Expression): orderby = self.expand(orderby) orders = orderby.split(', ') for order in orders: order={'-id':'-__key__','id':'__key__'}.get(order,order) items = items.order(order) if attributes.get('limitby', None): (lmin, lmax) = attributes['limitby'] (limit, offset) = (lmax - lmin, lmin) items = items.fetch(limit, offset=offset) fields = self.db[tablename].fields return (items, tablename, fields) def select(self,query,fields,attributes): (items, tablename, fields) = self.select_raw(query,fields,attributes) # self.db['_lastsql'] = self._select(query,fields,attributes) rows = [ [t=='id' and int(item.key().id()) or getattr(item, t) for t in fields] for item in items] colnames = ['%s.%s' % (tablename, t) for t in fields] return self.parse(rows, colnames, False) def count(self,query,distinct=None): if distinct: raise RuntimeError, "COUNT DISTINCT not supported" (items, tablename, fields) = self.select_raw(query) # self.db['_lastsql'] = self._count(query) try: return len(items) except TypeError: return items.count(limit=None) def delete(self,tablename, query): """ This function was changed on 2010-05-04 because according to http://code.google.com/p/googleappengine/issues/detail?id=3119 GAE no longer support deleting more than 1000 records. """ # self.db['_lastsql'] = self._delete(tablename,query) (items, tablename, fields) = self.select_raw(query) # items can be one item or a query if not isinstance(items,list): counter = items.count(limit=None) leftitems = items.fetch(1000) while len(leftitems): gae.delete(leftitems) leftitems = items.fetch(1000) else: counter = len(items) gae.delete(items) return counter def update(self,tablename,query,update_fields): # self.db['_lastsql'] = self._update(tablename,query,update_fields) (items, tablename, fields) = self.select_raw(query) counter = 0 for item in items: for field, value in update_fields: setattr(item, field.name, self.represent(value,field.type)) item.put() counter += 1 logger.info(str(counter)) return counter def insert(self,table,fields): dfields=dict((f.name,self.represent(v,f.type)) for f,v in fields) # table._db['_lastsql'] = self._insert(table,fields) tmp = table._tableobj(**dfields) tmp.put() rid = Reference(tmp.key().id()) (rid._table, rid._record) = (table, None) return rid def bulk_insert(self,table,items): parsed_items = [] for item in items: dfields=dict((f.name,self.represent(v,f.type)) for f,v in item) parsed_items.append(table._tableobj(**dfields)) gae.put(parsed_items) return True def uuid2int(uuidv): return uuid.UUID(uuidv).int def int2uuid(n): return str(uuid.UUID(int=n)) class CouchDBAdapter(NoSQLAdapter): uploads_in_blob = True types = { 'boolean': bool, 'string': str, 'text': str, 'password': str, 'blob': str, 'upload': str, 'integer': long, 'double': float, 'date': datetime.date, 'time': datetime.time, 'datetime': datetime.datetime, 'id': long, 'reference': long, 'list:string': list, 'list:integer': list, 'list:reference': list, } def file_exists(self, filename): pass def file_open(self, filename, mode='rb', lock=True): pass def file_close(self, fileobj, unlock=True): pass def expand(self,expression,field_type=None): if isinstance(expression,Field): if expression.type=='id': return "%s._id" % expression.tablename return BaseAdapter.expand(self,expression,field_type) def AND(self,first,second): return '(%s && %s)' % (self.expand(first),self.expand(second)) def OR(self,first,second): return '(%s || %s)' % (self.expand(first),self.expand(second)) def EQ(self,first,second): if second is None: return '(%s == null)' % self.expand(first) return '(%s == %s)' % (self.expand(first),self.expand(second,first.type)) def NE(self,first,second): if second is None: return '(%s != null)' % self.expand(first) return '(%s != %s)' % (self.expand(first),self.expand(second,first.type)) def COMMA(self,first,second): return '%s + %s' % (self.expand(first),self.expand(second)) def represent(self, obj, fieldtype): value = NoSQLAdapter.represent(self, obj, fieldtype) if fieldtype=='id': return repr(str(int(value))) return repr(not isinstance(value,unicode) and value or value.encode('utf8')) def __init__(self,db,uri='couchdb://127.0.0.1:5984', pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=lambda x:x, driver_args={}, adapter_args={}): self.db = db self.uri = uri self.dbengine = 'couchdb' self.folder = folder db['_lastsql'] = '' self.db_codec = 'UTF-8' self.pool_size = pool_size url='http://'+uri[10:] def connect(url=url,driver_args=driver_args): return couchdb.Server(url,**driver_args) self.pool_connection(connect) def create_table(self, table, migrate=True, fake_migrate=False, polymodel=None): if migrate: try: self.connection.create(table._tablename) except: pass def insert(self,table,fields): id = uuid2int(web2py_uuid()) ctable = self.connection[table._tablename] values = dict((k.name,NoSQLAdapter.represent(self,v,k.type)) for k,v in fields) values['_id'] = str(id) ctable.save(values) return id def _select(self,query,fields,attributes): if not isinstance(query,Query): raise SyntaxError, "Not Supported" for key in set(attributes.keys())-set(('orderby','groupby','limitby', 'required','cache','left', 'distinct','having')): raise SyntaxError, 'invalid select attribute: %s' % key new_fields=[] for item in fields: if isinstance(item,SQLALL): new_fields += item.table else: new_fields.append(item) def uid(fd): return fd=='id' and '_id' or fd def get(row,fd): return fd=='id' and int(row['_id']) or row.get(fd,None) fields = new_fields tablename = self.get_table(query) fieldnames = [f.name for f in (fields or self.db[tablename])] colnames = ['%s.%s' % (tablename,k) for k in fieldnames] fields = ','.join(['%s.%s' % (tablename,uid(f)) for f in fieldnames]) fn="function(%(t)s){if(%(query)s)emit(%(order)s,[%(fields)s]);}" %\ dict(t=tablename, query=self.expand(query), order='%s._id' % tablename, fields=fields) return fn, colnames def select(self,query,fields,attributes): if not isinstance(query,Query): raise SyntaxError, "Not Supported" fn, colnames = self._select(query,fields,attributes) tablename = colnames[0].split('.')[0] ctable = self.connection[tablename] rows = [cols['value'] for cols in ctable.query(fn)] return self.parse(rows, colnames, False) def delete(self,tablename,query): if not isinstance(query,Query): raise SyntaxError, "Not Supported" if query.first.type=='id' and query.op==self.EQ: id = query.second tablename = query.first.tablename assert(tablename == query.first.tablename) ctable = self.connection[tablename] try: del ctable[str(id)] return 1 except couchdb.http.ResourceNotFound: return 0 else: tablename = self.get_table(query) rows = self.select(query,[self.db[tablename]._id],{}) ctable = self.connection[tablename] for row in rows: del ctable[str(row.id)] return len(rows) def update(self,tablename,query,fields): if not isinstance(query,Query): raise SyntaxError, "Not Supported" if query.first.type=='id' and query.op==self.EQ: id = query.second tablename = query.first.tablename ctable = self.connection[tablename] try: doc = ctable[str(id)] for key,value in fields: doc[key.name] = NoSQLAdapter.represent(self,value,self.db[tablename][key.name].type) ctable.save(doc) return 1 except couchdb.http.ResourceNotFound: return 0 else: tablename = self.get_table(query) rows = self.select(query,[self.db[tablename]._id],{}) ctable = self.connection[tablename] table = self.db[tablename] for row in rows: doc = ctable[str(row.id)] for key,value in fields: doc[key.name] = NoSQLAdapter.represent(self,value,table[key.name].type) ctable.save(doc) return len(rows) def count(self,query,distinct=None): if distinct: raise RuntimeError, "COUNT DISTINCT not supported" if not isinstance(query,Query): raise SyntaxError, "Not Supported" tablename = self.get_table(query) rows = self.select(query,[self.db[tablename]._id],{}) return len(rows) def cleanup(text): """ validates that the given text is clean: only contains [0-9a-zA-Z_] """ if re.compile('[^0-9a-zA-Z_]').findall(text): raise SyntaxError, \ 'only [0-9a-zA-Z_] allowed in table and field names, received %s' \ % text return text class MongoDBAdapter(NoSQLAdapter): uploads_in_blob = True types = { 'boolean': bool, 'string': str, 'text': str, 'password': str, 'blob': str, 'upload': str, 'integer': long, 'double': float, 'date': datetime.date, 'time': datetime.time, 'datetime': datetime.datetime, 'id': long, 'reference': long, 'list:string': list, 'list:integer': list, 'list:reference': list, } def __init__(self,db,uri='mongodb://127.0.0.1:5984/db', pool_size=0,folder=None,db_codec ='UTF-8', credential_decoder=lambda x:x, driver_args={}, adapter_args={}): self.db = db self.uri = uri self.dbengine = 'mongodb' self.folder = folder db['_lastsql'] = '' self.db_codec = 'UTF-8' self.pool_size = pool_size m = re.compile('^(?P<host>[^\:/]+)(\:(?P<port>[0-9]+))?/(?P<db>.+)$').match(self._uri[10:]) if not m: raise SyntaxError, "Invalid URI string in DAL: %s" % self._uri host = m.group('host') if not host: raise SyntaxError, 'mongodb: host name required' dbname = m.group('db') if not dbname: raise SyntaxError, 'mongodb: db name required' port = m.group('port') or 27017 driver_args.update(dict(host=host,port=port)) def connect(dbname=dbname,driver_args=driver_args): return pymongo.Connection(**driver_args)[dbname] self.pool_connection(connect) def insert(self,table,fields): ctable = self.connection[table._tablename] values = dict((k,self.represent(v,table[k].type)) for k,v in fields) ctable.insert(values) return uuid2int(id) def count(self,query): raise RuntimeError, "Not implemented" def select(self,query,fields,attributes): raise RuntimeError, "Not implemented" def delete(self,tablename, query): raise RuntimeError, "Not implemented" def update(self,tablename,query,fields): raise RuntimeError, "Not implemented" ######################################################################## # end of adapters ######################################################################## ADAPTERS = { 'sqlite': SQLiteAdapter, 'sqlite:memory': SQLiteAdapter, 'mysql': MySQLAdapter, 'postgres': PostgreSQLAdapter, 'oracle': OracleAdapter, 'mssql': MSSQLAdapter, 'mssql2': MSSQL2Adapter, 'db2': DB2Adapter, 'teradata': TeradataAdapter, 'informix': InformixAdapter, 'firebird': FireBirdAdapter, 'firebird_embedded': FireBirdAdapter, 'ingres': IngresAdapter, 'ingresu': IngresUnicodeAdapter, 'sapdb': SAPDBAdapter, 'cubrid': CubridAdapter, 'jdbc:sqlite': JDBCSQLiteAdapter, 'jdbc:sqlite:memory': JDBCSQLiteAdapter, 'jdbc:postgres': JDBCPostgreSQLAdapter, 'gae': GoogleDatastoreAdapter, # discouraged, for backward compatibility 'google:datastore': GoogleDatastoreAdapter, 'google:sql': GoogleSQLAdapter, 'couchdb': CouchDBAdapter, 'mongodb': MongoDBAdapter, } def sqlhtml_validators(field): """ Field type validation, using web2py's validators mechanism. makes sure the content of a field is in line with the declared fieldtype """ if not have_validators: return [] field_type, field_length = field.type, field.length if isinstance(field_type, SQLCustomType): if hasattr(field_type, 'validator'): return field_type.validator else: field_type = field_type.type elif not isinstance(field_type,str): return [] requires=[] def ff(r,id): row=r(id) if not row: return id elif hasattr(r, '_format') and isinstance(r._format,str): return r._format % row elif hasattr(r, '_format') and callable(r._format): return r._format(row) else: return id if field_type == 'string': requires.append(validators.IS_LENGTH(field_length)) elif field_type == 'text': requires.append(validators.IS_LENGTH(field_length)) elif field_type == 'password': requires.append(validators.IS_LENGTH(field_length)) elif field_type == 'double': requires.append(validators.IS_FLOAT_IN_RANGE(-1e100, 1e100)) elif field_type == 'integer': requires.append(validators.IS_INT_IN_RANGE(-1e100, 1e100)) elif field_type.startswith('decimal'): requires.append(validators.IS_DECIMAL_IN_RANGE(-10**10, 10**10)) elif field_type == 'date': requires.append(validators.IS_DATE()) elif field_type == 'time': requires.append(validators.IS_TIME()) elif field_type == 'datetime': requires.append(validators.IS_DATETIME()) elif field.db and field_type.startswith('reference') and \ field_type.find('.') < 0 and \ field_type[10:] in field.db.tables: referenced = field.db[field_type[10:]] def repr_ref(id, r=referenced, f=ff): return f(r, id) field.represent = field.represent or repr_ref if hasattr(referenced, '_format') and referenced._format: requires = validators.IS_IN_DB(field.db,referenced._id, referenced._format) if field.unique: requires._and = validators.IS_NOT_IN_DB(field.db,field) if field.tablename == field_type[10:]: return validators.IS_EMPTY_OR(requires) return requires elif field.db and field_type.startswith('list:reference') and \ field_type.find('.') < 0 and \ field_type[15:] in field.db.tables: referenced = field.db[field_type[15:]] def list_ref_repr(ids, r=referenced, f=ff): if not ids: return None refs = r._db(r._id.belongs(ids)).select(r._id) return (refs and ', '.join(str(f(r,ref.id)) for ref in refs) or '') field.represent = field.represent or list_ref_repr if hasattr(referenced, '_format') and referenced._format: requires = validators.IS_IN_DB(field.db,referenced._id, referenced._format,multiple=True) else: requires = validators.IS_IN_DB(field.db,referenced._id, multiple=True) if field.unique: requires._and = validators.IS_NOT_IN_DB(field.db,field) return requires elif field_type.startswith('list:'): def repr_list(values): return', '.join(str(v) for v in (values or [])) field.represent = field.represent or repr_list if field.unique: requires.insert(0,validators.IS_NOT_IN_DB(field.db,field)) sff = ['in', 'do', 'da', 'ti', 'de', 'bo'] if field.notnull and not field_type[:2] in sff: requires.insert(0, validators.IS_NOT_EMPTY()) elif not field.notnull and field_type[:2] in sff and requires: requires[-1] = validators.IS_EMPTY_OR(requires[-1]) return requires def bar_escape(item): return str(item).replace('|', '||') def bar_encode(items): return '|%s|' % '|'.join(bar_escape(item) for item in items if str(item).strip()) def bar_decode_integer(value): return [int(x) for x in value.split('|') if x.strip()] def bar_decode_string(value): return [x.replace('||', '|') for x in string_unpack.split(value[1:-1]) if x.strip()] class Row(dict): """ a dictionary that lets you do d['a'] as well as d.a this is only used to store a Row """ def __getitem__(self, key): key=str(key) if key in self.get('_extra',{}): return self._extra[key] return dict.__getitem__(self, key) def __call__(self,key): return self.__getitem__(key) def __setitem__(self, key, value): dict.__setitem__(self, str(key), value) def __getattr__(self, key): return self[key] def __setattr__(self, key, value): self[key] = value def __repr__(self): return '<Row ' + dict.__repr__(self) + '>' def __int__(self): return dict.__getitem__(self,'id') def __eq__(self,other): try: return self.as_dict() == other.as_dict() except AttributeError: return False def __ne__(self,other): return not (self == other) def __copy__(self): return Row(dict(self)) def as_dict(self,datetime_to_str=False): SERIALIZABLE_TYPES = (str,unicode,int,long,float,bool,list) d = dict(self) for k in copy.copy(d.keys()): v=d[k] if d[k] is None: continue elif isinstance(v,Row): d[k]=v.as_dict() elif isinstance(v,Reference): d[k]=int(v) elif isinstance(v,decimal.Decimal): d[k]=float(v) elif isinstance(v, (datetime.date, datetime.datetime, datetime.time)): if datetime_to_str: d[k] = v.isoformat().replace('T',' ')[:19] elif not isinstance(v,SERIALIZABLE_TYPES): del d[k] return d def Row_unpickler(data): return Row(cPickle.loads(data)) def Row_pickler(data): return Row_unpickler, (cPickle.dumps(data.as_dict(datetime_to_str=False)),) copy_reg.pickle(Row, Row_pickler, Row_unpickler) ################################################################################ # Everything below should be independent on the specifics of the # database and should for RDBMs and some NoSQL databases ################################################################################ class SQLCallableList(list): def __call__(self): return copy.copy(self) class DAL(dict): """ an instance of this class represents a database connection Example:: db = DAL('sqlite://test.db') db.define_table('tablename', Field('fieldname1'), Field('fieldname2')) """ @staticmethod def set_folder(folder): """ # ## this allows gluon to set a folder for this thread # ## <<<<<<<<< Should go away as new DAL replaces old sql.py """ BaseAdapter.set_folder(folder) @staticmethod def distributed_transaction_begin(*instances): if not instances: return thread_key = '%s.%s' % (socket.gethostname(), threading.currentThread()) keys = ['%s.%i' % (thread_key, i) for (i,db) in instances] instances = enumerate(instances) for (i, db) in instances: if not db._adapter.support_distributed_transaction(): raise SyntaxError, \ 'distributed transaction not suported by %s' % db._dbname for (i, db) in instances: db._adapter.distributed_transaction_begin(keys[i]) @staticmethod def distributed_transaction_commit(*instances): if not instances: return instances = enumerate(instances) thread_key = '%s.%s' % (socket.gethostname(), threading.currentThread()) keys = ['%s.%i' % (thread_key, i) for (i,db) in instances] for (i, db) in instances: if not db._adapter.support_distributed_transaction(): raise SyntaxError, \ 'distributed transaction not suported by %s' % db._dbanme try: for (i, db) in instances: db._adapter.prepare(keys[i]) except: for (i, db) in instances: db._adapter.rollback_prepared(keys[i]) raise RuntimeError, 'failure to commit distributed transaction' else: for (i, db) in instances: db._adapter.commit_prepared(keys[i]) return def __init__(self, uri='sqlite://dummy.db', pool_size=0, folder=None, db_codec='UTF-8', check_reserved=None, migrate=True, fake_migrate=False, migrate_enabled=True, fake_migrate_all=False, decode_credentials=False, driver_args=None, adapter_args={}, attempts=5, auto_import=False): """ Creates a new Database Abstraction Layer instance. Keyword arguments: :uri: string that contains information for connecting to a database. (default: 'sqlite://dummy.db') :pool_size: How many open connections to make to the database object. :folder: <please update me> :db_codec: string encoding of the database (default: 'UTF-8') :check_reserved: list of adapters to check tablenames and column names against sql reserved keywords. (Default None) * 'common' List of sql keywords that are common to all database types such as "SELECT, INSERT". (recommended) * 'all' Checks against all known SQL keywords. (not recommended) <adaptername> Checks against the specific adapters list of keywords (recommended) * '<adaptername>_nonreserved' Checks against the specific adapters list of nonreserved keywords. (if available) :migrate (defaults to True) sets default migrate behavior for all tables :fake_migrate (defaults to False) sets default fake_migrate behavior for all tables :migrate_enabled (defaults to True). If set to False disables ALL migrations :fake_migrate_all (defaults to False). If sets to True fake migrates ALL tables :attempts (defaults to 5). Number of times to attempt connecting """ if not decode_credentials: credential_decoder = lambda cred: cred else: credential_decoder = lambda cred: urllib.unquote(cred) if folder: self.set_folder(folder) self._uri = uri self._pool_size = pool_size self._db_codec = db_codec self._lastsql = '' self._timings = [] self._pending_references = {} self._request_tenant = 'request_tenant' self._common_fields = [] if not str(attempts).isdigit() or attempts < 0: attempts = 5 if uri: uris = isinstance(uri,(list,tuple)) and uri or [uri] error = '' connected = False for k in range(attempts): for uri in uris: try: if is_jdbc and not uri.startswith('jdbc:'): uri = 'jdbc:'+uri self._dbname = regex_dbname.match(uri).group() if not self._dbname in ADAPTERS: raise SyntaxError, "Error in URI '%s' or database not supported" % self._dbname # notice that driver args or {} else driver_args defaults to {} global, not correct args = (self,uri,pool_size,folder,db_codec,credential_decoder,driver_args or {}, adapter_args) self._adapter = ADAPTERS[self._dbname](*args) connected = True break except SyntaxError: raise except Exception, error: sys.stderr.write('DEBUG_c: Exception %r' % ((Exception, error,),)) if connected: break else: time.sleep(1) if not connected: raise RuntimeError, "Failure to connect, tried %d times:\n%s" % (attempts, error) else: args = (self,'None',0,folder,db_codec) self._adapter = BaseAdapter(*args) migrate = fake_migrate = False adapter = self._adapter self._uri_hash = hashlib.md5(adapter.uri).hexdigest() self.tables = SQLCallableList() self.check_reserved = check_reserved if self.check_reserved: from reserved_sql_keywords import ADAPTERS as RSK self.RSK = RSK self._migrate = migrate self._fake_migrate = fake_migrate self._migrate_enabled = migrate_enabled self._fake_migrate_all = fake_migrate_all if auto_import: self.import_table_definitions(adapter.folder) def import_table_definitions(self,path,migrate=False,fake_migrate=False): pattern = os.path.join(path,self._uri_hash+'_*.table') for filename in glob.glob(pattern): tfile = self._adapter.file_open(filename, 'r') try: sql_fields = cPickle.load(tfile) name = filename[len(pattern)-7:-6] mf = [(value['sortable'],Field(key,type=value['type'])) \ for key, value in sql_fields.items()] mf.sort(lambda a,b: cmp(a[0],b[0])) self.define_table(name,*[item[1] for item in mf], **dict(migrate=migrate,fake_migrate=fake_migrate)) finally: self._adapter.file_close(tfile) def check_reserved_keyword(self, name): """ Validates ``name`` against SQL keywords Uses self.check_reserve which is a list of operators to use. self.check_reserved ['common', 'postgres', 'mysql'] self.check_reserved ['all'] """ for backend in self.check_reserved: if name.upper() in self.RSK[backend]: raise SyntaxError, 'invalid table/column name "%s" is a "%s" reserved SQL keyword' % (name, backend.upper()) def __contains__(self, tablename): if self.has_key(tablename): return True else: return False def parse_as_rest(self,patterns,args,vars,query=None,nested_select=True): """ EXAMPLE: db.define_table('person',Field('name'),Field('info')) db.define_table('pet',Field('person',db.person),Field('name'),Field('info')) @request.restful() def index(): def GET(*kargs,**kvars): patterns = [ "/persons[person]", "/{person.name.startswith}", "/{person.name}/:field", "/{person.name}/pets[pet.person]", "/{person.name}/pet[pet.person]/{pet.name}", "/{person.name}/pet[pet.person]/{pet.name}/:field" ] parser = db.parse_as_rest(patterns,kargs,kvars) if parser.status == 200: return dict(content=parser.response) else: raise HTTP(parser.status,parser.error) def POST(table_name,**kvars): if table_name == 'person': return db.person.validate_and_insert(**kvars) elif table_name == 'pet': return db.pet.validate_and_insert(**kvars) else: raise HTTP(400) return locals() """ db = self re1 = re.compile('^{[^\.]+\.[^\.]+(\.(lt|gt|le|ge|eq|ne|contains|startswith|year|month|day|hour|minute|second))?(\.not)?}$') re2 = re.compile('^.+\[.+\]$') def auto_table(table,base='',depth=0): patterns = [] for field in db[table].fields: if base: tag = '%s/%s' % (base,field.replace('_','-')) else: tag = '/%s/%s' % (table.replace('_','-'),field.replace('_','-')) f = db[table][field] if not f.readable: continue if f.type=='id' or 'slug' in field or f.type.startswith('reference'): tag += '/{%s.%s}' % (table,field) patterns.append(tag) patterns.append(tag+'/:field') elif f.type.startswith('boolean'): tag += '/{%s.%s}' % (table,field) patterns.append(tag) patterns.append(tag+'/:field') elif f.type.startswith('double') or f.type.startswith('integer'): tag += '/{%s.%s.ge}/{%s.%s.lt}' % (table,field,table,field) patterns.append(tag) patterns.append(tag+'/:field') elif f.type.startswith('list:'): tag += '/{%s.%s.contains}' % (table,field) patterns.append(tag) patterns.append(tag+'/:field') elif f.type in ('date','datetime'): tag+= '/{%s.%s.year}' % (table,field) patterns.append(tag) patterns.append(tag+'/:field') tag+='/{%s.%s.month}' % (table,field) patterns.append(tag) patterns.append(tag+'/:field') tag+='/{%s.%s.day}' % (table,field) patterns.append(tag) patterns.append(tag+'/:field') if f.type in ('datetime','time'): tag+= '/{%s.%s.hour}' % (table,field) patterns.append(tag) patterns.append(tag+'/:field') tag+='/{%s.%s.minute}' % (table,field) patterns.append(tag) patterns.append(tag+'/:field') tag+='/{%s.%s.second}' % (table,field) patterns.append(tag) patterns.append(tag+'/:field') if depth>0: for rtable,rfield in db[table]._referenced_by: tag+='/%s[%s.%s]' % (rtable,rtable,rfield) patterns.append(tag) patterns += auto_table(rtable,base=tag,depth=depth-1) return patterns if patterns=='auto': patterns=[] for table in db.tables: if not table.startswith('auth_'): patterns += auto_table(table,base='',depth=1) else: i = 0 while i<len(patterns): pattern = patterns[i] tokens = pattern.split('/') if tokens[-1].startswith(':auto') and re2.match(tokens[-1]): new_patterns = auto_table(tokens[-1][tokens[-1].find('[')+1:-1],'/'.join(tokens[:-1])) patterns = patterns[:i]+new_patterns+patterns[i+1:] i += len(new_patterns) else: i += 1 if '/'.join(args) == 'patterns': return Row({'status':200,'pattern':'list', 'error':None,'response':patterns}) for pattern in patterns: otable=table=None dbset=db(query) i=0 tags = pattern[1:].split('/') # print pattern if len(tags)!=len(args): continue for tag in tags: # print i, tag, args[i] if re1.match(tag): # print 're1:'+tag tokens = tag[1:-1].split('.') table, field = tokens[0], tokens[1] if not otable or table == otable: if len(tokens)==2 or tokens[2]=='eq': query = db[table][field]==args[i] elif tokens[2]=='ne': query = db[table][field]!=args[i] elif tokens[2]=='lt': query = db[table][field]<args[i] elif tokens[2]=='gt': query = db[table][field]>args[i] elif tokens[2]=='ge': query = db[table][field]>=args[i] elif tokens[2]=='le': query = db[table][field]<=args[i] elif tokens[2]=='year': query = db[table][field].year()==args[i] elif tokens[2]=='month': query = db[table][field].month()==args[i] elif tokens[2]=='day': query = db[table][field].day()==args[i] elif tokens[2]=='hour': query = db[table][field].hour()==args[i] elif tokens[2]=='minute': query = db[table][field].minutes()==args[i] elif tokens[2]=='second': query = db[table][field].seconds()==args[i] elif tokens[2]=='startswith': query = db[table][field].startswith(args[i]) elif tokens[2]=='contains': query = db[table][field].contains(args[i]) else: raise RuntimeError, "invalid pattern: %s" % pattern if len(tokens)==4 and tokens[3]=='not': query = ~query elif len(tokens)>=4: raise RuntimeError, "invalid pattern: %s" % pattern dbset=dbset(query) else: raise RuntimeError, "missing relation in pattern: %s" % pattern elif otable and re2.match(tag) and args[i]==tag[:tag.find('[')]: # print 're2:'+tag ref = tag[tag.find('[')+1:-1] if '.' in ref: table,field = ref.split('.') # print table,field if nested_select: try: dbset=db(db[table][field].belongs(dbset._select(db[otable]._id))) except ValueError: return Row({'status':400,'pattern':pattern, 'error':'invalid path','response':None}) else: items = [item.id for item in dbset.select(db[otable]._id)] dbset=db(db[table][field].belongs(items)) else: dbset=dbset(db[ref]) elif tag==':field' and table: # # print 're3:'+tag field = args[i] if not field in db[table]: break try: item = dbset.select(db[table][field],limitby=(0,1)).first() except ValueError: return Row({'status':400,'pattern':pattern, 'error':'invalid path','response':None}) if not item: return Row({'status':404,'pattern':pattern, 'error':'record not found','response':None}) else: return Row({'status':200,'response':item[field], 'pattern':pattern}) elif tag != args[i]: break otable = table i += 1 if i==len(tags) and table: otable,ofield = vars.get('order','%s.%s' % (table,field)).split('.',1) try: if otable[:1]=='~': orderby = ~db[otable[1:]][ofield] else: orderby = db[otable][ofield] except KeyError: return Row({'status':400,'error':'invalid orderby','response':None}) fields = [field for field in db[table] if field.readable] count = dbset.count() try: limits = (int(vars.get('min',0)),int(vars.get('max',1000))) if limits[0]<0 or limits[1]<limits[0]: raise ValueError except ValueError: Row({'status':400,'error':'invalid limits','response':None}) if count > limits[1]-limits[0]: Row({'status':400,'error':'too many records','response':None}) try: response = dbset.select(limitby=limits,orderby=orderby,*fields) except ValueError: return Row({'status':400,'pattern':pattern, 'error':'invalid path','response':None}) return Row({'status':200,'response':response,'pattern':pattern}) return Row({'status':400,'error':'no matching pattern','response':None}) def define_table( self, tablename, *fields, **args ): for key in args: if key not in [ 'migrate', 'primarykey', 'fake_migrate', 'format', 'trigger_name', 'sequence_name', 'polymodel']: raise SyntaxError, 'invalid table "%s" attribute: %s' % (tablename, key) migrate = self._migrate_enabled and args.get('migrate',self._migrate) fake_migrate = self._fake_migrate_all or args.get('fake_migrate',self._fake_migrate) format = args.get('format',None) trigger_name = args.get('trigger_name', None) sequence_name = args.get('sequence_name', None) primarykey=args.get('primarykey',None) polymodel=args.get('polymodel',None) if not isinstance(tablename,str): raise SyntaxError, "missing table name" tablename = cleanup(tablename) lowertablename = tablename.lower() if tablename.startswith('_') or hasattr(self,lowertablename) or \ regex_python_keywords.match(tablename): raise SyntaxError, 'invalid table name: %s' % tablename elif lowertablename in self.tables: raise SyntaxError, 'table already defined: %s' % tablename elif self.check_reserved: self.check_reserved_keyword(tablename) if self._common_fields: fields = [f for f in fields] + [f for f in self._common_fields] t = self[tablename] = Table(self, tablename, *fields, **dict(primarykey=primarykey, trigger_name=trigger_name, sequence_name=sequence_name)) # db magic if self._uri in (None,'None'): return t t._create_references() if migrate or self._adapter.dbengine=='google:datastore': try: sql_locker.acquire() self._adapter.create_table(t,migrate=migrate, fake_migrate=fake_migrate, polymodel=polymodel) finally: sql_locker.release() else: t._dbt = None self.tables.append(tablename) t._format = format return t def __iter__(self): for tablename in self.tables: yield self[tablename] def __getitem__(self, key): return dict.__getitem__(self, str(key)) def __setitem__(self, key, value): dict.__setitem__(self, str(key), value) def __getattr__(self, key): return self[key] def __setattr__(self, key, value): if key[:1]!='_' and key in self: raise SyntaxError, \ 'Object %s exists and cannot be redefined' % key self[key] = value def __repr__(self): return '<DAL ' + dict.__repr__(self) + '>' def __call__(self, query=None): if isinstance(query,Table): query = query._id>0 elif isinstance(query,Field): query = query!=None return Set(self, query) def commit(self): self._adapter.commit() def rollback(self): self._adapter.rollback() def executesql(self, query, placeholders=None, as_dict=False): """ placeholders is optional and will always be None when using DAL if using raw SQL with placeholders, placeholders may be a sequence of values to be substituted in or, *if supported by the DB driver*, a dictionary with keys matching named placeholders in your SQL. Added 2009-12-05 "as_dict" optional argument. Will always be None when using DAL. If using raw SQL can be set to True and the results cursor returned by the DB driver will be converted to a sequence of dictionaries keyed with the db field names. Tested with SQLite but should work with any database since the cursor.description used to get field names is part of the Python dbi 2.0 specs. Results returned with as_dict = True are the same as those returned when applying .to_list() to a DAL query. [{field1: value1, field2: value2}, {field1: value1b, field2: value2b}] --bmeredyk """ if placeholders: self._adapter.execute(query, placeholders) else: self._adapter.execute(query) if as_dict: if not hasattr(self._adapter.cursor,'description'): raise RuntimeError, "database does not support executesql(...,as_dict=True)" # Non-DAL legacy db query, converts cursor results to dict. # sequence of 7-item sequences. each sequence tells about a column. # first item is always the field name according to Python Database API specs columns = self._adapter.cursor.description # reduce the column info down to just the field names fields = [f[0] for f in columns] # will hold our finished resultset in a list data = self._adapter.cursor.fetchall() # convert the list for each row into a dictionary so it's # easier to work with. row['field_name'] rather than row[0] return [dict(zip(fields,row)) for row in data] # see if any results returned from database try: return self._adapter.cursor.fetchall() except: return None def _update_referenced_by(self, other): for tablename in self.tables: by = self[tablename]._referenced_by by[:] = [item for item in by if not item[0] == other] def export_to_csv_file(self, ofile, *args, **kwargs): for table in self.tables: ofile.write('TABLE %s\r\n' % table) self(self[table]._id > 0).select().export_to_csv_file(ofile, *args, **kwargs) ofile.write('\r\n\r\n') ofile.write('END') def import_from_csv_file(self, ifile, id_map={}, null='<NULL>', unique='uuid', *args, **kwargs): for line in ifile: line = line.strip() if not line: continue elif line == 'END': return elif not line.startswith('TABLE ') or not line[6:] in self.tables: raise SyntaxError, 'invalid file format' else: tablename = line[6:] self[tablename].import_from_csv_file(ifile, id_map, null, unique, *args, **kwargs) class SQLALL(object): """ Helper class providing a comma-separated string having all the field names (prefixed by table name and '.') normally only called from within gluon.sql """ def __init__(self, table): self.table = table def __str__(self): return ', '.join([str(field) for field in self.table]) class Reference(int): def __allocate(self): if not self._record: self._record = self._table[int(self)] if not self._record: raise RuntimeError, "Using a recursive select but encountered a broken reference: %s %d"%(self._table, int(self)) def __getattr__(self, key): if key == 'id': return int(self) self.__allocate() return self._record.get(key, None) def __setattr__(self, key, value): if key.startswith('_'): int.__setattr__(self, key, value) return self.__allocate() self._record[key] = value def __getitem__(self, key): if key == 'id': return int(self) self.__allocate() return self._record.get(key, None) def __setitem__(self,key,value): self.__allocate() self._record[key] = value def Reference_unpickler(data): return marshal.loads(data) def Reference_pickler(data): try: marshal_dump = marshal.dumps(int(data)) except AttributeError: marshal_dump = 'i%s' % struct.pack('<i', int(data)) return (Reference_unpickler, (marshal_dump,)) copy_reg.pickle(Reference, Reference_pickler, Reference_unpickler) class Table(dict): """ an instance of this class represents a database table Example:: db = DAL(...) db.define_table('users', Field('name')) db.users.insert(name='me') # print db.users._insert(...) to see SQL db.users.drop() """ def __init__( self, db, tablename, *fields, **args ): """ Initializes the table and performs checking on the provided fields. Each table will have automatically an 'id'. If a field is of type Table, the fields (excluding 'id') from that table will be used instead. :raises SyntaxError: when a supplied field is of incorrect type. """ self._tablename = tablename self._sequence_name = args.get('sequence_name',None) or \ db and db._adapter.sequence_name(tablename) self._trigger_name = args.get('trigger_name',None) or \ db and db._adapter.trigger_name(tablename) primarykey = args.get('primarykey', None) fieldnames,newfields=set(),[] if primarykey: if not isinstance(primarykey,list): raise SyntaxError, \ "primarykey must be a list of fields from table '%s'" \ % tablename self._primarykey = primarykey elif not [f for f in fields if isinstance(f,Field) and f.type=='id']: field = Field('id', 'id') newfields.append(field) fieldnames.add('id') self._id = field for field in fields: if not isinstance(field, (Field, Table)): raise SyntaxError, \ 'define_table argument is not a Field or Table: %s' % field elif isinstance(field, Field) and not field.name in fieldnames: if hasattr(field, '_db'): field = copy.copy(field) newfields.append(field) fieldnames.add(field.name) if field.type=='id': self._id = field elif isinstance(field, Table): table = field for field in table: if not field.name in fieldnames and not field.type=='id': newfields.append(copy.copy(field)) fieldnames.add(field.name) else: # let's ignore new fields with duplicated names!!! pass fields = newfields self._db = db tablename = tablename self.fields = SQLCallableList() self.virtualfields = [] fields = list(fields) if db and self._db._adapter.uploads_in_blob==True: for field in fields: if isinstance(field, Field) and field.type == 'upload'\ and field.uploadfield is True: tmp = field.uploadfield = '%s_blob' % field.name fields.append(self._db.Field(tmp, 'blob', default='')) lower_fieldnames = set() reserved = dir(Table) + ['fields'] for field in fields: if db and db.check_reserved: db.check_reserved_keyword(field.name) elif field.name in reserved: raise SyntaxError, "field name %s not allowed" % field.name if field.name.lower() in lower_fieldnames: raise SyntaxError, "duplicate field %s in table %s" \ % (field.name, tablename) else: lower_fieldnames.add(field.name.lower()) self.fields.append(field.name) self[field.name] = field if field.type == 'id': self['id'] = field field.tablename = field._tablename = tablename field.table = field._table = self field.db = field._db = self._db if self._db and field.type!='text' and \ self._db._adapter.maxcharlength < field.length: field.length = self._db._adapter.maxcharlength if field.requires == DEFAULT: field.requires = sqlhtml_validators(field) self.ALL = SQLALL(self) if hasattr(self,'_primarykey'): for k in self._primarykey: if k not in self.fields: raise SyntaxError, \ "primarykey must be a list of fields from table '%s " % tablename else: self[k].notnull = True def _validate(self,**vars): errors = Row() for key,value in vars.items(): value,error = self[key].validate(value) if error: errors[key] = error return errors def _create_references(self): pr = self._db._pending_references self._referenced_by = [] for fieldname in self.fields: field=self[fieldname] if isinstance(field.type,str) and field.type[:10] == 'reference ': ref = field.type[10:].strip() if not ref.split(): raise SyntaxError, 'Table: reference to nothing: %s' %ref refs = ref.split('.') rtablename = refs[0] if not rtablename in self._db: pr[rtablename] = pr.get(rtablename,[]) + [field] continue rtable = self._db[rtablename] if len(refs)==2: rfieldname = refs[1] if not hasattr(rtable,'_primarykey'): raise SyntaxError,\ 'keyed tables can only reference other keyed tables (for now)' if rfieldname not in rtable.fields: raise SyntaxError,\ "invalid field '%s' for referenced table '%s' in table '%s'" \ % (rfieldname, rtablename, self._tablename) rtable._referenced_by.append((self._tablename, field.name)) for referee in pr.get(self._tablename,[]): self._referenced_by.append((referee._tablename,referee.name)) def _filter_fields(self, record, id=False): return dict([(k, v) for (k, v) in record.items() if k in self.fields and (self[k].type!='id' or id)]) def _build_query(self,key): """ for keyed table only """ query = None for k,v in key.iteritems(): if k in self._primarykey: if query: query = query & (self[k] == v) else: query = (self[k] == v) else: raise SyntaxError, \ 'Field %s is not part of the primary key of %s' % \ (k,self._tablename) return query def __getitem__(self, key): if not key: return None elif isinstance(key, dict): """ for keyed table """ query = self._build_query(key) rows = self._db(query).select() if rows: return rows[0] return None elif str(key).isdigit(): return self._db(self._id == key).select(limitby=(0,1)).first() elif key: return dict.__getitem__(self, str(key)) def __call__(self, key=DEFAULT, **kwargs): if key!=DEFAULT: if isinstance(key, Query): record = self._db(key).select(limitby=(0,1)).first() elif not str(key).isdigit(): record = None else: record = self._db(self._id == key).select(limitby=(0,1)).first() if record: for k,v in kwargs.items(): if record[k]!=v: return None return record elif kwargs: query = reduce(lambda a,b:a&b,[self[k]==v for k,v in kwargs.items()]) return self._db(query).select(limitby=(0,1)).first() else: return None def __setitem__(self, key, value): if isinstance(key, dict) and isinstance(value, dict): """ option for keyed table """ if set(key.keys()) == set(self._primarykey): value = self._filter_fields(value) kv = {} kv.update(value) kv.update(key) if not self.insert(**kv): query = self._build_query(key) self._db(query).update(**self._filter_fields(value)) else: raise SyntaxError,\ 'key must have all fields from primary key: %s'%\ (self._primarykey) elif str(key).isdigit(): if key == 0: self.insert(**self._filter_fields(value)) elif not self._db(self._id == key)\ .update(**self._filter_fields(value)): raise SyntaxError, 'No such record: %s' % key else: if isinstance(key, dict): raise SyntaxError,\ 'value must be a dictionary: %s' % value dict.__setitem__(self, str(key), value) def __delitem__(self, key): if isinstance(key, dict): query = self._build_query(key) if not self._db(query).delete(): raise SyntaxError, 'No such record: %s' % key elif not str(key).isdigit() or not self._db(self._id == key).delete(): raise SyntaxError, 'No such record: %s' % key def __getattr__(self, key): return self[key] def __setattr__(self, key, value): if key in self: raise SyntaxError, 'Object exists and cannot be redefined: %s' % key self[key] = value def __iter__(self): for fieldname in self.fields: yield self[fieldname] def __repr__(self): return '<Table ' + dict.__repr__(self) + '>' def __str__(self): if self.get('_ot', None): return '%s AS %s' % (self._ot, self._tablename) return self._tablename def _drop(self, mode = ''): return self._db._adapter._drop(self, mode) def drop(self, mode = ''): return self._db._adapter.drop(self,mode) def _listify(self,fields,update=False): new_fields = [] new_fields_names = [] for name in fields: if not name in self.fields: if name != 'id': raise SyntaxError, 'Field %s does not belong to the table' % name else: new_fields.append((self[name],fields[name])) new_fields_names.append(name) for ofield in self: if not ofield.name in new_fields_names: if not update and ofield.default!=None: new_fields.append((ofield,ofield.default)) elif update and ofield.update!=None: new_fields.append((ofield,ofield.update)) for ofield in self: if not ofield.name in new_fields_names and ofield.compute: try: new_fields.append((ofield,ofield.compute(Row(fields)))) except KeyError: pass if not update and ofield.required and not ofield.name in new_fields_names: raise SyntaxError,'Table: missing required field: %s' % ofield.name return new_fields def _insert(self, **fields): return self._db._adapter._insert(self,self._listify(fields)) def insert(self, **fields): return self._db._adapter.insert(self,self._listify(fields)) def validate_and_insert(self,**fields): response = Row() response.errors = self._validate(**fields) if not response.errors: response.id = self.insert(**fields) else: response.id = None return response def update_or_insert(self, key=DEFAULT, **values): if key==DEFAULT: record = self(**values) else: record = self(key) if record: record.update_record(**values) newid = None else: newid = self.insert(**values) return newid def bulk_insert(self, items): """ here items is a list of dictionaries """ items = [self._listify(item) for item in items] return self._db._adapter.bulk_insert(self,items) def _truncate(self, mode = None): return self._db._adapter._truncate(self, mode) def truncate(self, mode = None): return self._db._adapter.truncate(self, mode) def import_from_csv_file( self, csvfile, id_map=None, null='<NULL>', unique='uuid', *args, **kwargs ): """ import records from csv file. Column headers must have same names as table fields. field 'id' is ignored. If column names read 'table.file' the 'table.' prefix is ignored. 'unique' argument is a field which must be unique (typically a uuid field) """ delimiter = kwargs.get('delimiter', ',') quotechar = kwargs.get('quotechar', '"') quoting = kwargs.get('quoting', csv.QUOTE_MINIMAL) reader = csv.reader(csvfile, delimiter=delimiter, quotechar=quotechar, quoting=quoting) colnames = None if isinstance(id_map, dict): if not self._tablename in id_map: id_map[self._tablename] = {} id_map_self = id_map[self._tablename] def fix(field, value, id_map): if value == null: value = None elif field.type=='blob': value = base64.b64decode(value) elif field.type=='double': if not value.strip(): value = None else: value = float(value) elif field.type=='integer': if not value.strip(): value = None else: value = int(value) elif field.type.startswith('list:string'): value = bar_decode_string(value) elif field.type.startswith('list:reference'): ref_table = field.type[10:].strip() value = [id_map[ref_table][int(v)] \ for v in bar_decode_string(value)] elif field.type.startswith('list:'): value = bar_decode_integer(value) elif id_map and field.type.startswith('reference'): try: value = id_map[field.type[9:].strip()][value] except KeyError: pass return (field.name, value) def is_id(colname): if colname in self: return self[colname].type == 'id' else: return False for line in reader: if not line: break if not colnames: colnames = [x.split('.',1)[-1] for x in line][:len(line)] cols, cid = [], [] for i,colname in enumerate(colnames): if is_id(colname): cid = i else: cols.append(i) if colname == unique: unique_idx = i else: items = [fix(self[colnames[i]], line[i], id_map) \ for i in cols if colnames[i] in self.fields] # Validation. Check for duplicate of 'unique' &, # if present, update instead of insert. if not unique or unique not in colnames: new_id = self.insert(**dict(items)) else: unique_value = line[unique_idx] query = self._db[self][unique] == unique_value record = self._db(query).select().first() if record: record.update_record(**dict(items)) new_id = record[self._id.name] else: new_id = self.insert(**dict(items)) if id_map and cid != []: id_map_self[line[cid]] = new_id def with_alias(self, alias): return self._db._adapter.alias(self,alias) def on(self, query): return Expression(self._db,self._db._adapter.ON,self,query) class Expression(object): def __init__( self, db, op, first=None, second=None, type=None, ): self.db = db self.op = op self.first = first self.second = second ### self._tablename = first._tablename ## CHECK if not type and first and hasattr(first,'type'): self.type = first.type else: self.type = type def sum(self): return Expression(self.db, self.db._adapter.AGGREGATE, self, 'SUM', self.type) def max(self): return Expression(self.db, self.db._adapter.AGGREGATE, self, 'MAX', self.type) def min(self): return Expression(self.db, self.db._adapter.AGGREGATE, self, 'MIN', self.type) def len(self): return Expression(self.db, self.db._adapter.AGGREGATE, self, 'LENGTH', 'integer') def lower(self): return Expression(self.db, self.db._adapter.LOWER, self, None, self.type) def upper(self): return Expression(self.db, self.db._adapter.UPPER, self, None, self.type) def year(self): return Expression(self.db, self.db._adapter.EXTRACT, self, 'year', 'integer') def month(self): return Expression(self.db, self.db._adapter.EXTRACT, self, 'month', 'integer') def day(self): return Expression(self.db, self.db._adapter.EXTRACT, self, 'day', 'integer') def hour(self): return Expression(self.db, self.db._adapter.EXTRACT, self, 'hour', 'integer') def minutes(self): return Expression(self.db, self.db._adapter.EXTRACT, self, 'minute', 'integer') def coalesce_zero(self): return Expression(self.db, self.db._adapter.COALESCE_ZERO, self, None, self.type) def seconds(self): return Expression(self.db, self.db._adapter.EXTRACT, self, 'second', 'integer') def __getslice__(self, start, stop): if start < 0: pos0 = '(%s - %d)' % (self.len(), abs(start) - 1) else: pos0 = start + 1 if stop < 0: length = '(%s - %d - %s)' % (self.len(), abs(stop) - 1, pos0) elif stop == sys.maxint: length = self.len() else: length = '(%s - %s)' % (stop + 1, pos0) return Expression(self.db,self.db._adapter.SUBSTRING, self, (pos0, length), self.type) def __getitem__(self, i): return self[i:i + 1] def __str__(self): return self.db._adapter.expand(self,self.type) def __or__(self, other): # for use in sortby return Expression(self.db,self.db._adapter.COMMA,self,other,self.type) def __invert__(self): if hasattr(self,'_op') and self.op == self.db._adapter.INVERT: return self.first return Expression(self.db,self.db._adapter.INVERT,self,type=self.type) def __add__(self, other): return Expression(self.db,self.db._adapter.ADD,self,other,self.type) def __sub__(self, other): if self.type == 'integer': result_type = 'integer' elif self.type in ['date','time','datetime','double']: result_type = 'double' else: raise SyntaxError, "subtraction operation not supported for type" return Expression(self.db,self.db._adapter.SUB,self,other, result_type) def __mul__(self, other): return Expression(self.db,self.db._adapter.MUL,self,other,self.type) def __div__(self, other): return Expression(self.db,self.db._adapter.DIV,self,other,self.type) def __mod__(self, other): return Expression(self.db,self.db._adapter.MOD,self,other,self.type) def __eq__(self, value): return Query(self.db, self.db._adapter.EQ, self, value) def __ne__(self, value): return Query(self.db, self.db._adapter.NE, self, value) def __lt__(self, value): return Query(self.db, self.db._adapter.LT, self, value) def __le__(self, value): return Query(self.db, self.db._adapter.LE, self, value) def __gt__(self, value): return Query(self.db, self.db._adapter.GT, self, value) def __ge__(self, value): return Query(self.db, self.db._adapter.GE, self, value) def like(self, value): return Query(self.db, self.db._adapter.LIKE, self, value) def belongs(self, value): return Query(self.db, self.db._adapter.BELONGS, self, value) def startswith(self, value): if not self.type in ('string', 'text'): raise SyntaxError, "startswith used with incompatible field type" return Query(self.db, self.db._adapter.STARTSWITH, self, value) def endswith(self, value): if not self.type in ('string', 'text'): raise SyntaxError, "endswith used with incompatible field type" return Query(self.db, self.db._adapter.ENDSWITH, self, value) def contains(self, value): if not self.type in ('string', 'text') and not self.type.startswith('list:'): raise SyntaxError, "contains used with incompatible field type" return Query(self.db, self.db._adapter.CONTAINS, self, value) def with_alias(self,alias): return Expression(self.db,self.db._adapter.AS,self,alias,self.type) # for use in both Query and sortby class SQLCustomType(object): """ allows defining of custom SQL types Example:: decimal = SQLCustomType( type ='double', native ='integer', encoder =(lambda x: int(float(x) * 100)), decoder = (lambda x: Decimal("0.00") + Decimal(str(float(x)/100)) ) ) db.define_table( 'example', Field('value', type=decimal) ) :param type: the web2py type (default = 'string') :param native: the backend type :param encoder: how to encode the value to store it in the backend :param decoder: how to decode the value retrieved from the backend :param validator: what validators to use ( default = None, will use the default validator for type) """ def __init__( self, type='string', native=None, encoder=None, decoder=None, validator=None, _class=None, ): self.type = type self.native = native self.encoder = encoder or (lambda x: x) self.decoder = decoder or (lambda x: x) self.validator = validator self._class = _class or type def startswith(self, dummy=None): return False def __getslice__(self, a=0, b=100): return None def __getitem__(self, i): return None def __str__(self): return self._class class Field(Expression): """ an instance of this class represents a database field example:: a = Field(name, 'string', length=32, default=None, required=False, requires=IS_NOT_EMPTY(), ondelete='CASCADE', notnull=False, unique=False, uploadfield=True, widget=None, label=None, comment=None, uploadfield=True, # True means store on disk, # 'a_field_name' means store in this field in db # False means file content will be discarded. writable=True, readable=True, update=None, authorize=None, autodelete=False, represent=None, uploadfolder=None, uploadseparate=False # upload to separate directories by uuid_keys # first 2 character and tablename.fieldname # False - old behavior # True - put uploaded file in # <uploaddir>/<tablename>.<fieldname>/uuid_key[:2] # directory) to be used as argument of DAL.define_table allowed field types: string, boolean, integer, double, text, blob, date, time, datetime, upload, password strings must have a length of Adapter.maxcharlength by default (512 or 255 for mysql) fields should have a default or they will be required in SQLFORMs the requires argument is used to validate the field input in SQLFORMs """ def __init__( self, fieldname, type='string', length=None, default=DEFAULT, required=False, requires=DEFAULT, ondelete='CASCADE', notnull=False, unique=False, uploadfield=True, widget=None, label=None, comment=None, writable=True, readable=True, update=None, authorize=None, autodelete=False, represent=None, uploadfolder=None, uploadseparate=False, compute=None, custom_store=None, custom_retrieve=None, custom_delete=None, ): self.db = None self.op = None self.first = None self.second = None if not isinstance(fieldname,str): raise SyntaxError, "missing field name" if fieldname.startswith(':'): fieldname,readable,writable=fieldname[1:],False,False elif fieldname.startswith('.'): fieldname,readable,writable=fieldname[1:],False,False if '=' in fieldname: fieldname,default = fieldname.split('=',1) self.name = fieldname = cleanup(fieldname) if hasattr(Table,fieldname) or fieldname[0] == '_' or \ regex_python_keywords.match(fieldname): raise SyntaxError, 'Field: invalid field name: %s' % fieldname if isinstance(type, Table): type = 'reference ' + type._tablename self.type = type # 'string', 'integer' self.length = (length is None) and MAXCHARLENGTH or length if default==DEFAULT: self.default = update or None else: self.default = default self.required = required # is this field required self.ondelete = ondelete.upper() # this is for reference fields only self.notnull = notnull self.unique = unique self.uploadfield = uploadfield self.uploadfolder = uploadfolder self.uploadseparate = uploadseparate self.widget = widget self.label = label or ' '.join(item.capitalize() for item in fieldname.split('_')) self.comment = comment self.writable = writable self.readable = readable self.update = update self.authorize = authorize self.autodelete = autodelete if not represent and type in ('list:integer','list:string'): represent=lambda x: ', '.join(str(y) for y in x or []) self.represent = represent self.compute = compute self.isattachment = True self.custom_store = custom_store self.custom_retrieve = custom_retrieve self.custom_delete = custom_delete if self.label is None: self.label = ' '.join([x.capitalize() for x in fieldname.split('_')]) if requires is None: self.requires = [] else: self.requires = requires def store(self, file, filename=None, path=None): if self.custom_store: return self.custom_store(file,filename,path) if not filename: filename = file.name filename = os.path.basename(filename.replace('/', os.sep)\ .replace('\\', os.sep)) m = re.compile('\.(?P<e>\w{1,5})$').search(filename) extension = m and m.group('e') or 'txt' uuid_key = web2py_uuid().replace('-', '')[-16:] encoded_filename = base64.b16encode(filename).lower() newfilename = '%s.%s.%s.%s' % \ (self._tablename, self.name, uuid_key, encoded_filename) newfilename = newfilename[:200] + '.' + extension if isinstance(self.uploadfield,Field): blob_uploadfield_name = self.uploadfield.uploadfield keys={self.uploadfield.name: newfilename, blob_uploadfield_name: file.read()} self.uploadfield.table.insert(**keys) elif self.uploadfield == True: if path: pass elif self.uploadfolder: path = self.uploadfolder elif self.db._adapter.folder: path = os.path.join(self.db._adapter.folder, '..', 'uploads') else: raise RuntimeError, "you must specify a Field(...,uploadfolder=...)" if self.uploadseparate: path = os.path.join(path,"%s.%s" % (self._tablename, self.name),uuid_key[:2]) if not os.path.exists(path): os.makedirs(path) pathfilename = os.path.join(path, newfilename) dest_file = open(pathfilename, 'wb') try: shutil.copyfileobj(file, dest_file) finally: dest_file.close() return newfilename def retrieve(self, name, path=None): if self.custom_retrieve: return self.custom_retrieve(name, path) import http if self.authorize or isinstance(self.uploadfield, str): row = self.db(self == name).select().first() if not row: raise http.HTTP(404) if self.authorize and not self.authorize(row): raise http.HTTP(403) try: m = regex_content.match(name) if not m or not self.isattachment: raise TypeError, 'Can\'t retrieve %s' % name filename = base64.b16decode(m.group('name'), True) filename = regex_cleanup_fn.sub('_', filename) except (TypeError, AttributeError): filename = name if isinstance(self.uploadfield, str): # ## if file is in DB return (filename, cStringIO.StringIO(row[self.uploadfield] or '')) elif isinstance(self.uploadfield,Field): blob_uploadfield_name = self.uploadfield.uploadfield query = self.uploadfield == name data = self.uploadfield.table(query)[blob_uploadfield_name] return (filename, cStringIO.StringIO(data)) else: # ## if file is on filesystem if path: pass elif self.uploadfolder: path = self.uploadfolder else: path = os.path.join(self.db._adapter.folder, '..', 'uploads') if self.uploadseparate: t = m.group('table') f = m.group('field') u = m.group('uuidkey') path = os.path.join(path,"%s.%s" % (t,f),u[:2]) return (filename, open(os.path.join(path, name), 'rb')) def formatter(self, value): if value is None or not self.requires: return value if not isinstance(self.requires, (list, tuple)): requires = [self.requires] elif isinstance(self.requires, tuple): requires = list(self.requires) else: requires = copy.copy(self.requires) requires.reverse() for item in requires: if hasattr(item, 'formatter'): value = item.formatter(value) return value def validate(self, value): if not self.requires: return (value, None) requires = self.requires if not isinstance(requires, (list, tuple)): requires = [requires] for validator in requires: (value, error) = validator(value) if error: return (value, error) return (value, None) def count(self): return Expression(self.db, self.db._adapter.AGGREGATE, self, 'COUNT', 'integer') def __nonzero__(self): return True def __str__(self): try: return '%s.%s' % (self.tablename, self.name) except: return '<no table>.%s' % self.name class Query(object): """ a query object necessary to define a set. it can be stored or can be passed to DAL.__call__() to obtain a Set Example:: query = db.users.name=='Max' set = db(query) records = set.select() """ def __init__( self, db, op, first=None, second=None, ): self.db = db self.op = op self.first = first self.second = second def __str__(self): return self.db._adapter.expand(self) def __and__(self, other): return Query(self.db,self.db._adapter.AND,self,other) def __or__(self, other): return Query(self.db,self.db._adapter.OR,self,other) def __invert__(self): if self.op==self.db._adapter.NOT: return self.first return Query(self.db,self.db._adapter.NOT,self) regex_quotes = re.compile("'[^']*'") def xorify(orderby): if not orderby: return None orderby2 = orderby[0] for item in orderby[1:]: orderby2 = orderby2 | item return orderby2 class Set(object): """ a Set represents a set of records in the database, the records are identified by the query=Query(...) object. normally the Set is generated by DAL.__call__(Query(...)) given a set, for example set = db(db.users.name=='Max') you can: set.update(db.users.name='Massimo') set.delete() # all elements in the set set.select(orderby=db.users.id, groupby=db.users.name, limitby=(0,10)) and take subsets: subset = set(db.users.id<5) """ def __init__(self, db, query): self.db = db self._db = db # for backward compatibility self.query = query def __call__(self, query): if isinstance(query,Table): query = query._id>0 elif isinstance(query,Field): query = query!=None if self.query: return Set(self.db, self.query & query) else: return Set(self.db, query) def _count(self,distinct=None): return self.db._adapter._count(self.query,distinct) def _select(self, *fields, **attributes): return self.db._adapter._select(self.query,fields,attributes) def _delete(self): tablename=self.db._adapter.get_table(self.query) return self.db._adapter._delete(tablename,self.query) def _update(self, **update_fields): tablename = self.db._adapter.get_table(self.query) fields = self.db[tablename]._listify(update_fields,update=True) return self.db._adapter._update(tablename,self.query,fields) def isempty(self): return not self.select(limitby=(0,1)) def count(self,distinct=None): return self.db._adapter.count(self.query,distinct) def select(self, *fields, **attributes): return self.db._adapter.select(self.query,fields,attributes) def delete(self): tablename=self.db._adapter.get_table(self.query) self.delete_uploaded_files() return self.db._adapter.delete(tablename,self.query) def update(self, **update_fields): tablename = self.db._adapter.get_table(self.query) fields = self.db[tablename]._listify(update_fields,update=True) if not fields: raise SyntaxError, "No fields to update" self.delete_uploaded_files(update_fields) return self.db._adapter.update(tablename,self.query,fields) def validate_and_update(self, **update_fields): tablename = self.db._adapter.get_table(self.query) response = Row() response.errors = self.db[tablename]._validate(**update_fields) fields = self.db[tablename]._listify(update_fields,update=True) if not fields: raise SyntaxError, "No fields to update" self.delete_uploaded_files(update_fields) if not response.errors: response.updated = self.db._adapter.update(tablename,self.query,fields) else: response.updated = None return response def delete_uploaded_files(self, upload_fields=None): table = self.db[self.db._adapter.tables(self.query)[0]] # ## mind uploadfield==True means file is not in DB if upload_fields: fields = upload_fields.keys() else: fields = table.fields fields = [f for f in fields if table[f].type == 'upload' and table[f].uploadfield == True and table[f].autodelete] if not fields: return for record in self.select(*[table[f] for f in fields]): for fieldname in fields: field = table[fieldname] oldname = record.get(fieldname, None) if not oldname: continue if upload_fields and oldname == upload_fields[fieldname]: continue if field.custom_delete: field.custom_delete(oldname) else: uploadfolder = field.uploadfolder if not uploadfolder: uploadfolder = os.path.join(self.db._adapter.folder, '..', 'uploads') if field.uploadseparate: items = oldname.split('.') uploadfolder = os.path.join(uploadfolder, "%s.%s" % (items[0], items[1]), items[2][:2]) oldpath = os.path.join(uploadfolder, oldname) if os.path.exists(oldpath): os.unlink(oldpath) def update_record(pack, a={}): (colset, table, id) = pack b = a or dict(colset) c = dict([(k,v) for (k,v) in b.items() if k in table.fields and table[k].type!='id']) table._db(table._id==id).update(**c) for (k, v) in c.items(): colset[k] = v class Rows(object): """ A wrapper for the return value of a select. It basically represents a table. It has an iterator and each row is represented as a dictionary. """ # ## TODO: this class still needs some work to care for ID/OID def __init__( self, db=None, records=[], colnames=[], compact=True, rawrows=None ): self.db = db self.records = records self.colnames = colnames self.compact = compact self.response = rawrows def setvirtualfields(self,**keyed_virtualfields): if not keyed_virtualfields: return self for row in self.records: for (tablename,virtualfields) in keyed_virtualfields.items(): attributes = dir(virtualfields) virtualfields.__dict__.update(row) if not tablename in row: box = row[tablename] = Row() else: box = row[tablename] for attribute in attributes: if attribute[0] != '_': method = getattr(virtualfields,attribute) if hasattr(method,'im_func') and method.im_func.func_code.co_argcount: box[attribute]=method() return self def __and__(self,other): if self.colnames!=other.colnames: raise Exception, 'Cannot & incompatible Rows objects' records = self.records+other.records return Rows(self.db,records,self.colnames) def __or__(self,other): if self.colnames!=other.colnames: raise Exception, 'Cannot | incompatible Rows objects' records = self.records records += [record for record in other.records \ if not record in records] return Rows(self.db,records,self.colnames) def __nonzero__(self): if len(self.records): return 1 return 0 def __len__(self): return len(self.records) def __getslice__(self, a, b): return Rows(self.db,self.records[a:b],self.colnames) def __getitem__(self, i): row = self.records[i] keys = row.keys() if self.compact and len(keys) == 1 and keys[0] != '_extra': return row[row.keys()[0]] return row def __iter__(self): """ iterator over records """ for i in xrange(len(self)): yield self[i] def __str__(self): """ serializes the table into a csv file """ s = cStringIO.StringIO() self.export_to_csv_file(s) return s.getvalue() def first(self): if not self.records: return None return self[0] def last(self): if not self.records: return None return self[-1] def find(self,f): """ returns a new Rows object, a subset of the original object, filtered by the function f """ if not self.records: return Rows(self.db, [], self.colnames) records = [] for i in range(0,len(self)): row = self[i] if f(row): records.append(self.records[i]) return Rows(self.db, records, self.colnames) def exclude(self, f): """ removes elements from the calling Rows object, filtered by the function f, and returns a new Rows object containing the removed elements """ if not self.records: return Rows(self.db, [], self.colnames) removed = [] i=0 while i<len(self): row = self[i] if f(row): removed.append(self.records[i]) del self.records[i] else: i += 1 return Rows(self.db, removed, self.colnames) def sort(self, f, reverse=False): """ returns a list of sorted elements (not sorted in place) """ return Rows(self.db,sorted(self,key=f,reverse=reverse),self.colnames) def as_list(self, compact=True, storage_to_dict=True, datetime_to_str=True): """ returns the data as a list or dictionary. :param storage_to_dict: when True returns a dict, otherwise a list(default True) :param datetime_to_str: convert datetime fields as strings (default True) """ (oc, self.compact) = (self.compact, compact) if storage_to_dict: items = [item.as_dict(datetime_to_str) for item in self] else: items = [item for item in self] self.compact = compact return items def as_dict(self, key='id', compact=True, storage_to_dict=True, datetime_to_str=True): """ returns the data as a dictionary of dictionaries (storage_to_dict=True) or records (False) :param key: the name of the field to be used as dict key, normally the id :param compact: ? (default True) :param storage_to_dict: when True returns a dict, otherwise a list(default True) :param datetime_to_str: convert datetime fields as strings (default True) """ rows = self.as_list(compact, storage_to_dict, datetime_to_str) if isinstance(key,str) and key.count('.')==1: (table, field) = key.split('.') return dict([(r[table][field],r) for r in rows]) elif isinstance(key,str): return dict([(r[key],r) for r in rows]) else: return dict([(key(r),r) for r in rows]) def export_to_csv_file(self, ofile, null='<NULL>', *args, **kwargs): """ export data to csv, the first line contains the column names :param ofile: where the csv must be exported to :param null: how null values must be represented (default '<NULL>') :param delimiter: delimiter to separate values (default ',') :param quotechar: character to use to quote string values (default '"') :param quoting: quote system, use csv.QUOTE_*** (default csv.QUOTE_MINIMAL) :param represent: use the fields .represent value (default False) :param colnames: list of column names to use (default self.colnames) This will only work when exporting rows objects!!!! DO NOT use this with db.export_to_csv() """ delimiter = kwargs.get('delimiter', ',') quotechar = kwargs.get('quotechar', '"') quoting = kwargs.get('quoting', csv.QUOTE_MINIMAL) represent = kwargs.get('represent', False) writer = csv.writer(ofile, delimiter=delimiter, quotechar=quotechar, quoting=quoting) colnames = kwargs.get('colnames', self.colnames) # a proper csv starting with the column names writer.writerow(colnames) def none_exception(value): """ returns a cleaned up value that can be used for csv export: - unicode text is encoded as such - None values are replaced with the given representation (default <NULL>) """ if value is None: return null elif isinstance(value, unicode): return value.encode('utf8') elif isinstance(value,Reference): return int(value) elif hasattr(value, 'isoformat'): return value.isoformat()[:19].replace('T', ' ') elif isinstance(value, (list,tuple)): # for type='list:..' return bar_encode(value) return value for record in self: row = [] for col in colnames: if not table_field.match(col): row.append(record._extra[col]) else: (t, f) = col.split('.') field = self.db[t][f] if isinstance(record.get(t, None), (Row,dict)): value = record[t][f] else: value = record[f] if field.type=='blob' and value!=None: value = base64.b64encode(value) elif represent and field.represent: value = field.represent(value) row.append(none_exception(value)) writer.writerow(row) def xml(self): """ serializes the table using sqlhtml.SQLTABLE (if present) """ import sqlhtml return sqlhtml.SQLTABLE(self).xml() def json(self, mode='object', default=None): """ serializes the table to a JSON list of objects """ mode = mode.lower() if not mode in ['object', 'array']: raise SyntaxError, 'Invalid JSON serialization mode: %s' % mode def inner_loop(record, col): (t, f) = col.split('.') res = None if not table_field.match(col): res = record._extra[col] else: if isinstance(record.get(t, None), Row): res = record[t][f] else: res = record[f] if mode == 'object': return (f, res) else: return res if mode == 'object': items = [dict([inner_loop(record, col) for col in self.colnames]) for record in self] else: items = [[inner_loop(record, col) for col in self.colnames] for record in self] if have_serializers: return serializers.json(items,default=default or serializers.custom_json) else: import simplejson return simplejson.dumps(items) def Rows_unpickler(data): return cPickle.loads(data) def Rows_pickler(data): return Rows_unpickler, \ (cPickle.dumps(data.as_list(storage_to_dict=True, datetime_to_str=False)),) copy_reg.pickle(Rows, Rows_pickler, Rows_unpickler) ################################################################################ # dummy function used to define some doctests ################################################################################ def test_all(): """ >>> if len(sys.argv)<2: db = DAL(\"sqlite://test.db\") >>> if len(sys.argv)>1: db = DAL(sys.argv[1]) >>> tmp = db.define_table('users',\ Field('stringf', 'string', length=32, required=True),\ Field('booleanf', 'boolean', default=False),\ Field('passwordf', 'password', notnull=True),\ Field('uploadf', 'upload'),\ Field('blobf', 'blob'),\ Field('integerf', 'integer', unique=True),\ Field('doublef', 'double', unique=True,notnull=True),\ Field('datef', 'date', default=datetime.date.today()),\ Field('timef', 'time'),\ Field('datetimef', 'datetime'),\ migrate='test_user.table') Insert a field >>> db.users.insert(stringf='a', booleanf=True, passwordf='p', blobf='0A',\ uploadf=None, integerf=5, doublef=3.14,\ datef=datetime.date(2001, 1, 1),\ timef=datetime.time(12, 30, 15),\ datetimef=datetime.datetime(2002, 2, 2, 12, 30, 15)) 1 Drop the table >>> db.users.drop() Examples of insert, select, update, delete >>> tmp = db.define_table('person',\ Field('name'),\ Field('birth','date'),\ migrate='test_person.table') >>> person_id = db.person.insert(name=\"Marco\",birth='2005-06-22') >>> person_id = db.person.insert(name=\"Massimo\",birth='1971-12-21') commented len(db().select(db.person.ALL)) commented 2 >>> me = db(db.person.id==person_id).select()[0] # test select >>> me.name 'Massimo' >>> db(db.person.name=='Massimo').update(name='massimo') # test update 1 >>> db(db.person.name=='Marco').select().first().delete_record() # test delete 1 Update a single record >>> me.update_record(name=\"Max\") >>> me.name 'Max' Examples of complex search conditions >>> len(db((db.person.name=='Max')&(db.person.birth<'2003-01-01')).select()) 1 >>> len(db((db.person.name=='Max')&(db.person.birth<datetime.date(2003,01,01))).select()) 1 >>> len(db((db.person.name=='Max')|(db.person.birth<'2003-01-01')).select()) 1 >>> me = db(db.person.id==person_id).select(db.person.name)[0] >>> me.name 'Max' Examples of search conditions using extract from date/datetime/time >>> len(db(db.person.birth.month()==12).select()) 1 >>> len(db(db.person.birth.year()>1900).select()) 1 Example of usage of NULL >>> len(db(db.person.birth==None).select()) ### test NULL 0 >>> len(db(db.person.birth!=None).select()) ### test NULL 1 Examples of search conditions using lower, upper, and like >>> len(db(db.person.name.upper()=='MAX').select()) 1 >>> len(db(db.person.name.like('%ax')).select()) 1 >>> len(db(db.person.name.upper().like('%AX')).select()) 1 >>> len(db(~db.person.name.upper().like('%AX')).select()) 0 orderby, groupby and limitby >>> people = db().select(db.person.name, orderby=db.person.name) >>> order = db.person.name|~db.person.birth >>> people = db().select(db.person.name, orderby=order) >>> people = db().select(db.person.name, orderby=db.person.name, groupby=db.person.name) >>> people = db().select(db.person.name, orderby=order, limitby=(0,100)) Example of one 2 many relation >>> tmp = db.define_table('dog',\ Field('name'),\ Field('birth','date'),\ Field('owner',db.person),\ migrate='test_dog.table') >>> db.dog.insert(name='Snoopy', birth=None, owner=person_id) 1 A simple JOIN >>> len(db(db.dog.owner==db.person.id).select()) 1 >>> len(db().select(db.person.ALL, db.dog.name,left=db.dog.on(db.dog.owner==db.person.id))) 1 Drop tables >>> db.dog.drop() >>> db.person.drop() Example of many 2 many relation and Set >>> tmp = db.define_table('author', Field('name'),\ migrate='test_author.table') >>> tmp = db.define_table('paper', Field('title'),\ migrate='test_paper.table') >>> tmp = db.define_table('authorship',\ Field('author_id', db.author),\ Field('paper_id', db.paper),\ migrate='test_authorship.table') >>> aid = db.author.insert(name='Massimo') >>> pid = db.paper.insert(title='QCD') >>> tmp = db.authorship.insert(author_id=aid, paper_id=pid) Define a Set >>> authored_papers = db((db.author.id==db.authorship.author_id)&(db.paper.id==db.authorship.paper_id)) >>> rows = authored_papers.select(db.author.name, db.paper.title) >>> for row in rows: print row.author.name, row.paper.title Massimo QCD Example of search condition using belongs >>> set = (1, 2, 3) >>> rows = db(db.paper.id.belongs(set)).select(db.paper.ALL) >>> print rows[0].title QCD Example of search condition using nested select >>> nested_select = db()._select(db.authorship.paper_id) >>> rows = db(db.paper.id.belongs(nested_select)).select(db.paper.ALL) >>> print rows[0].title QCD Example of expressions >>> mynumber = db.define_table('mynumber', Field('x', 'integer')) >>> db(mynumber.id>0).delete() 0 >>> for i in range(10): tmp = mynumber.insert(x=i) >>> db(mynumber.id>0).select(mynumber.x.sum())[0](mynumber.x.sum()) 45 >>> db(mynumber.x+2==5).select(mynumber.x + 2)[0](mynumber.x + 2) 5 Output in csv >>> print str(authored_papers.select(db.author.name, db.paper.title)).strip() author.name,paper.title\r Massimo,QCD Delete all leftover tables >>> DAL.distributed_transaction_commit(db) >>> db.mynumber.drop() >>> db.authorship.drop() >>> db.author.drop() >>> db.paper.drop() """ ################################################################################ # deprecated since the new DAL; here only for backward compatibility ################################################################################ SQLField = Field SQLTable = Table SQLXorable = Expression SQLQuery = Query SQLSet = Set SQLRows = Rows SQLStorage = Row SQLDB = DAL GQLDB = DAL DAL.Field = Field # was necessary in gluon/globals.py session.connect DAL.Table = Table # was necessary in gluon/globals.py session.connect ################################################################################ # run tests ################################################################################ if __name__ == '__main__': import doctest doctest.testmod()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- import __builtin__ import os import re import sys import threading # Install the new import function: def custom_import_install(web2py_path): global _web2py_importer global _web2py_path if _web2py_importer: return # Already installed _web2py_path = web2py_path _web2py_importer = _Web2pyImporter(web2py_path) __builtin__.__import__ = _web2py_importer def is_tracking_changes(): """ @return: True: neo_importer is tracking changes made to Python source files. False: neo_import does not reload Python modules. """ global _is_tracking_changes return _is_tracking_changes def track_changes(track=True): """ Tell neo_importer to start/stop tracking changes made to Python modules. @param track: True: Start tracking changes. False: Stop tracking changes. """ global _is_tracking_changes global _web2py_importer global _web2py_date_tracker_importer assert track is True or track is False, "Boolean expected." if track == _is_tracking_changes: return if track: if not _web2py_date_tracker_importer: _web2py_date_tracker_importer = \ _Web2pyDateTrackerImporter(_web2py_path) __builtin__.__import__ = _web2py_date_tracker_importer else: __builtin__.__import__ = _web2py_importer _is_tracking_changes = track _STANDARD_PYTHON_IMPORTER = __builtin__.__import__ # Keep standard importer _web2py_importer = None # The standard web2py importer _web2py_date_tracker_importer = None # The web2py importer with date tracking _web2py_path = None # Absolute path of the web2py directory _is_tracking_changes = False # The tracking mode class _BaseImporter(object): """ The base importer. Dispatch the import the call to the standard Python importer. """ def begin(self): """ Many imports can be made for a single import statement. This method help the management of this aspect. """ def __call__(self, name, globals={}, locals={}, fromlist=[], level=-1): """ The import method itself. """ return _STANDARD_PYTHON_IMPORTER(name, globals, locals, fromlist, level) def end(self): """ Needed for clean up. """ class _DateTrackerImporter(_BaseImporter): """ An importer tracking the date of the module files and reloading them when they have changed. """ _PACKAGE_PATH_SUFFIX = os.path.sep+"__init__.py" def __init__(self): super(_DateTrackerImporter, self).__init__() self._import_dates = {} # Import dates of the files of the modules # Avoid reloading cause by file modifications of reload: self._tl = threading.local() self._tl._modules_loaded = None def begin(self): self._tl._modules_loaded = set() def __call__(self, name, globals={}, locals={}, fromlist=[], level=-1): """ The import method itself. """ call_begin_end = self._tl._modules_loaded == None if call_begin_end: self.begin() try: self._tl.globals = globals self._tl.locals = locals self._tl.level = level # Check the date and reload if needed: self._update_dates(name, fromlist) # Try to load the module and update the dates if it works: result = super(_DateTrackerImporter, self) \ .__call__(name, globals, locals, fromlist, level) # Module maybe loaded for the 1st time so we need to set the date self._update_dates(name, fromlist) return result except Exception, e: raise e # Don't hide something that went wrong finally: if call_begin_end: self.end() def _update_dates(self, name, fromlist): """ Update all the dates associated to the statement import. A single import statement may import many modules. """ self._reload_check(name) if fromlist: for fromlist_name in fromlist: self._reload_check("%s.%s" % (name, fromlist_name)) def _reload_check(self, name): """ Update the date associated to the module and reload the module if the file has changed. """ module = sys.modules.get(name) file = self._get_module_file(module) if file: date = self._import_dates.get(file) new_date = None reload_mod = False mod_to_pack = False # Module turning into a package? (special case) try: new_date = os.path.getmtime(file) except: self._import_dates.pop(file, None) # Clean up # Handle module changing in package and #package changing in module: if file.endswith(".py"): # Get path without file ext: file = os.path.splitext(file)[0] reload_mod = os.path.isdir(file) \ and os.path.isfile(file+self._PACKAGE_PATH_SUFFIX) mod_to_pack = reload_mod else: # Package turning into module? file += ".py" reload_mod = os.path.isfile(file) if reload_mod: new_date = os.path.getmtime(file) # Refresh file date if reload_mod or not date or new_date > date: self._import_dates[file] = new_date if reload_mod or (date and new_date > date): if module not in self._tl._modules_loaded: if mod_to_pack: # Module turning into a package: mod_name = module.__name__ del sys.modules[mod_name] # Delete the module # Reload the module: super(_DateTrackerImporter, self).__call__ \ (mod_name, self._tl.globals, self._tl.locals, [], self._tl.level) else: reload(module) self._tl._modules_loaded.add(module) def end(self): self._tl._modules_loaded = None @classmethod def _get_module_file(cls, module): """ Get the absolute path file associated to the module or None. """ file = getattr(module, "__file__", None) if file: # Make path absolute if not: #file = os.path.join(cls.web2py_path, file) file = os.path.splitext(file)[0]+".py" # Change .pyc for .py if file.endswith(cls._PACKAGE_PATH_SUFFIX): file = os.path.dirname(file) # Track dir for packages return file class _Web2pyImporter(_BaseImporter): """ The standard web2py importer. Like the standard Python importer but it tries to transform import statements as something like "import applications.app_name.modules.x". If the import failed, fall back on _BaseImporter. """ _RE_ESCAPED_PATH_SEP = re.escape(os.path.sep) # os.path.sep escaped for re def __init__(self, web2py_path): """ @param web2py_path: The absolute path of the web2py installation. """ global DEBUG super(_Web2pyImporter, self).__init__() self.web2py_path = web2py_path self.__web2py_path_os_path_sep = self.web2py_path+os.path.sep self.__web2py_path_os_path_sep_len = len(self.__web2py_path_os_path_sep) self.__RE_APP_DIR = re.compile( self._RE_ESCAPED_PATH_SEP.join( \ ( \ #"^" + re.escape(web2py_path), # Not working with Python 2.5 "^(" + "applications", "[^", "]+)", "", ) )) def _matchAppDir(self, file_path): """ Does the file in a directory inside the "applications" directory? """ if file_path.startswith(self.__web2py_path_os_path_sep): file_path = file_path[self.__web2py_path_os_path_sep_len:] return self.__RE_APP_DIR.match(file_path) return False def __call__(self, name, globals={}, locals={}, fromlist=[], level=-1): """ The import method itself. """ self.begin() #try: # if not relative and not from applications: if not name.startswith(".") and level <= 0 \ and not name.startswith("applications.") \ and isinstance(globals, dict): # Get the name of the file do the import caller_file_name = os.path.join(self.web2py_path, \ globals.get("__file__", "")) # Is the path in an application directory? match_app_dir = self._matchAppDir(caller_file_name) if match_app_dir: try: # Get the prefix to add for the import # (like applications.app_name.modules): modules_prefix = \ ".".join((match_app_dir.group(1). \ replace(os.path.sep, "."), "modules")) if not fromlist: # import like "import x" or "import x.y" return self.__import__dot(modules_prefix, name, globals, locals, fromlist, level) else: # import like "from x import a, b, ..." return super(_Web2pyImporter, self) \ .__call__(modules_prefix+"."+name, globals, locals, fromlist, level) except ImportError: pass return super(_Web2pyImporter, self).__call__(name, globals, locals, fromlist, level) #except Exception, e: # raise e # Don't hide something that went wrong #finally: self.end() def __import__dot(self, prefix, name, globals, locals, fromlist, level): """ Here we will import x.y.z as many imports like: from applications.app_name.modules import x from applications.app_name.modules.x import y from applications.app_name.modules.x.y import z. x will be the module returned. """ result = None for name in name.split("."): new_mod = super(_Web2pyImporter, self).__call__(prefix, globals, locals, [name], level) try: result = result or new_mod.__dict__[name] except KeyError: raise ImportError() prefix += "." + name return result class _Web2pyDateTrackerImporter(_Web2pyImporter, _DateTrackerImporter): """ Like _Web2pyImporter but using a _DateTrackerImporter. """
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) Basic caching classes and methods ================================= - Cache - The generic caching object interfacing with the others - CacheInRam - providing caching in ram - CacheInDisk - provides caches on disk Memcache is also available via a different module (see gluon.contrib.memcache) When web2py is running on Google App Engine, caching will be provided by the GAE memcache (see gluon.contrib.gae_memcache) """ import time import portalocker import shelve import thread import os import logging import re logger = logging.getLogger("web2py.cache") __all__ = ['Cache'] DEFAULT_TIME_EXPIRE = 300 class CacheAbstract(object): """ Abstract class for cache implementations. Main function is now to provide referenced api documentation. Use CacheInRam or CacheOnDisk instead which are derived from this class. """ cache_stats_name = 'web2py_cache_statistics' def __init__(self, request=None): """ Paremeters ---------- request: the global request object """ raise NotImplementedError def __call__(self, key, f, time_expire = DEFAULT_TIME_EXPIRE): """ Tries retrieve the value corresponding to `key` from the cache of the object exists and if it did not expire, else it called the function `f` and stores the output in the cache corresponding to `key`. In the case the output of the function is returned. :param key: the key of the object to be store or retrieved :param f: the function, whose output is to be cached :param time_expire: expiration of the cache in microseconds - `time_expire` is used to compare the current time with the time when the requested object was last saved in cache. It does not affect future requests. - Setting `time_expire` to 0 or negative value forces the cache to refresh. If the function `f` is `None` the cache is cleared. """ raise NotImplementedError def clear(self, regex=None): """ Clears the cache of all keys that match the provided regular expression. If no regular expression is provided, it clears all entries in cache. Parameters ---------- regex: if provided, only keys matching the regex will be cleared. Otherwise all keys are cleared. """ raise NotImplementedError def increment(self, key, value=1): """ Increments the cached value for the given key by the amount in value Parameters ---------- key: key for the cached object to be incremeneted value: amount of the increment (defaults to 1, can be negative) """ raise NotImplementedError def _clear(self, storage, regex): """ Auxiliary function called by `clear` to search and clear cache entries """ r = re.compile(regex) for (key, value) in storage.items(): if r.match(str(key)): del storage[key] class CacheInRam(CacheAbstract): """ Ram based caching This is implemented as global (per process, shared by all threads) dictionary. A mutex-lock mechanism avoid conflicts. """ locker = thread.allocate_lock() meta_storage = {} def __init__(self, request=None): self.locker.acquire() self.request = request if request: app = request.application else: app = '' if not app in self.meta_storage: self.storage = self.meta_storage[app] = {CacheAbstract.cache_stats_name: { 'hit_total': 0, 'misses': 0, }} else: self.storage = self.meta_storage[app] self.locker.release() def clear(self, regex=None): self.locker.acquire() storage = self.storage if regex == None: storage.clear() else: self._clear(storage, regex) if not CacheAbstract.cache_stats_name in storage.keys(): storage[CacheAbstract.cache_stats_name] = { 'hit_total': 0, 'misses': 0, } self.locker.release() def __call__(self, key, f, time_expire = DEFAULT_TIME_EXPIRE): """ Attention! cache.ram does not copy the cached object. It just stores a reference to it. Turns out the deepcopying the object has some problems: 1) would break backward compatibility 2) would be limiting because people may want to cache live objects 3) would work unless we deepcopy no storage and retrival which would make things slow. Anyway. You can deepcopy explicitly in the function generating the value to be cached. """ dt = time_expire self.locker.acquire() item = self.storage.get(key, None) if item and f == None: del self.storage[key] self.storage[CacheAbstract.cache_stats_name]['hit_total'] += 1 self.locker.release() if f is None: return None if item and (dt == None or item[0] > time.time() - dt): return item[1] value = f() self.locker.acquire() self.storage[key] = (time.time(), value) self.storage[CacheAbstract.cache_stats_name]['misses'] += 1 self.locker.release() return value def increment(self, key, value=1): self.locker.acquire() try: if key in self.storage: value = self.storage[key][1] + value self.storage[key] = (time.time(), value) except BaseException, e: self.locker.release() raise e self.locker.release() return value class CacheOnDisk(CacheAbstract): """ Disk based cache This is implemented as a shelve object and it is shared by multiple web2py processes (and threads) as long as they share the same filesystem. The file is locked wen accessed. Disk cache provides persistance when web2py is started/stopped but it slower than `CacheInRam` Values stored in disk cache must be pickable. """ speedup_checks = set() def __init__(self, request, folder=None): self.request = request # Lets test if the cache folder exists, if not # we are going to create it folder = folder or os.path.join(request.folder, 'cache') if not os.path.exists(folder): os.mkdir(folder) ### we need this because of a possible bug in shelve that may ### or may not lock self.locker_name = os.path.join(folder,'cache.lock') self.shelve_name = os.path.join(folder,'cache.shelve') locker, locker_locked = None, False speedup_key = (folder,CacheAbstract.cache_stats_name) if not speedup_key in self.speedup_checks or \ not os.path.exists(self.shelve_name): try: locker = open(self.locker_name, 'a') portalocker.lock(locker, portalocker.LOCK_EX) locker_locked = True storage = shelve.open(self.shelve_name) try: if not storage.has_key(CacheAbstract.cache_stats_name): storage[CacheAbstract.cache_stats_name] = { 'hit_total': 0, 'misses': 0, } storage.sync() finally: storage.close() self.speedup_checks.add(speedup_key) except ImportError: pass # no module _bsddb, ignoring exception now so it makes a ticket only if used except: logger.error('corrupted file %s, will try delete it!' \ % self.shelve_name) try: os.unlink(self.shelve_name) except IOError: logger.warn('unable to delete file %s' % self.shelve_name) if locker_locked: portalocker.unlock(locker) if locker: locker.close() def clear(self, regex=None): locker = open(self.locker_name,'a') portalocker.lock(locker, portalocker.LOCK_EX) storage = shelve.open(self.shelve_name) try: if regex == None: storage.clear() else: self._clear(storage, regex) if not CacheAbstract.cache_stats_name in storage.keys(): storage[CacheAbstract.cache_stats_name] = { 'hit_total': 0, 'misses': 0, } storage.sync() finally: storage.close() portalocker.unlock(locker) locker.close() def __call__(self, key, f, time_expire = DEFAULT_TIME_EXPIRE): dt = time_expire locker = open(self.locker_name,'a') portalocker.lock(locker, portalocker.LOCK_EX) storage = shelve.open(self.shelve_name) item = storage.get(key, None) if item and f == None: del storage[key] storage[CacheAbstract.cache_stats_name] = { 'hit_total': storage[CacheAbstract.cache_stats_name]['hit_total'] + 1, 'misses': storage[CacheAbstract.cache_stats_name]['misses'] } storage.sync() portalocker.unlock(locker) locker.close() if f is None: return None if item and (dt == None or item[0] > time.time() - dt): return item[1] value = f() locker = open(self.locker_name,'a') portalocker.lock(locker, portalocker.LOCK_EX) storage[key] = (time.time(), value) storage[CacheAbstract.cache_stats_name] = { 'hit_total': storage[CacheAbstract.cache_stats_name]['hit_total'], 'misses': storage[CacheAbstract.cache_stats_name]['misses'] + 1 } storage.sync() storage.close() portalocker.unlock(locker) locker.close() return value def increment(self, key, value=1): locker = open(self.locker_name,'a') portalocker.lock(locker, portalocker.LOCK_EX) storage = shelve.open(self.shelve_name) try: if key in storage: value = storage[key][1] + value storage[key] = (time.time(), value) storage.sync() finally: storage.close() portalocker.unlock(locker) locker.close() return value class Cache(object): """ Sets up generic caching, creating an instance of both CacheInRam and CacheOnDisk. In case of GAE will make use of gluon.contrib.gae_memcache. - self.ram is an instance of CacheInRam - self.disk is an instance of CacheOnDisk """ def __init__(self, request): """ Parameters ---------- request: the global request object """ # GAE will have a special caching import settings if settings.global_settings.web2py_runtime_gae: from contrib.gae_memcache import MemcacheClient self.ram=self.disk=MemcacheClient(request) else: # Otherwise use ram (and try also disk) self.ram = CacheInRam(request) try: self.disk = CacheOnDisk(request) except IOError: logger.warning('no cache.disk (IOError)') except AttributeError: # normally not expected anymore, as GAE has already # been accounted for logger.warning('no cache.disk (AttributeError)') def __call__(self, key = None, time_expire = DEFAULT_TIME_EXPIRE, cache_model = None): """ Decorator function that can be used to cache any function/method. Example:: @cache('key', 5000, cache.ram) def f(): return time.ctime() When the function f is called, web2py tries to retrieve the value corresponding to `key` from the cache of the object exists and if it did not expire, else it calles the function `f` and stores the output in the cache corresponding to `key`. In the case the output of the function is returned. :param key: the key of the object to be store or retrieved :param time_expire: expiration of the cache in microseconds :param cache_model: `cache.ram`, `cache.disk`, or other (like `cache.memcache` if defined). It defaults to `cache.ram`. Notes ----- `time_expire` is used to compare the curret time with the time when the requested object was last saved in cache. It does not affect future requests. Setting `time_expire` to 0 or negative value forces the cache to refresh. If the function `f` is an action, we suggest using `request.env.path_info` as key. """ if not cache_model: cache_model = self.ram def tmp(func): def action(): return cache_model(key, func, time_expire) action.__name___ = func.__name__ action.__doc__ = func.__doc__ return action return tmp
Python
#!/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) Contains: - wsgibase: the gluon wsgi application """ import gc import cgi import cStringIO import Cookie import os import re import copy import sys import time import thread import datetime import signal import socket import tempfile import random import string import platform from fileutils import abspath, write_file from settings import global_settings from admin import add_path_first, create_missing_folders, create_missing_app_folders from globals import current from custom_import import custom_import_install from contrib.simplejson import dumps # Remarks: # calling script has inserted path to script directory into sys.path # applications_parent (path to applications/, site-packages/ etc) # defaults to that directory set sys.path to # ("", gluon_parent/site-packages, gluon_parent, ...) # # this is wrong: # web2py_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # because we do not want the path to this file which may be Library.zip # gluon_parent is the directory containing gluon, web2py.py, logging.conf # and the handlers. # applications_parent (web2py_path) is the directory containing applications/ # and routes.py # The two are identical unless web2py_path is changed via the web2py.py -f folder option # main.web2py_path is the same as applications_parent (for backward compatibility) if not hasattr(os, 'mkdir'): global_settings.db_sessions = True if global_settings.db_sessions is not True: global_settings.db_sessions = set() global_settings.gluon_parent = os.environ.get('web2py_path', os.getcwd()) global_settings.applications_parent = global_settings.gluon_parent web2py_path = global_settings.applications_parent # backward compatibility global_settings.app_folders = set() global_settings.debugging = False custom_import_install(web2py_path) create_missing_folders() # set up logging for subsequent imports import logging import logging.config logpath = abspath("logging.conf") if os.path.exists(logpath): logging.config.fileConfig(abspath("logging.conf")) else: logging.basicConfig() logger = logging.getLogger("web2py") from restricted import RestrictedError from http import HTTP, redirect from globals import Request, Response, Session from compileapp import build_environment, run_models_in, \ run_controller_in, run_view_in from fileutils import copystream from contenttype import contenttype from dal import BaseAdapter from settings import global_settings from validators import CRYPT from cache import Cache from html import URL as Url import newcron import rewrite __all__ = ['wsgibase', 'save_password', 'appfactory', 'HttpServer'] requests = 0 # gc timer # Security Checks: validate URL and session_id here, # accept_language is validated in languages # pattern used to validate client address regex_client = re.compile('[\w\-:]+(\.[\w\-]+)*\.?') # ## to account for IPV6 version_info = open(abspath('VERSION', gluon=True), 'r') web2py_version = version_info.read() version_info.close() try: import rocket except: if not global_settings.web2py_runtime_gae: logger.warn('unable to import Rocket') rewrite.load() def get_client(env): """ guess the client address from the environment variables first tries 'http_x_forwarded_for', secondly 'remote_addr' if all fails assume '127.0.0.1' (running locally) """ g = regex_client.search(env.get('http_x_forwarded_for', '')) if g: return g.group() g = regex_client.search(env.get('remote_addr', '')) if g: return g.group() return '127.0.0.1' def copystream_progress(request, chunk_size= 10**5): """ copies request.env.wsgi_input into request.body and stores progress upload status in cache.ram X-Progress-ID:length and X-Progress-ID:uploaded """ if not request.env.content_length: return cStringIO.StringIO() source = request.env.wsgi_input size = int(request.env.content_length) dest = tempfile.TemporaryFile() if not 'X-Progress-ID' in request.vars: copystream(source, dest, size, chunk_size) return dest cache_key = 'X-Progress-ID:'+request.vars['X-Progress-ID'] cache = Cache(request) cache.ram(cache_key+':length', lambda: size, 0) cache.ram(cache_key+':uploaded', lambda: 0, 0) while size > 0: if size < chunk_size: data = source.read(size) cache.ram.increment(cache_key+':uploaded', size) else: data = source.read(chunk_size) cache.ram.increment(cache_key+':uploaded', chunk_size) length = len(data) if length > size: (data, length) = (data[:size], size) size -= length if length == 0: break dest.write(data) if length < chunk_size: break dest.seek(0) cache.ram(cache_key+':length', None) cache.ram(cache_key+':uploaded', None) return dest def serve_controller(request, response, session): """ this function is used to generate a dynamic page. It first runs all models, then runs the function in the controller, and then tries to render the output using a view/template. this function must run from the [application] folder. A typical example would be the call to the url /[application]/[controller]/[function] that would result in a call to [function]() in applications/[application]/[controller].py rendered by applications/[application]/views/[controller]/[function].html """ # ################################################## # build environment for controller and view # ################################################## environment = build_environment(request, response, session) # set default view, controller can override it response.view = '%s/%s.%s' % (request.controller, request.function, request.extension) # also, make sure the flash is passed through # ################################################## # process models, controller and view (if required) # ################################################## run_models_in(environment) response._view_environment = copy.copy(environment) page = run_controller_in(request.controller, request.function, environment) if isinstance(page, dict): response._vars = page for key in page: response._view_environment[key] = page[key] run_view_in(response._view_environment) page = response.body.getvalue() # logic to garbage collect after exec, not always, once every 100 requests global requests requests = ('requests' in globals()) and (requests+1) % 100 or 0 if not requests: gc.collect() # end garbage collection logic raise HTTP(response.status, page, **response.headers) def start_response_aux(status, headers, exc_info, response=None): """ in controller you can use:: - request.wsgi.environ - request.wsgi.start_response to call third party WSGI applications """ response.status = str(status).split(' ',1)[0] response.headers = dict(headers) return lambda *args, **kargs: response.write(escape=False,*args,**kargs) def middleware_aux(request, response, *middleware_apps): """ In you controller use:: @request.wsgi.middleware(middleware1, middleware2, ...) to decorate actions with WSGI middleware. actions must return strings. uses a simulated environment so it may have weird behavior in some cases """ def middleware(f): def app(environ, start_response): data = f() start_response(response.status,response.headers.items()) if isinstance(data,list): return data return [data] for item in middleware_apps: app=item(app) def caller(app): return app(request.wsgi.environ,request.wsgi.start_response) return lambda caller=caller, app=app: caller(app) return middleware def environ_aux(environ,request): new_environ = copy.copy(environ) new_environ['wsgi.input'] = request.body new_environ['wsgi.version'] = 1 return new_environ def parse_get_post_vars(request, environ): # always parse variables in URL for GET, POST, PUT, DELETE, etc. in get_vars dget = cgi.parse_qsl(request.env.query_string or '', keep_blank_values=1) for (key, value) in dget: if key in request.get_vars: if isinstance(request.get_vars[key], list): request.get_vars[key] += [value] else: request.get_vars[key] = [request.get_vars[key]] + [value] else: request.get_vars[key] = value request.vars[key] = request.get_vars[key] # parse POST variables on POST, PUT, BOTH only in post_vars request.body = copystream_progress(request) ### stores request body if (request.body and request.env.request_method in ('POST', 'PUT', 'BOTH')): dpost = cgi.FieldStorage(fp=request.body,environ=environ,keep_blank_values=1) # The same detection used by FieldStorage to detect multipart POSTs is_multipart = dpost.type[:10] == 'multipart/' request.body.seek(0) isle25 = sys.version_info[1] <= 5 def listify(a): return (not isinstance(a,list) and [a]) or a try: keys = sorted(dpost) except TypeError: keys = [] for key in keys: dpk = dpost[key] # if en element is not a file replace it with its value else leave it alone if isinstance(dpk, list): if not dpk[0].filename: value = [x.value for x in dpk] else: value = [x for x in dpk] elif not dpk.filename: value = dpk.value else: value = dpk pvalue = listify(value) if key in request.vars: gvalue = listify(request.vars[key]) if isle25: value = pvalue + gvalue elif is_multipart: pvalue = pvalue[len(gvalue):] else: pvalue = pvalue[:-len(gvalue)] request.vars[key] = value if len(pvalue): request.post_vars[key] = (len(pvalue)>1 and pvalue) or pvalue[0] def wsgibase(environ, responder): """ this is the gluon wsgi application. the first function called when a page is requested (static or dynamic). it can be called by paste.httpserver or by apache mod_wsgi. - fills request with info - the environment variables, replacing '.' with '_' - adds web2py path and version info - compensates for fcgi missing path_info and query_string - validates the path in url The url path must be either: 1. for static pages: - /<application>/static/<file> 2. for dynamic pages: - /<application>[/<controller>[/<function>[/<sub>]]][.<extension>] - (sub may go several levels deep, currently 3 levels are supported: sub1/sub2/sub3) The naming conventions are: - application, controller, function and extension may only contain [a-zA-Z0-9_] - file and sub may also contain '-', '=', '.' and '/' """ current.__dict__.clear() request = Request() response = Response() session = Session() request.env.web2py_path = global_settings.applications_parent request.env.web2py_version = web2py_version request.env.update(global_settings) static_file = False try: try: try: # ################################################## # handle fcgi missing path_info and query_string # select rewrite parameters # rewrite incoming URL # parse rewritten header variables # parse rewritten URL # serve file if static # ################################################## if not environ.get('PATH_INFO',None) and \ environ.get('REQUEST_URI',None): # for fcgi, get path_info and query_string from request_uri items = environ['REQUEST_URI'].split('?') environ['PATH_INFO'] = items[0] if len(items) > 1: environ['QUERY_STRING'] = items[1] else: environ['QUERY_STRING'] = '' if not environ.get('HTTP_HOST',None): environ['HTTP_HOST'] = '%s:%s' % (environ.get('SERVER_NAME'), environ.get('SERVER_PORT')) (static_file, environ) = rewrite.url_in(request, environ) if static_file: if request.env.get('query_string', '')[:10] == 'attachment': response.headers['Content-Disposition'] = 'attachment' response.stream(static_file, request=request) # ################################################## # fill in request items # ################################################## http_host = request.env.http_host.split(':',1)[0] local_hosts = [http_host,'::1','127.0.0.1','::ffff:127.0.0.1'] if not global_settings.web2py_runtime_gae: local_hosts += [socket.gethostname(), socket.gethostbyname(http_host)] request.client = get_client(request.env) request.folder = abspath('applications', request.application) + os.sep x_req_with = str(request.env.http_x_requested_with).lower() request.ajax = x_req_with == 'xmlhttprequest' request.cid = request.env.http_web2py_component_element request.is_local = request.env.remote_addr in local_hosts request.is_https = request.env.wsgi_url_scheme \ in ['https', 'HTTPS'] or request.env.https == 'on' # ################################################## # compute a request.uuid to be used for tickets and toolbar # ################################################## response.uuid = request.compute_uuid() # ################################################## # access the requested application # ################################################## if not os.path.exists(request.folder): if request.application == rewrite.thread.routes.default_application and request.application != 'welcome': request.application = 'welcome' redirect(Url(r=request)) elif rewrite.thread.routes.error_handler: redirect(Url(rewrite.thread.routes.error_handler['application'], rewrite.thread.routes.error_handler['controller'], rewrite.thread.routes.error_handler['function'], args=request.application)) else: raise HTTP(404, rewrite.thread.routes.error_message % 'invalid request', web2py_error='invalid application') request.url = Url(r=request, args=request.args, extension=request.raw_extension) # ################################################## # build missing folders # ################################################## create_missing_app_folders(request) # ################################################## # get the GET and POST data # ################################################## parse_get_post_vars(request, environ) # ################################################## # expose wsgi hooks for convenience # ################################################## request.wsgi.environ = environ_aux(environ,request) request.wsgi.start_response = lambda status='200', headers=[], \ exec_info=None, response=response: \ start_response_aux(status, headers, exec_info, response) request.wsgi.middleware = lambda *a: middleware_aux(request,response,*a) # ################################################## # load cookies # ################################################## if request.env.http_cookie: try: request.cookies.load(request.env.http_cookie) except Cookie.CookieError, e: pass # invalid cookies # ################################################## # try load session or create new session file # ################################################## session.connect(request, response) # ################################################## # set no-cache headers # ################################################## response.headers['Content-Type'] = contenttype('.'+request.extension) response.headers['Cache-Control'] = \ 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0' response.headers['Expires'] = \ time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime()) response.headers['Pragma'] = 'no-cache' # ################################################## # run controller # ################################################## serve_controller(request, response, session) except HTTP, http_response: if static_file: return http_response.to(responder) if request.body: request.body.close() # ################################################## # on success, try store session in database # ################################################## session._try_store_in_db(request, response) # ################################################## # on success, commit database # ################################################## if response._custom_commit: response._custom_commit() else: BaseAdapter.close_all_instances('commit') # ################################################## # if session not in db try store session on filesystem # this must be done after trying to commit database! # ################################################## session._try_store_on_disk(request, response) # ################################################## # store cookies in headers # ################################################## if request.cid: if response.flash and not 'web2py-component-flash' in http_response.headers: http_response.headers['web2py-component-flash'] = \ str(response.flash).replace('\n','') if response.js and not 'web2py-component-command' in http_response.headers: http_response.headers['web2py-component-command'] = \ response.js.replace('\n','') if session._forget and \ response.session_id_name in response.cookies: del response.cookies[response.session_id_name] elif session._secure: response.cookies[response.session_id_name]['secure'] = True if len(response.cookies)>0: http_response.headers['Set-Cookie'] = \ [str(cookie)[11:] for cookie in response.cookies.values()] ticket=None except RestrictedError, e: if request.body: request.body.close() # ################################################## # on application error, rollback database # ################################################## ticket = e.log(request) or 'unknown' if response._custom_rollback: response._custom_rollback() else: BaseAdapter.close_all_instances('rollback') http_response = \ HTTP(500, rewrite.thread.routes.error_message_ticket % dict(ticket=ticket), web2py_error='ticket %s' % ticket) except: if request.body: request.body.close() # ################################################## # on application error, rollback database # ################################################## try: if response._custom_rollback: response._custom_rollback() else: BaseAdapter.close_all_instances('rollback') except: pass e = RestrictedError('Framework', '', '', locals()) ticket = e.log(request) or 'unrecoverable' http_response = \ HTTP(500, rewrite.thread.routes.error_message_ticket % dict(ticket=ticket), web2py_error='ticket %s' % ticket) finally: if response and hasattr(response, 'session_file') and response.session_file: response.session_file.close() # if global_settings.debugging: # import gluon.debug # gluon.debug.stop_trace() session._unlock(response) http_response, new_environ = rewrite.try_rewrite_on_error( http_response, request, environ, ticket) if not http_response: return wsgibase(new_environ,responder) if global_settings.web2py_crontype == 'soft': newcron.softcron(global_settings.applications_parent).start() return http_response.to(responder) def save_password(password, port): """ used by main() to save the password in the parameters_port.py file. """ password_file = abspath('parameters_%i.py' % port) if password == '<random>': # make up a new password chars = string.letters + string.digits password = ''.join([random.choice(chars) for i in range(8)]) cpassword = CRYPT()(password)[0] print '******************* IMPORTANT!!! ************************' print 'your admin password is "%s"' % password print '*********************************************************' elif password == '<recycle>': # reuse the current password if any if os.path.exists(password_file): return else: password = '' elif password.startswith('<pam_user:'): # use the pam password for specified user cpassword = password[1:-1] else: # use provided password cpassword = CRYPT()(password)[0] fp = open(password_file, 'w') if password: fp.write('password="%s"\n' % cpassword) else: fp.write('password=None\n') fp.close() def appfactory(wsgiapp=wsgibase, logfilename='httpserver.log', profilerfilename='profiler.log'): """ generates a wsgi application that does logging and profiling and calls wsgibase .. function:: gluon.main.appfactory( [wsgiapp=wsgibase [, logfilename='httpserver.log' [, profilerfilename='profiler.log']]]) """ if profilerfilename and os.path.exists(profilerfilename): os.unlink(profilerfilename) locker = thread.allocate_lock() def app_with_logging(environ, responder): """ a wsgi app that does logging and profiling and calls wsgibase """ status_headers = [] def responder2(s, h): """ wsgi responder app """ status_headers.append(s) status_headers.append(h) return responder(s, h) time_in = time.time() ret = [0] if not profilerfilename: ret[0] = wsgiapp(environ, responder2) else: import cProfile import pstats logger.warn('profiler is on. this makes web2py slower and serial') locker.acquire() cProfile.runctx('ret[0] = wsgiapp(environ, responder2)', globals(), locals(), profilerfilename+'.tmp') stat = pstats.Stats(profilerfilename+'.tmp') stat.stream = cStringIO.StringIO() stat.strip_dirs().sort_stats("time").print_stats(80) profile_out = stat.stream.getvalue() profile_file = open(profilerfilename, 'a') profile_file.write('%s\n%s\n%s\n%s\n\n' % \ ('='*60, environ['PATH_INFO'], '='*60, profile_out)) profile_file.close() locker.release() try: line = '%s, %s, %s, %s, %s, %s, %f\n' % ( environ['REMOTE_ADDR'], datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S'), environ['REQUEST_METHOD'], environ['PATH_INFO'].replace(',', '%2C'), environ['SERVER_PROTOCOL'], (status_headers[0])[:3], time.time() - time_in, ) if not logfilename: sys.stdout.write(line) elif isinstance(logfilename, str): write_file(logfilename, line, 'a') else: logfilename.write(line) except: pass return ret[0] return app_with_logging class HttpServer(object): """ the web2py web server (Rocket) """ def __init__( self, ip='127.0.0.1', port=8000, password='', pid_filename='httpserver.pid', log_filename='httpserver.log', profiler_filename=None, ssl_certificate=None, ssl_private_key=None, min_threads=None, max_threads=None, server_name=None, request_queue_size=5, timeout=10, shutdown_timeout=None, # Rocket does not use a shutdown timeout path=None, interfaces=None # Rocket is able to use several interfaces - must be list of socket-tuples as string ): """ starts the web server. """ if interfaces: # if interfaces is specified, it must be tested for rocket parameter correctness # not necessarily completely tested (e.g. content of tuples or ip-format) import types if isinstance(interfaces,types.ListType): for i in interfaces: if not isinstance(i,types.TupleType): raise "Wrong format for rocket interfaces parameter - see http://packages.python.org/rocket/" else: raise "Wrong format for rocket interfaces parameter - see http://packages.python.org/rocket/" if path: # if a path is specified change the global variables so that web2py # runs from there instead of cwd or os.environ['web2py_path'] global web2py_path path = os.path.normpath(path) web2py_path = path global_settings.applications_parent = path os.chdir(path) [add_path_first(p) for p in (path, abspath('site-packages'), "")] save_password(password, port) self.pid_filename = pid_filename if not server_name: server_name = socket.gethostname() logger.info('starting web server...') rocket.SERVER_NAME = server_name sock_list = [ip, port] if not ssl_certificate or not ssl_private_key: logger.info('SSL is off') elif not rocket.ssl: logger.warning('Python "ssl" module unavailable. SSL is OFF') elif not os.path.exists(ssl_certificate): logger.warning('unable to open SSL certificate. SSL is OFF') elif not os.path.exists(ssl_private_key): logger.warning('unable to open SSL private key. SSL is OFF') else: sock_list.extend([ssl_private_key, ssl_certificate]) logger.info('SSL is ON') app_info = {'wsgi_app': appfactory(wsgibase, log_filename, profiler_filename) } self.server = rocket.Rocket(interfaces or tuple(sock_list), method='wsgi', app_info=app_info, min_threads=min_threads, max_threads=max_threads, queue_size=int(request_queue_size), timeout=int(timeout), handle_signals=False, ) def start(self): """ start the web server """ try: signal.signal(signal.SIGTERM, lambda a, b, s=self: s.stop()) signal.signal(signal.SIGINT, lambda a, b, s=self: s.stop()) except: pass write_file(self.pid_filename, str(os.getpid())) self.server.start() def stop(self, stoplogging=False): """ stop cron and the web server """ newcron.stopcron() self.server.stop(stoplogging) try: os.unlink(self.pid_filename) except: pass
Python
# this file exists for backward compatibility __all__ = ['DAL','Field','drivers'] from dal import DAL, Field, Table, Query, Set, Expression, Row, Rows, drivers, BaseAdapter, SQLField, SQLTable, SQLXorable, SQLQuery, SQLSet, SQLRows, SQLStorage, SQLDB, GQLDB, SQLALL, SQLCustomType
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ :: # from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496942 # Title: Cross-site scripting (XSS) defense # Submitter: Josh Goldfoot (other recipes) # Last Updated: 2006/08/05 # Version no: 1.0 """ from htmllib import HTMLParser from cgi import escape from urlparse import urlparse from formatter import AbstractFormatter from htmlentitydefs import entitydefs from xml.sax.saxutils import quoteattr __all__ = ['sanitize'] def xssescape(text): """Gets rid of < and > and & and, for good measure, :""" return escape(text, quote=True).replace(':', '&#58;') class XssCleaner(HTMLParser): def __init__( self, permitted_tags=[ 'a', 'b', 'blockquote', 'br/', 'i', 'li', 'ol', 'ul', 'p', 'cite', 'code', 'pre', 'img/', ], allowed_attributes={'a': ['href', 'title'], 'img': ['src', 'alt' ], 'blockquote': ['type']}, fmt=AbstractFormatter, strip_disallowed = False ): HTMLParser.__init__(self, fmt) self.result = '' self.open_tags = [] self.permitted_tags = [i for i in permitted_tags if i[-1] != '/'] self.requires_no_close = [i[:-1] for i in permitted_tags if i[-1] == '/'] self.permitted_tags += self.requires_no_close self.allowed_attributes = allowed_attributes # The only schemes allowed in URLs (for href and src attributes). # Adding "javascript" or "vbscript" to this list would not be smart. self.allowed_schemes = ['http', 'https', 'ftp'] #to strip or escape disallowed tags? self.strip_disallowed = strip_disallowed self.in_disallowed = False def handle_data(self, data): if data and not self.in_disallowed: self.result += xssescape(data) def handle_charref(self, ref): if self.in_disallowed: return elif len(ref) < 7 and ref.isdigit(): self.result += '&#%s;' % ref else: self.result += xssescape('&#%s' % ref) def handle_entityref(self, ref): if self.in_disallowed: return elif ref in entitydefs: self.result += '&%s;' % ref else: self.result += xssescape('&%s' % ref) def handle_comment(self, comment): if self.in_disallowed: return elif comment: self.result += xssescape('<!--%s-->' % comment) def handle_starttag( self, tag, method, attrs, ): if tag not in self.permitted_tags: if self.strip_disallowed: self.in_disallowed = True else: self.result += xssescape('<%s>' % tag) else: bt = '<' + tag if tag in self.allowed_attributes: attrs = dict(attrs) self.allowed_attributes_here = [x for x in self.allowed_attributes[tag] if x in attrs and len(attrs[x]) > 0] for attribute in self.allowed_attributes_here: if attribute in ['href', 'src', 'background']: if self.url_is_acceptable(attrs[attribute]): bt += ' %s="%s"' % (attribute, attrs[attribute]) else: bt += ' %s=%s' % (xssescape(attribute), quoteattr(attrs[attribute])) if bt == '<a' or bt == '<img': return if tag in self.requires_no_close: bt += ' /' bt += '>' self.result += bt self.open_tags.insert(0, tag) def handle_endtag(self, tag, attrs): bracketed = '</%s>' % tag if tag not in self.permitted_tags: if self.strip_disallowed: self.in_disallowed = False else: self.result += xssescape(bracketed) elif tag in self.open_tags: self.result += bracketed self.open_tags.remove(tag) def unknown_starttag(self, tag, attributes): self.handle_starttag(tag, None, attributes) def unknown_endtag(self, tag): self.handle_endtag(tag, None) def url_is_acceptable(self, url): """ Accepts relative and absolute urls """ parsed = urlparse(url) return (parsed[0] in self.allowed_schemes and '.' in parsed[1]) \ or (parsed[0] == '' and parsed[2].startswith('/')) def strip(self, rawstring, escape=True): """ Returns the argument stripped of potentially harmful HTML or Javascript code @type escape: boolean @param escape: If True (default) it escapes the potentially harmful content, otherwise remove it """ if not isinstance(rawstring, str): return str(rawstring) for tag in self.requires_no_close: rawstring = rawstring.replace("<%s/>" % tag, "<%s />" % tag) if not escape: self.strip_disallowed = True self.result = '' self.feed(rawstring) for endtag in self.open_tags: if endtag not in self.requires_no_close: self.result += '</%s>' % endtag return self.result def xtags(self): """ Returns a printable string informing the user which tags are allowed """ tg = '' for x in sorted(self.permitted_tags): tg += '<' + x if x in self.allowed_attributes: for y in self.allowed_attributes[x]: tg += ' %s=""' % y tg += '> ' return xssescape(tg.strip()) def sanitize(text, permitted_tags=[ 'a', 'b', 'blockquote', 'br/', 'i', 'li', 'ol', 'ul', 'p', 'cite', 'code', 'pre', 'img/', 'h1','h2','h3','h4','h5','h6', 'table','tr','td','div', ], allowed_attributes = { 'a': ['href', 'title'], 'img': ['src', 'alt'], 'blockquote': ['type'], 'td': ['colspan'], }, escape=True): if not isinstance(text, str): return str(text) return XssCleaner(permitted_tags=permitted_tags, allowed_attributes=allowed_attributes).strip(text, escape)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created by Attila Csipa <web2py@csipa.in.rs> Modified by Massimo Di Pierro <mdipierro@cs.depaul.edu> """ import sys import os import threading import logging import time import sched import re import datetime import platform import portalocker import fileutils import cPickle from settings import global_settings logger = logging.getLogger("web2py.cron") _cron_stopping = False def stopcron(): "graceful shutdown of cron" global _cron_stopping _cron_stopping = True class extcron(threading.Thread): def __init__(self, applications_parent): threading.Thread.__init__(self) self.setDaemon(False) self.path = applications_parent crondance(self.path, 'external', startup=True) def run(self): if not _cron_stopping: logger.debug('external cron invocation') crondance(self.path, 'external', startup=False) class hardcron(threading.Thread): def __init__(self, applications_parent): threading.Thread.__init__(self) self.setDaemon(True) self.path = applications_parent crondance(self.path, 'hard', startup=True) def launch(self): if not _cron_stopping: logger.debug('hard cron invocation') crondance(self.path, 'hard', startup = False) def run(self): s = sched.scheduler(time.time, time.sleep) logger.info('Hard cron daemon started') while not _cron_stopping: now = time.time() s.enter(60 - now % 60, 1, self.launch, ()) s.run() class softcron(threading.Thread): def __init__(self, applications_parent): threading.Thread.__init__(self) self.path = applications_parent crondance(self.path, 'soft', startup=True) def run(self): if not _cron_stopping: logger.debug('soft cron invocation') crondance(self.path, 'soft', startup=False) class Token(object): def __init__(self,path): self.path = os.path.join(path, 'cron.master') if not os.path.exists(self.path): fileutils.write_file(self.path, '', 'wb') self.master = None self.now = time.time() def acquire(self,startup=False): """ returns the time when the lock is acquired or None if cron already running lock is implemented by writing a pickle (start, stop) in cron.master start is time when cron job starts and stop is time when cron completed stop == 0 if job started but did not yet complete if a cron job started within less than 60 seconds, acquire returns None if a cron job started before 60 seconds and did not stop, a warning is issue "Stale cron.master detected" """ if portalocker.LOCK_EX == None: logger.warning('WEB2PY CRON: Disabled because no file locking') return None self.master = open(self.path,'rb+') try: ret = None portalocker.lock(self.master,portalocker.LOCK_EX) try: (start, stop) = cPickle.load(self.master) except: (start, stop) = (0, 1) if startup or self.now - start > 59.99: ret = self.now if not stop: # this happens if previous cron job longer than 1 minute logger.warning('WEB2PY CRON: Stale cron.master detected') logger.debug('WEB2PY CRON: Acquiring lock') self.master.seek(0) cPickle.dump((self.now,0),self.master) finally: portalocker.unlock(self.master) if not ret: # do this so no need to release self.master.close() return ret def release(self): """ this function writes into cron.master the time when cron job was completed """ if not self.master.closed: portalocker.lock(self.master,portalocker.LOCK_EX) logger.debug('WEB2PY CRON: Releasing cron lock') self.master.seek(0) (start, stop) = cPickle.load(self.master) if start == self.now: # if this is my lock self.master.seek(0) cPickle.dump((self.now,time.time()),self.master) portalocker.unlock(self.master) self.master.close() def rangetolist(s, period='min'): retval = [] if s.startswith('*'): if period == 'min': s = s.replace('*', '0-59', 1) elif period == 'hr': s = s.replace('*', '0-23', 1) elif period == 'dom': s = s.replace('*', '1-31', 1) elif period == 'mon': s = s.replace('*', '1-12', 1) elif period == 'dow': s = s.replace('*', '0-6', 1) m = re.compile(r'(\d+)-(\d+)/(\d+)') match = m.match(s) if match: for i in range(int(match.group(1)), int(match.group(2)) + 1): if i % int(match.group(3)) == 0: retval.append(i) return retval def parsecronline(line): task = {} if line.startswith('@reboot'): line=line.replace('@reboot', '-1 * * * *') elif line.startswith('@yearly'): line=line.replace('@yearly', '0 0 1 1 *') elif line.startswith('@annually'): line=line.replace('@annually', '0 0 1 1 *') elif line.startswith('@monthly'): line=line.replace('@monthly', '0 0 1 * *') elif line.startswith('@weekly'): line=line.replace('@weekly', '0 0 * * 0') elif line.startswith('@daily'): line=line.replace('@daily', '0 0 * * *') elif line.startswith('@midnight'): line=line.replace('@midnight', '0 0 * * *') elif line.startswith('@hourly'): line=line.replace('@hourly', '0 * * * *') params = line.strip().split(None, 6) if len(params) < 7: return None daysofweek={'sun':0,'mon':1,'tue':2,'wed':3,'thu':4,'fri':5,'sat':6} for (s, id) in zip(params[:5], ['min', 'hr', 'dom', 'mon', 'dow']): if not s in [None, '*']: task[id] = [] vals = s.split(',') for val in vals: if val != '-1' and '-' in val and '/' not in val: val = '%s/1' % val if '/' in val: task[id] += rangetolist(val, id) elif val.isdigit() or val=='-1': task[id].append(int(val)) elif id=='dow' and val[:3].lower() in daysofweek: task[id].append(daysofweek(val[:3].lower())) task['user'] = params[5] task['cmd'] = params[6] return task class cronlauncher(threading.Thread): def __init__(self, cmd, shell=True): threading.Thread.__init__(self) if platform.system() == 'Windows': shell = False elif isinstance(cmd,list): cmd = ' '.join(cmd) self.cmd = cmd self.shell = shell def run(self): import subprocess proc = subprocess.Popen(self.cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=self.shell) (stdoutdata,stderrdata) = proc.communicate() if proc.returncode != 0: logger.warning( 'WEB2PY CRON Call returned code %s:\n%s' % \ (proc.returncode, stdoutdata+stderrdata)) else: logger.debug('WEB2PY CRON Call returned success:\n%s' \ % stdoutdata) def crondance(applications_parent, ctype='soft', startup=False): apppath = os.path.join(applications_parent,'applications') cron_path = os.path.join(apppath,'admin','cron') token = Token(cron_path) cronmaster = token.acquire(startup=startup) if not cronmaster: return now_s = time.localtime() checks=(('min',now_s.tm_min), ('hr',now_s.tm_hour), ('mon',now_s.tm_mon), ('dom',now_s.tm_mday), ('dow',(now_s.tm_wday+1)%7)) apps = [x for x in os.listdir(apppath) if os.path.isdir(os.path.join(apppath, x))] for app in apps: if _cron_stopping: break; apath = os.path.join(apppath,app) cronpath = os.path.join(apath, 'cron') crontab = os.path.join(cronpath, 'crontab') if not os.path.exists(crontab): continue try: cronlines = fileutils.readlines_file(crontab, 'rt') lines = [x.strip() for x in cronlines if x.strip() and not x.strip().startswith('#')] tasks = [parsecronline(cline) for cline in lines] except Exception, e: logger.error('WEB2PY CRON: crontab read error %s' % e) continue for task in tasks: if _cron_stopping: break; commands = [sys.executable] w2p_path = fileutils.abspath('web2py.py', gluon=True) if os.path.exists(w2p_path): commands.append(w2p_path) if global_settings.applications_parent != global_settings.gluon_parent: commands.extend(('-f', global_settings.applications_parent)) citems = [(k in task and not v in task[k]) for k,v in checks] task_min= task.get('min',[]) if not task: continue elif not startup and task_min == [-1]: continue elif task_min != [-1] and reduce(lambda a,b: a or b, citems): continue logger.info('WEB2PY CRON (%s): %s executing %s in %s at %s' \ % (ctype, app, task.get('cmd'), os.getcwd(), datetime.datetime.now())) action, command, models = False, task['cmd'], '' if command.startswith('**'): (action,models,command) = (True,'',command[2:]) elif command.startswith('*'): (action,models,command) = (True,'-M',command[1:]) else: action=False if action and command.endswith('.py'): commands.extend(('-J', # cron job models, # import models? '-S', app, # app name '-a', '"<recycle>"', # password '-R', command)) # command shell = True elif action: commands.extend(('-J', # cron job models, # import models? '-S', app+'/'+command, # app name '-a', '"<recycle>"')) # password shell = True else: commands = command shell = False try: cronlauncher(commands, shell=shell).start() except Exception, e: logger.warning( 'WEB2PY CRON: Execution error for %s: %s' \ % (task.get('cmd'), e)) token.release()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework (Copyrighted, 2007-2011). License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) Author: Thadeus Burgess Contributors: - Thank you to Massimo Di Pierro for creating the original gluon/template.py - Thank you to Jonathan Lundell for extensively testing the regex on Jython. - Thank you to Limodou (creater of uliweb) who inspired the block-element support for web2py. """ import os import re import cgi import cStringIO import logging try: from restricted import RestrictedError except: def RestrictedError(a,b,c): logging.error(str(a)+':'+str(b)+':'+str(c)) return RuntimeError class Node(object): """ Basic Container Object """ def __init__(self, value = None, pre_extend = False): self.value = value self.pre_extend = pre_extend def __str__(self): return str(self.value) class SuperNode(Node): def __init__(self, name = '', pre_extend = False): self.name = name self.value = None self.pre_extend = pre_extend def __str__(self): if self.value: return str(self.value) else: raise SyntaxError("Undefined parent block ``%s``. \n" % self.name + \ "You must define a block before referencing it.\nMake sure you have not left out an ``{{end}}`` tag." ) def __repr__(self): return "%s->%s" % (self.name, self.value) class BlockNode(Node): """ Block Container. This Node can contain other Nodes and will render in a hierarchical order of when nodes were added. ie:: {{ block test }} This is default block test {{ end }} """ def __init__(self, name = '', pre_extend = False, delimiters = ('{{','}}')): """ name - Name of this Node. """ self.nodes = [] self.name = name self.pre_extend = pre_extend self.left, self.right = delimiters def __repr__(self): lines = ['%sblock %s%s' % (self.left,self.name,self.right)] for node in self.nodes: lines.append(str(node)) lines.append('%send%s' % (self.left, self.right)) return ''.join(lines) def __str__(self): """ Get this BlockNodes content, not including child Nodes """ lines = [] for node in self.nodes: if not isinstance(node, BlockNode): lines.append(str(node)) return ''.join(lines) def append(self, node): """ Add an element to the nodes. Keyword Arguments - node -- Node object or string to append. """ if isinstance(node, str) or isinstance(node, Node): self.nodes.append(node) else: raise TypeError("Invalid type; must be instance of ``str`` or ``BlockNode``. %s" % node) def extend(self, other): """ Extend the list of nodes with another BlockNode class. Keyword Arguments - other -- BlockNode or Content object to extend from. """ if isinstance(other, BlockNode): self.nodes.extend(other.nodes) else: raise TypeError("Invalid type; must be instance of ``BlockNode``. %s" % other) def output(self, blocks): """ Merges all nodes into a single string. blocks -- Dictionary of blocks that are extending from this template. """ lines = [] # Get each of our nodes for node in self.nodes: # If we have a block level node. if isinstance(node, BlockNode): # If we can override this block. if node.name in blocks: # Override block from vars. lines.append(blocks[node.name].output(blocks)) # Else we take the default else: lines.append(node.output(blocks)) # Else its just a string else: lines.append(str(node)) # Now combine all of our lines together. return ''.join(lines) class Content(BlockNode): """ Parent Container -- Used as the root level BlockNode. Contains functions that operate as such. """ def __init__(self, name = "ContentBlock", pre_extend = False): """ Keyword Arguments name -- Unique name for this BlockNode """ self.name = name self.nodes = [] self.blocks = {} self.pre_extend = pre_extend def __str__(self): lines = [] # For each of our nodes for node in self.nodes: # If it is a block node. if isinstance(node, BlockNode): # And the node has a name that corresponds with a block in us if node.name in self.blocks: # Use the overriding output. lines.append(self.blocks[node.name].output(self.blocks)) else: # Otherwise we just use the nodes output. lines.append(node.output(self.blocks)) else: # It is just a string, so include it. lines.append(str(node)) # Merge our list together. return ''.join(lines) def _insert(self, other, index = 0): """ Inserts object at index. """ if isinstance(other, str) or isinstance(other, Node): self.nodes.insert(index, other) else: raise TypeError("Invalid type, must be instance of ``str`` or ``Node``.") def insert(self, other, index = 0): """ Inserts object at index. You may pass a list of objects and have them inserted. """ if isinstance(other, (list, tuple)): # Must reverse so the order stays the same. other.reverse() for item in other: self._insert(item, index) else: self._insert(other, index) def append(self, node): """ Adds a node to list. If it is a BlockNode then we assign a block for it. """ if isinstance(node, str) or isinstance(node, Node): self.nodes.append(node) if isinstance(node, BlockNode): self.blocks[node.name] = node else: raise TypeError("Invalid type, must be instance of ``str`` or ``BlockNode``. %s" % node) def extend(self, other): """ Extends the objects list of nodes with another objects nodes """ if isinstance(other, BlockNode): self.nodes.extend(other.nodes) self.blocks.update(other.blocks) else: raise TypeError("Invalid type; must be instance of ``BlockNode``. %s" % other) def clear_content(self): self.nodes = [] class TemplateParser(object): r_tag = re.compile(r'(\{\{.*?\}\})', re.DOTALL) r_multiline = re.compile(r'(""".*?""")|(\'\'\'.*?\'\'\')', re.DOTALL) # These are used for re-indentation. # Indent + 1 re_block = re.compile('^(elif |else:|except:|except |finally:).*$', re.DOTALL) # Indent - 1 re_unblock = re.compile('^(return|continue|break|raise)( .*)?$', re.DOTALL) # Indent - 1 re_pass = re.compile('^pass( .*)?$', re.DOTALL) def __init__(self, text, name = "ParserContainer", context = dict(), path = 'views/', writer = 'response.write', lexers = {}, delimiters = ('{{','}}'), _super_nodes = [], ): """ text -- text to parse context -- context to parse in path -- folder path to templates writer -- string of writer class to use lexers -- dict of custom lexers to use. delimiters -- for example ('{{','}}') _super_nodes -- a list of nodes to check for inclusion this should only be set by "self.extend" It contains a list of SuperNodes from a child template that need to be handled. """ # Keep a root level name. self.name = name # Raw text to start parsing. self.text = text # Writer to use (refer to the default for an example). # This will end up as # "%s(%s, escape=False)" % (self.writer, value) self.writer = writer # Dictionary of custom name lexers to use. if isinstance(lexers, dict): self.lexers = lexers else: self.lexers = {} # Path of templates self.path = path # Context for templates. self.context = context # allow optional alternative delimiters self.delimiters = delimiters if delimiters!=('{{','}}'): escaped_delimiters = (re.escape(delimiters[0]),re.escape(delimiters[1])) self.r_tag = re.compile(r'(%s.*?%s)' % escaped_delimiters, re.DOTALL) # Create a root level Content that everything will go into. self.content = Content(name=name) # Stack will hold our current stack of nodes. # As we descend into a node, it will be added to the stack # And when we leave, it will be removed from the stack. # self.content should stay on the stack at all times. self.stack = [self.content] # This variable will hold a reference to every super block # that we come across in this template. self.super_nodes = [] # This variable will hold a reference to the child # super nodes that need handling. self.child_super_nodes = _super_nodes # This variable will hold a reference to every block # that we come across in this template self.blocks = {} # Begin parsing. self.parse(text) def to_string(self): """ Return the parsed template with correct indentation. Used to make it easier to port to python3. """ return self.reindent(str(self.content)) def __str__(self): "Make sure str works exactly the same as python 3" return self.to_string() def __unicode__(self): "Make sure str works exactly the same as python 3" return self.to_string() def reindent(self, text): """ Reindents a string of unindented python code. """ # Get each of our lines into an array. lines = text.split('\n') # Our new lines new_lines = [] # Keeps track of how many indents we have. # Used for when we need to drop a level of indentation # only to reindent on the next line. credit = 0 # Current indentation k = 0 ################# # THINGS TO KNOW ################# # k += 1 means indent # k -= 1 means unindent # credit = 1 means unindent on the next line. for raw_line in lines: line = raw_line.strip() # ignore empty lines if not line: continue # If we have a line that contains python code that # should be unindented for this line of code. # and then reindented for the next line. if TemplateParser.re_block.match(line): k = k + credit - 1 # We obviously can't have a negative indentation k = max(k,0) # Add the indentation! new_lines.append(' '*(4*k)+line) # Bank account back to 0 again :( credit = 0 # If we are a pass block, we obviously de-dent. if TemplateParser.re_pass.match(line): k -= 1 # If we are any of the following, de-dent. # However, we should stay on the same level # But the line right after us will be de-dented. # So we add one credit to keep us at the level # while moving back one indentation level. if TemplateParser.re_unblock.match(line): credit = 1 k -= 1 # If we are an if statement, a try, or a semi-colon we # probably need to indent the next line. if line.endswith(':') and not line.startswith('#'): k += 1 # This must come before so that we can raise an error with the # right content. new_text = '\n'.join(new_lines) if k > 0: self._raise_error('missing "pass" in view', new_text) elif k < 0: self._raise_error('too many "pass" in view', new_text) return new_text def _raise_error(self, message='', text=None): """ Raise an error using itself as the filename and textual content. """ raise RestrictedError(self.name, text or self.text, message) def _get_file_text(self, filename): """ Attempt to open ``filename`` and retrieve its text. This will use self.path to search for the file. """ # If they didn't specify a filename, how can we find one! if not filename.strip(): self._raise_error('Invalid template filename') # Get the filename; filename looks like ``"template.html"``. # We need to eval to remove the quotes and get the string type. filename = eval(filename, self.context) # Get the path of the file on the system. filepath = os.path.join(self.path, filename) # try to read the text. try: fileobj = open(filepath, 'rb') text = fileobj.read() fileobj.close() except IOError: self._raise_error('Unable to open included view file: ' + filepath) return text def include(self, content, filename): """ Include ``filename`` here. """ text = self._get_file_text(filename) t = TemplateParser(text, name = filename, context = self.context, path = self.path, writer = self.writer, delimiters = self.delimiters) content.append(t.content) def extend(self, filename): """ Extend ``filename``. Anything not declared in a block defined by the parent will be placed in the parent templates ``{{include}}`` block. """ text = self._get_file_text(filename) # Create out nodes list to send to the parent super_nodes = [] # We want to include any non-handled nodes. super_nodes.extend(self.child_super_nodes) # And our nodes as well. super_nodes.extend(self.super_nodes) t = TemplateParser(text, name = filename, context = self.context, path = self.path, writer = self.writer, delimiters = self.delimiters, _super_nodes = super_nodes) # Make a temporary buffer that is unique for parent # template. buf = BlockNode(name='__include__' + filename, delimiters=self.delimiters) pre = [] # Iterate through each of our nodes for node in self.content.nodes: # If a node is a block if isinstance(node, BlockNode): # That happens to be in the parent template if node.name in t.content.blocks: # Do not include it continue if isinstance(node, Node): # Or if the node was before the extension # we should not include it if node.pre_extend: pre.append(node) continue # Otherwise, it should go int the # Parent templates {{include}} section. buf.append(node) else: buf.append(node) # Clear our current nodes. We will be replacing this with # the parent nodes. self.content.nodes = [] # Set our include, unique by filename t.content.blocks['__include__' + filename] = buf # Make sure our pre_extended nodes go first t.content.insert(pre) # Then we extend our blocks t.content.extend(self.content) # Work off the parent node. self.content = t.content def parse(self, text): # Basically, r_tag.split will split the text into # an array containing, 'non-tag', 'tag', 'non-tag', 'tag' # so if we alternate this variable, we know # what to look for. This is alternate to # line.startswith("{{") in_tag = False extend = None pre_extend = True # Use a list to store everything in # This is because later the code will "look ahead" # for missing strings or brackets. ij = self.r_tag.split(text) # j = current index # i = current item for j in range(len(ij)): i = ij[j] if i: if len(self.stack) == 0: self._raise_error('The "end" tag is unmatched, please check if you have a starting "block" tag') # Our current element in the stack. top = self.stack[-1] if in_tag: line = i # If we are missing any strings!!!! # This usually happens with the following example # template code # # {{a = '}}'}} # or # {{a = '}}blahblah{{'}} # # This will fix these # This is commented out because the current template # system has this same limitation. Since this has a # performance hit on larger templates, I do not recommend # using this code on production systems. This is still here # for "i told you it *can* be fixed" purposes. # # # if line.count("'") % 2 != 0 or line.count('"') % 2 != 0: # # # Look ahead # la = 1 # nextline = ij[j+la] # # # As long as we have not found our ending # # brackets keep going # while '}}' not in nextline: # la += 1 # nextline += ij[j+la] # # clear this line, so we # # don't attempt to parse it # # this is why there is an "if i" # # around line 530 # ij[j+la] = '' # # # retrieve our index. # index = nextline.index('}}') # # # Everything before the new brackets # before = nextline[:index+2] # # # Everything after # after = nextline[index+2:] # # # Make the next line everything after # # so it parses correctly, this *should* be # # all html # ij[j+1] = after # # # Add everything before to the current line # line += before # Get rid of '{{' and '}}' line = line[2:-2].strip() # This is bad juju, but let's do it anyway if not line: continue # We do not want to replace the newlines in code, # only in block comments. def remove_newline(re_val): # Take the entire match and replace newlines with # escaped newlines. return re_val.group(0).replace('\n', '\\n') # Perform block comment escaping. # This performs escaping ON anything # in between """ and """ line = re.sub(TemplateParser.r_multiline, remove_newline, line) if line.startswith('='): # IE: {{=response.title}} name, value = '=', line[1:].strip() else: v = line.split(' ', 1) if len(v) == 1: # Example # {{ include }} # {{ end }} name = v[0] value = '' else: # Example # {{ block pie }} # {{ include "layout.html" }} # {{ for i in range(10): }} name = v[0] value = v[1] # This will replace newlines in block comments # with the newline character. This is so that they # retain their formatting, but squish down to one # line in the rendered template. # First check if we have any custom lexers if name in self.lexers: # Pass the information to the lexer # and allow it to inject in the environment # You can define custom names such as # '{{<<variable}}' which could potentially # write unescaped version of the variable. self.lexers[name](parser = self, value = value, top = top, stack = self.stack,) elif name == '=': # So we have a variable to insert into # the template buf = "\n%s(%s)" % (self.writer, value) top.append(Node(buf, pre_extend = pre_extend)) elif name == 'block' and not value.startswith('='): # Make a new node with name. node = BlockNode(name = value.strip(), pre_extend = pre_extend, delimiters = self.delimiters) # Append this node to our active node top.append(node) # Make sure to add the node to the stack. # so anything after this gets added # to this node. This allows us to # "nest" nodes. self.stack.append(node) elif name == 'end' and not value.startswith('='): # We are done with this node. # Save an instance of it self.blocks[top.name] = top # Pop it. self.stack.pop() elif name == 'super' and not value.startswith('='): # Get our correct target name # If they just called {{super}} without a name # attempt to assume the top blocks name. if value: target_node = value else: target_node = top.name # Create a SuperNode instance node = SuperNode(name = target_node, pre_extend = pre_extend) # Add this to our list to be taken care of self.super_nodes.append(node) # And put in in the tree top.append(node) elif name == 'include' and not value.startswith('='): # If we know the target file to include if value: self.include(top, value) # Otherwise, make a temporary include node # That the child node will know to hook into. else: include_node = BlockNode(name = '__include__' + self.name, pre_extend = pre_extend, delimiters = self.delimiters) top.append(include_node) elif name == 'extend' and not value.startswith('='): # We need to extend the following # template. extend = value pre_extend = False else: # If we don't know where it belongs # we just add it anyways without formatting. if line and in_tag: # Split on the newlines >.< tokens = line.split('\n') # We need to look for any instances of # for i in range(10): # = i # pass # So we can properly put a response.write() in place. continuation = False len_parsed = 0 for k in range(len(tokens)): tokens[k] = tokens[k].strip() len_parsed += len(tokens[k]) if tokens[k].startswith('='): if tokens[k].endswith('\\'): continuation = True tokens[k] = "\n%s(%s" % (self.writer, tokens[k][1:].strip()) else: tokens[k] = "\n%s(%s)" % (self.writer, tokens[k][1:].strip()) elif continuation: tokens[k] += ')' continuation = False buf = "\n%s" % '\n'.join(tokens) top.append(Node(buf, pre_extend = pre_extend)) else: # It is HTML so just include it. buf = "\n%s(%r, escape=False)" % (self.writer, i) top.append(Node(buf, pre_extend = pre_extend)) # Remember: tag, not tag, tag, not tag in_tag = not in_tag # Make a list of items to remove from child to_rm = [] # Go through each of the children nodes for node in self.child_super_nodes: # If we declared a block that this node wants to include if node.name in self.blocks: # Go ahead and include it! node.value = self.blocks[node.name] # Since we processed this child, we don't need to # pass it along to the parent to_rm.append(node) # Remove some of the processed nodes for node in to_rm: # Since this is a pointer, it works beautifully. # Sometimes I miss C-Style pointers... I want my asterisk... self.child_super_nodes.remove(node) # If we need to extend a template. if extend: self.extend(extend) # We need this for integration with gluon def parse_template(filename, path = 'views/', context = dict(), lexers = {}, delimiters = ('{{','}}') ): """ filename can be a view filename in the views folder or an input stream path is the path of a views folder context is a dictionary of symbols used to render the template """ # First, if we have a str try to open the file if isinstance(filename, str): try: fp = open(os.path.join(path, filename), 'rb') text = fp.read() fp.close() except IOError: raise RestrictedError(filename, '', 'Unable to find the file') else: text = filename.read() # Use the file contents to get a parsed template and return it. return str(TemplateParser(text, context=context, path=path, lexers=lexers, delimiters=delimiters)) def get_parsed(text): """ Returns the indented python code of text. Useful for unit testing. """ return str(TemplateParser(text)) # And this is a generic render function. # Here for integration with gluon. def render(content = "hello world", stream = None, filename = None, path = None, context = {}, lexers = {}, delimiters = ('{{','}}') ): """ >>> render() 'hello world' >>> render(content='abc') 'abc' >>> render(content='abc\\'') "abc'" >>> render(content='a"\\'bc') 'a"\\'bc' >>> render(content='a\\nbc') 'a\\nbc' >>> render(content='a"bcd"e') 'a"bcd"e' >>> render(content="'''a\\nc'''") "'''a\\nc'''" >>> render(content="'''a\\'c'''") "'''a\'c'''" >>> render(content='{{for i in range(a):}}{{=i}}<br />{{pass}}', context=dict(a=5)) '0<br />1<br />2<br />3<br />4<br />' >>> render(content='{%for i in range(a):%}{%=i%}<br />{%pass%}', context=dict(a=5),delimiters=('{%','%}')) '0<br />1<br />2<br />3<br />4<br />' >>> render(content="{{='''hello\\nworld'''}}") 'hello\\nworld' >>> render(content='{{for i in range(3):\\n=i\\npass}}') '012' """ # Here to avoid circular Imports try: from globals import Response except: # Working standalone. Build a mock Response object. class Response(): def __init__(self): self.body = cStringIO.StringIO() def write(self, data, escape=True): if not escape: self.body.write(str(data)) elif hasattr(data,'xml') and callable(data.xml): self.body.write(data.xml()) else: # make it a string if not isinstance(data, (str, unicode)): data = str(data) elif isinstance(data, unicode): data = data.encode('utf8', 'xmlcharrefreplace') data = cgi.escape(data, True).replace("'","&#x27;") self.body.write(data) # A little helper to avoid escaping. class NOESCAPE(): def __init__(self, text): self.text = text def xml(self): return self.text # Add it to the context so we can use it. context['NOESCAPE'] = NOESCAPE # If we don't have anything to render, why bother? if not content and not stream and not filename: raise SyntaxError, "Must specify a stream or filename or content" # Here for legacy purposes, probably can be reduced to something more simple. close_stream = False if not stream: if filename: stream = open(filename, 'rb') close_stream = True elif content: stream = cStringIO.StringIO(content) # Get a response class. context['response'] = Response() # Execute the template. code = str(TemplateParser(stream.read(), context=context, path=path, lexers=lexers, delimiters=delimiters)) try: exec(code) in context except Exception: # for i,line in enumerate(code.split('\n')): print i,line raise if close_stream: stream.close() # Returned the rendered content. return context['response'].body.getvalue() if __name__ == '__main__': import doctest doctest.testmod()
Python
import codecs, encodings """Caller will hand this library a buffer and ask it to either convert it or auto-detect the type. Based on http://code.activestate.com/recipes/52257/ Licensed under the PSF License """ # None represents a potentially variable byte. "##" in the XML spec... autodetect_dict={ # bytepattern : ("name", (0x00, 0x00, 0xFE, 0xFF) : ("ucs4_be"), (0xFF, 0xFE, 0x00, 0x00) : ("ucs4_le"), (0xFE, 0xFF, None, None) : ("utf_16_be"), (0xFF, 0xFE, None, None) : ("utf_16_le"), (0x00, 0x3C, 0x00, 0x3F) : ("utf_16_be"), (0x3C, 0x00, 0x3F, 0x00) : ("utf_16_le"), (0x3C, 0x3F, 0x78, 0x6D): ("utf_8"), (0x4C, 0x6F, 0xA7, 0x94): ("EBCDIC") } def autoDetectXMLEncoding(buffer): """ buffer -> encoding_name The buffer should be at least 4 bytes long. Returns None if encoding cannot be detected. Note that encoding_name might not have an installed decoder (e.g. EBCDIC) """ # a more efficient implementation would not decode the whole # buffer at once but otherwise we'd have to decode a character at # a time looking for the quote character...that's a pain encoding = "utf_8" # according to the XML spec, this is the default # this code successively tries to refine the default # whenever it fails to refine, it falls back to # the last place encoding was set. if len(buffer)>=4: bytes = (byte1, byte2, byte3, byte4) = tuple(map(ord, buffer[0:4])) enc_info = autodetect_dict.get(bytes, None) if not enc_info: # try autodetection again removing potentially # variable bytes bytes = (byte1, byte2, None, None) enc_info = autodetect_dict.get(bytes) else: enc_info = None if enc_info: encoding = enc_info # we've got a guess... these are #the new defaults # try to find a more precise encoding using xml declaration secret_decoder_ring = codecs.lookup(encoding)[1] (decoded,length) = secret_decoder_ring(buffer) first_line = decoded.split("\n")[0] if first_line and first_line.startswith(u"<?xml"): encoding_pos = first_line.find(u"encoding") if encoding_pos!=-1: # look for double quote quote_pos=first_line.find('"', encoding_pos) if quote_pos==-1: # look for single quote quote_pos=first_line.find("'", encoding_pos) if quote_pos>-1: quote_char,rest=(first_line[quote_pos], first_line[quote_pos+1:]) encoding=rest[:rest.find(quote_char)] return encoding def decoder(buffer): encoding = autoDetectXMLEncoding(buffer) return buffer.decode(encoding).encode('utf8')
Python
# encoding utf-8 __author__ = "Thadeus Burgess <thadeusb@thadeusb.com>" # we classify as "non-reserved" those key words that are explicitly known # to the parser but are allowed as column or table names. Some key words # that are otherwise non-reserved cannot be used as function or data type n # ames and are in the nonreserved list. (Most of these words represent # built-in functions or data types with special syntax. The function # or type is still available but it cannot be redefined by the user.) # Labeled "reserved" are those tokens that are not allowed as column or # table names. Some reserved key words are allowable as names for # functions or data typesself. # Note at the bottom of the list is a dict containing references to the # tuples, and also if you add a list don't forget to remove its default # set of COMMON. # Keywords that are adapter specific. Such as a list of "postgresql" # or "mysql" keywords # These are keywords that are common to all SQL dialects, and should # never be used as a table or column. Even if you use one of these # the cursor will throw an OperationalError for the SQL syntax. COMMON = set(( 'SELECT', 'INSERT', 'DELETE', 'UPDATE', 'DROP', 'CREATE', 'ALTER', 'WHERE', 'FROM', 'INNER', 'JOIN', 'AND', 'OR', 'LIKE', 'ON', 'IN', 'SET', 'BY', 'GROUP', 'ORDER', 'LEFT', 'OUTER', 'IF', 'END', 'THEN', 'LOOP', 'AS', 'ELSE', 'FOR', 'CASE', 'WHEN', 'MIN', 'MAX', 'DISTINCT', )) POSTGRESQL = set(( 'FALSE', 'TRUE', 'ALL', 'ANALYSE', 'ANALYZE', 'AND', 'ANY', 'ARRAY', 'AS', 'ASC', 'ASYMMETRIC', 'AUTHORIZATION', 'BETWEEN', 'BIGINT', 'BINARY', 'BIT', 'BOOLEAN', 'BOTH', 'CASE', 'CAST', 'CHAR', 'CHARACTER', 'CHECK', 'COALESCE', 'COLLATE', 'COLUMN', 'CONSTRAINT', 'CREATE', 'CROSS', 'CURRENT_CATALOG', 'CURRENT_DATE', 'CURRENT_ROLE', 'CURRENT_SCHEMA', 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'CURRENT_USER', 'DEC', 'DECIMAL', 'DEFAULT', 'DEFERRABLE', 'DESC', 'DISTINCT', 'DO', 'ELSE', 'END', 'EXCEPT', 'EXISTS', 'EXTRACT', 'FETCH', 'FLOAT', 'FOR', 'FOREIGN', 'FREEZE', 'FROM', 'FULL', 'GRANT', 'GREATEST', 'GROUP', 'HAVING', 'ILIKE', 'IN', 'INITIALLY', 'INNER', 'INOUT', 'INT', 'INTEGER', 'INTERSECT', 'INTERVAL', 'INTO', 'IS', 'ISNULL', 'JOIN', 'LEADING', 'LEAST', 'LEFT', 'LIKE', 'LIMIT', 'LOCALTIME', 'LOCALTIMESTAMP', 'NATIONAL', 'NATURAL', 'NCHAR', 'NEW', 'NONE', 'NOT', 'NOTNULL', 'NULL', 'NULLIF', 'NUMERIC', 'OFF', 'OFFSET', 'OLD', 'ON', 'ONLY', 'OR', 'ORDER', 'OUT', 'OUTER', 'OVERLAPS', 'OVERLAY', 'PLACING', 'POSITION', 'PRECISION', 'PRIMARY', 'REAL', 'REFERENCES', 'RETURNING', 'RIGHT', 'ROW', 'SELECT', 'SESSION_USER', 'SETOF', 'SIMILAR', 'SMALLINT', 'SOME', 'SUBSTRING', 'SYMMETRIC', 'TABLE', 'THEN', 'TIME', 'TIMESTAMP', 'TO', 'TRAILING', 'TREAT', 'TRIM', 'UNION', 'UNIQUE', 'USER', 'USING', 'VALUES', 'VARCHAR', 'VARIADIC', 'VERBOSE', 'WHEN', 'WHERE', 'WITH', 'XMLATTRIBUTES', 'XMLCONCAT', 'XMLELEMENT', 'XMLFOREST', 'XMLPARSE', 'XMLPI', 'XMLROOT', 'XMLSERIALIZE', )) POSTGRESQL_NONRESERVED = set(( 'A', 'ABORT', 'ABS', 'ABSENT', 'ABSOLUTE', 'ACCESS', 'ACCORDING', 'ACTION', 'ADA', 'ADD', 'ADMIN', 'AFTER', 'AGGREGATE', 'ALIAS', 'ALLOCATE', 'ALSO', 'ALTER', 'ALWAYS', 'ARE', 'ARRAY_AGG', 'ASENSITIVE', 'ASSERTION', 'ASSIGNMENT', 'AT', 'ATOMIC', 'ATTRIBUTE', 'ATTRIBUTES', 'AVG', 'BACKWARD', 'BASE64', 'BEFORE', 'BEGIN', 'BERNOULLI', 'BIT_LENGTH', 'BITVAR', 'BLOB', 'BOM', 'BREADTH', 'BY', 'C', 'CACHE', 'CALL', 'CALLED', 'CARDINALITY', 'CASCADE', 'CASCADED', 'CATALOG', 'CATALOG_NAME', 'CEIL', 'CEILING', 'CHAIN', 'CHAR_LENGTH', 'CHARACTER_LENGTH', 'CHARACTER_SET_CATALOG', 'CHARACTER_SET_NAME', 'CHARACTER_SET_SCHEMA', 'CHARACTERISTICS', 'CHARACTERS', 'CHECKED', 'CHECKPOINT', 'CLASS', 'CLASS_ORIGIN', 'CLOB', 'CLOSE', 'CLUSTER', 'COBOL', 'COLLATION', 'COLLATION_CATALOG', 'COLLATION_NAME', 'COLLATION_SCHEMA', 'COLLECT', 'COLUMN_NAME', 'COLUMNS', 'COMMAND_FUNCTION', 'COMMAND_FUNCTION_CODE', 'COMMENT', 'COMMIT', 'COMMITTED', 'COMPLETION', 'CONCURRENTLY', 'CONDITION', 'CONDITION_NUMBER', 'CONFIGURATION', 'CONNECT', 'CONNECTION', 'CONNECTION_NAME', 'CONSTRAINT_CATALOG', 'CONSTRAINT_NAME', 'CONSTRAINT_SCHEMA', 'CONSTRAINTS', 'CONSTRUCTOR', 'CONTAINS', 'CONTENT', 'CONTINUE', 'CONVERSION', 'CONVERT', 'COPY', 'CORR', 'CORRESPONDING', 'COST', 'COUNT', 'COVAR_POP', 'COVAR_SAMP', 'CREATEDB', 'CREATEROLE', 'CREATEUSER', 'CSV', 'CUBE', 'CUME_DIST', 'CURRENT', 'CURRENT_DEFAULT_TRANSFORM_GROUP', 'CURRENT_PATH', 'CURRENT_TRANSFORM_GROUP_FOR_TYPE', 'CURSOR', 'CURSOR_NAME', 'CYCLE', 'DATA', 'DATABASE', 'DATE', 'DATETIME_INTERVAL_CODE', 'DATETIME_INTERVAL_PRECISION', 'DAY', 'DEALLOCATE', 'DECLARE', 'DEFAULTS', 'DEFERRED', 'DEFINED', 'DEFINER', 'DEGREE', 'DELETE', 'DELIMITER', 'DELIMITERS', 'DENSE_RANK', 'DEPTH', 'DEREF', 'DERIVED', 'DESCRIBE', 'DESCRIPTOR', 'DESTROY', 'DESTRUCTOR', 'DETERMINISTIC', 'DIAGNOSTICS', 'DICTIONARY', 'DISABLE', 'DISCARD', 'DISCONNECT', 'DISPATCH', 'DOCUMENT', 'DOMAIN', 'DOUBLE', 'DROP', 'DYNAMIC', 'DYNAMIC_FUNCTION', 'DYNAMIC_FUNCTION_CODE', 'EACH', 'ELEMENT', 'EMPTY', 'ENABLE', 'ENCODING', 'ENCRYPTED', 'END-EXEC', 'ENUM', 'EQUALS', 'ESCAPE', 'EVERY', 'EXCEPTION', 'EXCLUDE', 'EXCLUDING', 'EXCLUSIVE', 'EXEC', 'EXECUTE', 'EXISTING', 'EXP', 'EXPLAIN', 'EXTERNAL', 'FAMILY', 'FILTER', 'FINAL', 'FIRST', 'FIRST_VALUE', 'FLAG', 'FLOOR', 'FOLLOWING', 'FORCE', 'FORTRAN', 'FORWARD', 'FOUND', 'FREE', 'FUNCTION', 'FUSION', 'G', 'GENERAL', 'GENERATED', 'GET', 'GLOBAL', 'GO', 'GOTO', 'GRANTED', 'GROUPING', 'HANDLER', 'HEADER', 'HEX', 'HIERARCHY', 'HOLD', 'HOST', 'HOUR', # 'ID', 'IDENTITY', 'IF', 'IGNORE', 'IMMEDIATE', 'IMMUTABLE', 'IMPLEMENTATION', 'IMPLICIT', 'INCLUDING', 'INCREMENT', 'INDENT', 'INDEX', 'INDEXES', 'INDICATOR', 'INFIX', 'INHERIT', 'INHERITS', 'INITIALIZE', 'INPUT', 'INSENSITIVE', 'INSERT', 'INSTANCE', 'INSTANTIABLE', 'INSTEAD', 'INTERSECTION', 'INVOKER', 'ISOLATION', 'ITERATE', 'K', 'KEY', 'KEY_MEMBER', 'KEY_TYPE', 'LAG', 'LANCOMPILER', 'LANGUAGE', 'LARGE', 'LAST', 'LAST_VALUE', 'LATERAL', 'LC_COLLATE', 'LC_CTYPE', 'LEAD', 'LENGTH', 'LESS', 'LEVEL', 'LIKE_REGEX', 'LISTEN', 'LN', 'LOAD', 'LOCAL', 'LOCATION', 'LOCATOR', 'LOCK', 'LOGIN', 'LOWER', 'M', 'MAP', 'MAPPING', 'MATCH', 'MATCHED', 'MAX', 'MAX_CARDINALITY', 'MAXVALUE', 'MEMBER', 'MERGE', 'MESSAGE_LENGTH', 'MESSAGE_OCTET_LENGTH', 'MESSAGE_TEXT', 'METHOD', 'MIN', 'MINUTE', 'MINVALUE', 'MOD', 'MODE', 'MODIFIES', 'MODIFY', 'MODULE', 'MONTH', 'MORE', 'MOVE', 'MULTISET', 'MUMPS', # 'NAME', 'NAMES', 'NAMESPACE', 'NCLOB', 'NESTING', 'NEXT', 'NFC', 'NFD', 'NFKC', 'NFKD', 'NIL', 'NO', 'NOCREATEDB', 'NOCREATEROLE', 'NOCREATEUSER', 'NOINHERIT', 'NOLOGIN', 'NORMALIZE', 'NORMALIZED', 'NOSUPERUSER', 'NOTHING', 'NOTIFY', 'NOWAIT', 'NTH_VALUE', 'NTILE', 'NULLABLE', 'NULLS', 'NUMBER', 'OBJECT', 'OCCURRENCES_REGEX', 'OCTET_LENGTH', 'OCTETS', 'OF', 'OIDS', 'OPEN', 'OPERATION', 'OPERATOR', 'OPTION', 'OPTIONS', 'ORDERING', 'ORDINALITY', 'OTHERS', 'OUTPUT', 'OVER', 'OVERRIDING', 'OWNED', 'OWNER', 'P', 'PAD', 'PARAMETER', 'PARAMETER_MODE', 'PARAMETER_NAME', 'PARAMETER_ORDINAL_POSITION', 'PARAMETER_SPECIFIC_CATALOG', 'PARAMETER_SPECIFIC_NAME', 'PARAMETER_SPECIFIC_SCHEMA', 'PARAMETERS', 'PARSER', 'PARTIAL', 'PARTITION', 'PASCAL', 'PASSING', # 'PASSWORD', 'PATH', 'PERCENT_RANK', 'PERCENTILE_CONT', 'PERCENTILE_DISC', 'PLANS', 'PLI', 'POSITION_REGEX', 'POSTFIX', 'POWER', 'PRECEDING', 'PREFIX', 'PREORDER', 'PREPARE', 'PREPARED', 'PRESERVE', 'PRIOR', 'PRIVILEGES', 'PROCEDURAL', 'PROCEDURE', 'PUBLIC', 'QUOTE', 'RANGE', 'RANK', 'READ', 'READS', 'REASSIGN', 'RECHECK', 'RECURSIVE', 'REF', 'REFERENCING', 'REGR_AVGX', 'REGR_AVGY', 'REGR_COUNT', 'REGR_INTERCEPT', 'REGR_R2', 'REGR_SLOPE', 'REGR_SXX', 'REGR_SXY', 'REGR_SYY', 'REINDEX', 'RELATIVE', 'RELEASE', 'RENAME', 'REPEATABLE', 'REPLACE', 'REPLICA', 'RESET', 'RESPECT', 'RESTART', 'RESTRICT', 'RESULT', 'RETURN', 'RETURNED_CARDINALITY', 'RETURNED_LENGTH', 'RETURNED_OCTET_LENGTH', 'RETURNED_SQLSTATE', 'RETURNS', 'REVOKE', # 'ROLE', 'ROLLBACK', 'ROLLUP', 'ROUTINE', 'ROUTINE_CATALOG', 'ROUTINE_NAME', 'ROUTINE_SCHEMA', 'ROW_COUNT', 'ROW_NUMBER', 'ROWS', 'RULE', 'SAVEPOINT', 'SCALE', 'SCHEMA', 'SCHEMA_NAME', 'SCOPE', 'SCOPE_CATALOG', 'SCOPE_NAME', 'SCOPE_SCHEMA', 'SCROLL', 'SEARCH', 'SECOND', 'SECTION', 'SECURITY', 'SELF', 'SENSITIVE', 'SEQUENCE', 'SERIALIZABLE', 'SERVER', 'SERVER_NAME', 'SESSION', 'SET', 'SETS', 'SHARE', 'SHOW', 'SIMPLE', 'SIZE', 'SOURCE', 'SPACE', 'SPECIFIC', 'SPECIFIC_NAME', 'SPECIFICTYPE', 'SQL', 'SQLCODE', 'SQLERROR', 'SQLEXCEPTION', 'SQLSTATE', 'SQLWARNING', 'SQRT', 'STABLE', 'STANDALONE', 'START', 'STATE', 'STATEMENT', 'STATIC', 'STATISTICS', 'STDDEV_POP', 'STDDEV_SAMP', 'STDIN', 'STDOUT', 'STORAGE', 'STRICT', 'STRIP', 'STRUCTURE', 'STYLE', 'SUBCLASS_ORIGIN', 'SUBLIST', 'SUBMULTISET', 'SUBSTRING_REGEX', 'SUM', 'SUPERUSER', 'SYSID', 'SYSTEM', 'SYSTEM_USER', 'T', # 'TABLE_NAME', 'TABLESAMPLE', 'TABLESPACE', 'TEMP', 'TEMPLATE', 'TEMPORARY', 'TERMINATE', 'TEXT', 'THAN', 'TIES', 'TIMEZONE_HOUR', 'TIMEZONE_MINUTE', 'TOP_LEVEL_COUNT', 'TRANSACTION', 'TRANSACTION_ACTIVE', 'TRANSACTIONS_COMMITTED', 'TRANSACTIONS_ROLLED_BACK', 'TRANSFORM', 'TRANSFORMS', 'TRANSLATE', 'TRANSLATE_REGEX', 'TRANSLATION', 'TRIGGER', 'TRIGGER_CATALOG', 'TRIGGER_NAME', 'TRIGGER_SCHEMA', 'TRIM_ARRAY', 'TRUNCATE', 'TRUSTED', 'TYPE', 'UESCAPE', 'UNBOUNDED', 'UNCOMMITTED', 'UNDER', 'UNENCRYPTED', 'UNKNOWN', 'UNLISTEN', 'UNNAMED', 'UNNEST', 'UNTIL', 'UNTYPED', 'UPDATE', 'UPPER', 'URI', 'USAGE', 'USER_DEFINED_TYPE_CATALOG', 'USER_DEFINED_TYPE_CODE', 'USER_DEFINED_TYPE_NAME', 'USER_DEFINED_TYPE_SCHEMA', 'VACUUM', 'VALID', 'VALIDATOR', 'VALUE', 'VAR_POP', 'VAR_SAMP', 'VARBINARY', 'VARIABLE', 'VARYING', 'VERSION', 'VIEW', 'VOLATILE', 'WHENEVER', 'WHITESPACE', 'WIDTH_BUCKET', 'WINDOW', 'WITHIN', 'WITHOUT', 'WORK', 'WRAPPER', 'WRITE', 'XML', 'XMLAGG', 'XMLBINARY', 'XMLCAST', 'XMLCOMMENT', 'XMLDECLARATION', 'XMLDOCUMENT', 'XMLEXISTS', 'XMLITERATE', 'XMLNAMESPACES', 'XMLQUERY', 'XMLSCHEMA', 'XMLTABLE', 'XMLTEXT', 'XMLVALIDATE', 'YEAR', 'YES', 'ZONE', )) #Thanks villas FIREBIRD = set(( 'ABS', 'ACTIVE', 'ADMIN', 'AFTER', 'ASCENDING', 'AUTO', 'AUTODDL', 'BASED', 'BASENAME', 'BASE_NAME', 'BEFORE', 'BIT_LENGTH', 'BLOB', 'BLOBEDIT', 'BOOLEAN', 'BOTH', 'BUFFER', 'CACHE', 'CHAR_LENGTH', 'CHARACTER_LENGTH', 'CHECK_POINT_LEN', 'CHECK_POINT_LENGTH', 'CLOSE', 'COMMITTED', 'COMPILETIME', 'COMPUTED', 'CONDITIONAL', 'CONNECT', 'CONTAINING', 'CROSS', 'CSTRING', 'CURRENT_CONNECTION', 'CURRENT_ROLE', 'CURRENT_TRANSACTION', 'CURRENT_USER', 'DATABASE', 'DB_KEY', 'DEBUG', 'DESCENDING', 'DISCONNECT', 'DISPLAY', 'DO', 'ECHO', 'EDIT', 'ENTRY_POINT', 'EVENT', 'EXIT', 'EXTERN', 'FALSE', 'FETCH', 'FILE', 'FILTER', 'FREE_IT', 'FUNCTION', 'GDSCODE', 'GENERATOR', 'GEN_ID', 'GLOBAL', 'GROUP_COMMIT_WAIT', 'GROUP_COMMIT_WAIT_TIME', 'HELP', 'IF', 'INACTIVE', 'INDEX', 'INIT', 'INPUT_TYPE', 'INSENSITIVE', 'ISQL', 'LC_MESSAGES', 'LC_TYPE', 'LEADING', 'LENGTH', 'LEV', 'LOGFILE', 'LOG_BUFFER_SIZE', 'LOG_BUF_SIZE', 'LONG', 'LOWER', 'MANUAL', 'MAXIMUM', 'MAXIMUM_SEGMENT', 'MAX_SEGMENT', 'MERGE', 'MESSAGE', 'MINIMUM', 'MODULE_NAME', 'NOAUTO', 'NUM_LOG_BUFS', 'NUM_LOG_BUFFERS', 'OCTET_LENGTH', 'OPEN', 'OUTPUT_TYPE', 'OVERFLOW', 'PAGE', 'PAGELENGTH', 'PAGES', 'PAGE_SIZE', 'PARAMETER', # 'PASSWORD', 'PLAN', 'POST_EVENT', 'QUIT', 'RAW_PARTITIONS', 'RDB$DB_KEY', 'RECORD_VERSION', 'RECREATE', 'RECURSIVE', 'RELEASE', 'RESERV', 'RESERVING', 'RETAIN', 'RETURN', 'RETURNING_VALUES', 'RETURNS', # 'ROLE', 'ROW_COUNT', 'ROWS', 'RUNTIME', 'SAVEPOINT', 'SECOND', 'SENSITIVE', 'SHADOW', 'SHARED', 'SHELL', 'SHOW', 'SINGULAR', 'SNAPSHOT', 'SORT', 'STABILITY', 'START', 'STARTING', 'STARTS', 'STATEMENT', 'STATIC', 'STATISTICS', 'SUB_TYPE', 'SUSPEND', 'TERMINATOR', 'TRAILING', 'TRIGGER', 'TRIM', 'TRUE', 'TYPE', 'UNCOMMITTED', 'UNKNOWN', 'USING', 'VARIABLE', 'VERSION', 'WAIT', 'WEEKDAY', 'WHILE', 'YEARDAY', )) FIREBIRD_NONRESERVED = set(( 'BACKUP', 'BLOCK', 'COALESCE', 'COLLATION', 'COMMENT', 'DELETING', 'DIFFERENCE', 'IIF', 'INSERTING', 'LAST', 'LEAVE', 'LOCK', 'NEXT', 'NULLIF', 'NULLS', 'RESTART', 'RETURNING', 'SCALAR_ARRAY', 'SEQUENCE', 'STATEMENT', 'UPDATING', 'ABS', 'ACCENT', 'ACOS', 'ALWAYS', 'ASCII_CHAR', 'ASCII_VAL', 'ASIN', 'ATAN', 'ATAN2', 'BACKUP', 'BIN_AND', 'BIN_OR', 'BIN_SHL', 'BIN_SHR', 'BIN_XOR', 'BLOCK', 'CEIL', 'CEILING', 'COLLATION', 'COMMENT', 'COS', 'COSH', 'COT', 'DATEADD', 'DATEDIFF', 'DECODE', 'DIFFERENCE', 'EXP', 'FLOOR', 'GEN_UUID', 'GENERATED', 'HASH', 'IIF', 'LIST', 'LN', 'LOG', 'LOG10', 'LPAD', 'MATCHED', 'MATCHING', 'MAXVALUE', 'MILLISECOND', 'MINVALUE', 'MOD', 'NEXT', 'OVERLAY', 'PAD', 'PI', 'PLACING', 'POWER', 'PRESERVE', 'RAND', 'REPLACE', 'RESTART', 'RETURNING', 'REVERSE', 'ROUND', 'RPAD', 'SCALAR_ARRAY', 'SEQUENCE', 'SIGN', 'SIN', 'SINH', 'SPACE', 'SQRT', 'TAN', 'TANH', 'TEMPORARY', 'TRUNC', 'WEEK', )) # Thanks Jonathan Lundell MYSQL = set(( 'ACCESSIBLE', 'ADD', 'ALL', 'ALTER', 'ANALYZE', 'AND', 'AS', 'ASC', 'ASENSITIVE', 'BEFORE', 'BETWEEN', 'BIGINT', 'BINARY', 'BLOB', 'BOTH', 'BY', 'CALL', 'CASCADE', 'CASE', 'CHANGE', 'CHAR', 'CHARACTER', 'CHECK', 'COLLATE', 'COLUMN', 'CONDITION', 'CONSTRAINT', 'CONTINUE', 'CONVERT', 'CREATE', 'CROSS', 'CURRENT_DATE', 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'CURRENT_USER', 'CURSOR', 'DATABASE', 'DATABASES', 'DAY_HOUR', 'DAY_MICROSECOND', 'DAY_MINUTE', 'DAY_SECOND', 'DEC', 'DECIMAL', 'DECLARE', 'DEFAULT', 'DELAYED', 'DELETE', 'DESC', 'DESCRIBE', 'DETERMINISTIC', 'DISTINCT', 'DISTINCTROW', 'DIV', 'DOUBLE', 'DROP', 'DUAL', 'EACH', 'ELSE', 'ELSEIF', 'ENCLOSED', 'ESCAPED', 'EXISTS', 'EXIT', 'EXPLAIN', 'FALSE', 'FETCH', 'FLOAT', 'FLOAT4', 'FLOAT8', 'FOR', 'FORCE', 'FOREIGN', 'FROM', 'FULLTEXT', 'GRANT', 'GROUP', 'HAVING', 'HIGH_PRIORITY', 'HOUR_MICROSECOND', 'HOUR_MINUTE', 'HOUR_SECOND', 'IF', 'IGNORE', 'IGNORE_SERVER_IDS', 'IGNORE_SERVER_IDS', 'IN', 'INDEX', 'INFILE', 'INNER', 'INOUT', 'INSENSITIVE', 'INSERT', 'INT', 'INT1', 'INT2', 'INT3', 'INT4', 'INT8', 'INTEGER', 'INTERVAL', 'INTO', 'IS', 'ITERATE', 'JOIN', 'KEY', 'KEYS', 'KILL', 'LEADING', 'LEAVE', 'LEFT', 'LIKE', 'LIMIT', 'LINEAR', 'LINES', 'LOAD', 'LOCALTIME', 'LOCALTIMESTAMP', 'LOCK', 'LONG', 'LONGBLOB', 'LONGTEXT', 'LOOP', 'LOW_PRIORITY', 'MASTER_HEARTBEAT_PERIOD', 'MASTER_HEARTBEAT_PERIOD', 'MASTER_SSL_VERIFY_SERVER_CERT', 'MATCH', 'MAXVALUE', 'MAXVALUE', 'MEDIUMBLOB', 'MEDIUMINT', 'MEDIUMTEXT', 'MIDDLEINT', 'MINUTE_MICROSECOND', 'MINUTE_SECOND', 'MOD', 'MODIFIES', 'NATURAL', 'NO_WRITE_TO_BINLOG', 'NOT', 'NULL', 'NUMERIC', 'ON', 'OPTIMIZE', 'OPTION', 'OPTIONALLY', 'OR', 'ORDER', 'OUT', 'OUTER', 'OUTFILE', 'PRECISION', 'PRIMARY', 'PROCEDURE', 'PURGE', 'RANGE', 'READ', 'READ_WRITE', 'READS', 'REAL', 'REFERENCES', 'REGEXP', 'RELEASE', 'RENAME', 'REPEAT', 'REPLACE', 'REQUIRE', 'RESIGNAL', 'RESIGNAL', 'RESTRICT', 'RETURN', 'REVOKE', 'RIGHT', 'RLIKE', 'SCHEMA', 'SCHEMAS', 'SECOND_MICROSECOND', 'SELECT', 'SENSITIVE', 'SEPARATOR', 'SET', 'SHOW', 'SIGNAL', 'SIGNAL', 'SMALLINT', 'SPATIAL', 'SPECIFIC', 'SQL', 'SQL_BIG_RESULT', 'SQL_CALC_FOUND_ROWS', 'SQL_SMALL_RESULT', 'SQLEXCEPTION', 'SQLSTATE', 'SQLWARNING', 'SSL', 'STARTING', 'STRAIGHT_JOIN', 'TABLE', 'TERMINATED', 'THEN', 'TINYBLOB', 'TINYINT', 'TINYTEXT', 'TO', 'TRAILING', 'TRIGGER', 'TRUE', 'UNDO', 'UNION', 'UNIQUE', 'UNLOCK', 'UNSIGNED', 'UPDATE', 'USAGE', 'USE', 'USING', 'UTC_DATE', 'UTC_TIME', 'UTC_TIMESTAMP', 'VALUES', 'VARBINARY', 'VARCHAR', 'VARCHARACTER', 'VARYING', 'WHEN', 'WHERE', 'WHILE', 'WITH', 'WRITE', 'XOR', 'YEAR_MONTH', 'ZEROFILL', )) MSSQL = set(( 'ADD', 'ALL', 'ALTER', 'AND', 'ANY', 'AS', 'ASC', 'AUTHORIZATION', 'BACKUP', 'BEGIN', 'BETWEEN', 'BREAK', 'BROWSE', 'BULK', 'BY', 'CASCADE', 'CASE', 'CHECK', 'CHECKPOINT', 'CLOSE', 'CLUSTERED', 'COALESCE', 'COLLATE', 'COLUMN', 'COMMIT', 'COMPUTE', 'CONSTRAINT', 'CONTAINS', 'CONTAINSTABLE', 'CONTINUE', 'CONVERT', 'CREATE', 'CROSS', 'CURRENT', 'CURRENT_DATE', 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'CURRENT_USER', 'CURSOR', 'DATABASE', 'DBCC', 'DEALLOCATE', 'DECLARE', 'DEFAULT', 'DELETE', 'DENY', 'DESC', 'DISK', 'DISTINCT', 'DISTRIBUTED', 'DOUBLE', 'DROP', 'DUMMY', 'DUMP', 'ELSE', 'END', 'ERRLVL', 'ESCAPE', 'EXCEPT', 'EXEC', 'EXECUTE', 'EXISTS', 'EXIT', 'FETCH', 'FILE', 'FILLFACTOR', 'FOR', 'FOREIGN', 'FREETEXT', 'FREETEXTTABLE', 'FROM', 'FULL', 'FUNCTION', 'GOTO', 'GRANT', 'GROUP', 'HAVING', 'HOLDLOCK', 'IDENTITY', 'IDENTITY_INSERT', 'IDENTITYCOL', 'IF', 'IN', 'INDEX', 'INNER', 'INSERT', 'INTERSECT', 'INTO', 'IS', 'JOIN', 'KEY', 'KILL', 'LEFT', 'LIKE', 'LINENO', 'LOAD', 'NATIONAL ', 'NOCHECK', 'NONCLUSTERED', 'NOT', 'NULL', 'NULLIF', 'OF', 'OFF', 'OFFSETS', 'ON', 'OPEN', 'OPENDATASOURCE', 'OPENQUERY', 'OPENROWSET', 'OPENXML', 'OPTION', 'OR', 'ORDER', 'OUTER', 'OVER', 'PERCENT', 'PLAN', 'PRECISION', 'PRIMARY', 'PRINT', 'PROC', 'PROCEDURE', 'PUBLIC', 'RAISERROR', 'READ', 'READTEXT', 'RECONFIGURE', 'REFERENCES', 'REPLICATION', 'RESTORE', 'RESTRICT', 'RETURN', 'REVOKE', 'RIGHT', 'ROLLBACK', 'ROWCOUNT', 'ROWGUIDCOL', 'RULE', 'SAVE', 'SCHEMA', 'SELECT', 'SESSION_USER', 'SET', 'SETUSER', 'SHUTDOWN', 'SOME', 'STATISTICS', 'SYSTEM_USER', 'TABLE', 'TEXTSIZE', 'THEN', 'TO', 'TOP', 'TRAN', 'TRANSACTION', 'TRIGGER', 'TRUNCATE', 'TSEQUAL', 'UNION', 'UNIQUE', 'UPDATE', 'UPDATETEXT', 'USE', 'USER', 'VALUES', 'VARYING', 'VIEW', 'WAITFOR', 'WHEN', 'WHERE', 'WHILE', 'WITH', 'WRITETEXT', )) ORACLE = set(( 'ACCESS', 'ADD', 'ALL', 'ALTER', 'AND', 'ANY', 'AS', 'ASC', 'AUDIT', 'BETWEEN', 'BY', 'CHAR', 'CHECK', 'CLUSTER', 'COLUMN', 'COMMENT', 'COMPRESS', 'CONNECT', 'CREATE', 'CURRENT', 'DATE', 'DECIMAL', 'DEFAULT', 'DELETE', 'DESC', 'DISTINCT', 'DROP', 'ELSE', 'EXCLUSIVE', 'EXISTS', 'FILE', 'FLOAT', 'FOR', 'FROM', 'GRANT', 'GROUP', 'HAVING', 'IDENTIFIED', 'IMMEDIATE', 'IN', 'INCREMENT', 'INDEX', 'INITIAL', 'INSERT', 'INTEGER', 'INTERSECT', 'INTO', 'IS', 'LEVEL', 'LIKE', 'LOCK', 'LONG', 'MAXEXTENTS', 'MINUS', 'MLSLABEL', 'MODE', 'MODIFY', 'NOAUDIT', 'NOCOMPRESS', 'NOT', 'NOWAIT', 'NULL', 'NUMBER', 'OF', 'OFFLINE', 'ON', 'ONLINE', 'OPTION', 'OR', 'ORDER', 'PCTFREE', 'PRIOR', 'PRIVILEGES', 'PUBLIC', 'RAW', 'RENAME', 'RESOURCE', 'REVOKE', 'ROW', 'ROWID', 'ROWNUM', 'ROWS', 'SELECT', 'SESSION', 'SET', 'SHARE', 'SIZE', 'SMALLINT', 'START', 'SUCCESSFUL', 'SYNONYM', 'SYSDATE', 'TABLE', 'THEN', 'TO', 'TRIGGER', 'UID', 'UNION', 'UNIQUE', 'UPDATE', 'USER', 'VALIDATE', 'VALUES', 'VARCHAR', 'VARCHAR2', 'VIEW', 'WHENEVER', 'WHERE', 'WITH', )) SQLITE = set(( 'ABORT', 'ACTION', 'ADD', 'AFTER', 'ALL', 'ALTER', 'ANALYZE', 'AND', 'AS', 'ASC', 'ATTACH', 'AUTOINCREMENT', 'BEFORE', 'BEGIN', 'BETWEEN', 'BY', 'CASCADE', 'CASE', 'CAST', 'CHECK', 'COLLATE', 'COLUMN', 'COMMIT', 'CONFLICT', 'CONSTRAINT', 'CREATE', 'CROSS', 'CURRENT_DATE', 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'DATABASE', 'DEFAULT', 'DEFERRABLE', 'DEFERRED', 'DELETE', 'DESC', 'DETACH', 'DISTINCT', 'DROP', 'EACH', 'ELSE', 'END', 'ESCAPE', 'EXCEPT', 'EXCLUSIVE', 'EXISTS', 'EXPLAIN', 'FAIL', 'FOR', 'FOREIGN', 'FROM', 'FULL', 'GLOB', 'GROUP', 'HAVING', 'IF', 'IGNORE', 'IMMEDIATE', 'IN', 'INDEX', 'INDEXED', 'INITIALLY', 'INNER', 'INSERT', 'INSTEAD', 'INTERSECT', 'INTO', 'IS', 'ISNULL', 'JOIN', 'KEY', 'LEFT', 'LIKE', 'LIMIT', 'MATCH', 'NATURAL', 'NO', 'NOT', 'NOTNULL', 'NULL', 'OF', 'OFFSET', 'ON', 'OR', 'ORDER', 'OUTER', 'PLAN', 'PRAGMA', 'PRIMARY', 'QUERY', 'RAISE', 'REFERENCES', 'REGEXP', 'REINDEX', 'RELEASE', 'RENAME', 'REPLACE', 'RESTRICT', 'RIGHT', 'ROLLBACK', 'ROW', 'SAVEPOINT', 'SELECT', 'SET', 'TABLE', 'TEMP', 'TEMPORARY', 'THEN', 'TO', 'TRANSACTION', 'TRIGGER', 'UNION', 'UNIQUE', 'UPDATE', 'USING', 'VACUUM', 'VALUES', 'VIEW', 'VIRTUAL', 'WHEN', 'WHERE', )) # remove from here when you add a list. JDBCSQLITE = SQLITE DB2 = INFORMIX = INGRES = JDBCPOSTGRESQL = COMMON ADAPTERS = { 'sqlite': SQLITE, 'mysql': MYSQL, 'postgres': POSTGRESQL, 'postgres_nonreserved': POSTGRESQL_NONRESERVED, 'oracle': ORACLE, 'mssql': MSSQL, 'mssql2': MSSQL, 'db2': DB2, 'informix': INFORMIX, 'firebird': FIREBIRD, 'firebird_embedded': FIREBIRD, 'firebird_nonreserved': FIREBIRD_NONRESERVED, 'ingres': INGRES, 'ingresu': INGRES, 'jdbc:sqlite': JDBCSQLITE, 'jdbc:postgres': JDBCPOSTGRESQL, 'common': COMMON, } ADAPTERS['all'] = reduce(lambda a,b:a.union(b),(x for x in ADAPTERS.values()))
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>, limodou <limodou@gmail.com> and srackham <srackham@gmail.com>. License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) """ import os import sys import code import logging import types import re import optparse import glob import fileutils import settings from utils import web2py_uuid from compileapp import build_environment, read_pyc, run_models_in from restricted import RestrictedError from globals import Request, Response, Session from storage import Storage from admin import w2p_unpack logger = logging.getLogger("web2py") def exec_environment( pyfile='', request=None, response=None, session=None, ): """ .. function:: gluon.shell.exec_environment([pyfile=''[, request=Request() [, response=Response[, session=Session()]]]]) Environment builder and module loader. Builds a web2py environment and optionally executes a Python file into the environment. A Storage dictionary containing the resulting environment is returned. The working directory must be web2py root -- this is the web2py default. """ if request==None: request = Request() if response==None: response = Response() if session==None: session = Session() if request.folder is None: mo = re.match(r'(|.*/)applications/(?P<appname>[^/]+)', pyfile) if mo: appname = mo.group('appname') request.folder = os.path.join('applications', appname) else: request.folder = '' env = build_environment(request, response, session, store_current=False) if pyfile: pycfile = pyfile + 'c' if os.path.isfile(pycfile): exec read_pyc(pycfile) in env else: execfile(pyfile, env) return Storage(env) def env( a, import_models=False, c=None, f=None, dir='', extra_request={}, ): """ Return web2py execution environment for application (a), controller (c), function (f). If import_models is True the exec all application models into the environment. extra_request allows you to pass along any extra variables to the request object before your models get executed. This was mainly done to support web2py_utils.test_runner, however you can use it with any wrapper scripts that need access to the web2py environment. """ request = Request() response = Response() session = Session() request.application = a # Populate the dummy environment with sensible defaults. if not dir: request.folder = os.path.join('applications', a) else: request.folder = dir request.controller = c or 'default' request.function = f or 'index' response.view = '%s/%s.html' % (request.controller, request.function) request.env.path_info = '/%s/%s/%s' % (a, c, f) request.env.http_host = '127.0.0.1:8000' request.env.remote_addr = '127.0.0.1' request.env.web2py_runtime_gae = settings.global_settings.web2py_runtime_gae for k,v in extra_request.items(): request[k] = v # Monkey patch so credentials checks pass. def check_credentials(request, other_application='admin'): return True fileutils.check_credentials = check_credentials environment = build_environment(request, response, session) if import_models: try: run_models_in(environment) except RestrictedError, e: sys.stderr.write(e.traceback+'\n') sys.exit(1) environment['__name__'] = '__main__' return environment def exec_pythonrc(): pythonrc = os.environ.get('PYTHONSTARTUP') if pythonrc and os.path.isfile(pythonrc): try: execfile(pythonrc) except NameError: pass def run( appname, plain=False, import_models=False, startfile=None, bpython=False ): """ Start interactive shell or run Python script (startfile) in web2py controller environment. appname is formatted like: a web2py application name a/c exec the controller c into the application environment """ (a, c, f) = parse_path_info(appname) errmsg = 'invalid application name: %s' % appname if not a: die(errmsg) adir = os.path.join('applications', a) if not os.path.exists(adir): if raw_input('application %s does not exist, create (y/n)?' % a).lower() in ['y', 'yes']: os.mkdir(adir) w2p_unpack('welcome.w2p', adir) for subfolder in ['models','views','controllers', 'databases', 'modules','cron','errors','sessions', 'languages','static','private','uploads']: subpath = os.path.join(adir,subfolder) if not os.path.exists(subpath): os.mkdir(subpath) db = os.path.join(adir,'models/db.py') if os.path.exists(db): data = fileutils.read_file(db) data = data.replace('<your secret key>','sha512:'+web2py_uuid()) fileutils.write_file(db, data) if c: import_models = True _env = env(a, c=c, import_models=import_models) if c: cfile = os.path.join('applications', a, 'controllers', c + '.py') if not os.path.isfile(cfile): cfile = os.path.join('applications', a, 'compiled', "controllers_%s_%s.pyc" % (c,f)) if not os.path.isfile(cfile): die(errmsg) else: exec read_pyc(cfile) in _env else: execfile(cfile, _env) if f: exec ('print %s()' % f, _env) elif startfile: exec_pythonrc() try: execfile(startfile, _env) except RestrictedError, e: print e.traceback else: if not plain: if bpython: try: import bpython bpython.embed(locals_=_env) return except: logger.warning( 'import bpython error; trying ipython...') else: try: import IPython # following 2 lines fix a problem with IPython; thanks Michael Toomim if '__builtins__' in _env: del _env['__builtins__'] shell = IPython.Shell.IPShell(argv=[], user_ns=_env) shell.mainloop() return except: logger.warning( 'import IPython error; use default python shell') try: import readline import rlcompleter except ImportError: pass else: readline.set_completer(rlcompleter.Completer(_env).complete) readline.parse_and_bind('tab:complete') exec_pythonrc() code.interact(local=_env) def parse_path_info(path_info): """ Parse path info formatted like a/c/f where c and f are optional and a leading / accepted. Return tuple (a, c, f). If invalid path_info a is set to None. If c or f are omitted they are set to None. """ mo = re.match(r'^/?(?P<a>\w+)(/(?P<c>\w+)(/(?P<f>\w+))?)?$', path_info) if mo: return (mo.group('a'), mo.group('c'), mo.group('f')) else: return (None, None, None) def die(msg): print >> sys.stderr, msg sys.exit(1) def test(testpath, import_models=True, verbose=False): """ Run doctests in web2py environment. testpath is formatted like: a tests all controllers in application a a/c tests controller c in application a a/c/f test function f in controller c, application a Where a, c and f are application, controller and function names respectively. If the testpath is a file name the file is tested. If a controller is specified models are executed by default. """ import doctest if os.path.isfile(testpath): mo = re.match(r'(|.*/)applications/(?P<a>[^/]+)', testpath) if not mo: die('test file is not in application directory: %s' % testpath) a = mo.group('a') c = f = None files = [testpath] else: (a, c, f) = parse_path_info(testpath) errmsg = 'invalid test path: %s' % testpath if not a: die(errmsg) cdir = os.path.join('applications', a, 'controllers') if not os.path.isdir(cdir): die(errmsg) if c: cfile = os.path.join(cdir, c + '.py') if not os.path.isfile(cfile): die(errmsg) files = [cfile] else: files = glob.glob(os.path.join(cdir, '*.py')) for testfile in files: globs = env(a, import_models) ignores = globs.keys() execfile(testfile, globs) def doctest_object(name, obj): """doctest obj and enclosed methods and classes.""" if type(obj) in (types.FunctionType, types.TypeType, types.ClassType, types.MethodType, types.UnboundMethodType): # Reload environment before each test. globs = env(a, c=c, f=f, import_models=import_models) execfile(testfile, globs) doctest.run_docstring_examples(obj, globs=globs, name='%s: %s' % (os.path.basename(testfile), name), verbose=verbose) if type(obj) in (types.TypeType, types.ClassType): for attr_name in dir(obj): # Execute . operator so decorators are executed. o = eval('%s.%s' % (name, attr_name), globs) doctest_object(attr_name, o) for (name, obj) in globs.items(): if name not in ignores and (f is None or f == name): doctest_object(name, obj) def get_usage(): usage = """ %prog [options] pythonfile """ return usage def execute_from_command_line(argv=None): if argv is None: argv = sys.argv parser = optparse.OptionParser(usage=get_usage()) parser.add_option('-S', '--shell', dest='shell', metavar='APPNAME', help='run web2py in interactive shell or IPython(if installed) ' + \ 'with specified appname') msg = 'run web2py in interactive shell or bpython (if installed) with' msg += ' specified appname (if app does not exist it will be created).' msg += '\n Use combined with --shell' parser.add_option( '-B', '--bpython', action='store_true', default=False, dest='bpython', help=msg, ) parser.add_option( '-P', '--plain', action='store_true', default=False, dest='plain', help='only use plain python shell, should be used with --shell option', ) parser.add_option( '-M', '--import_models', action='store_true', default=False, dest='import_models', help='auto import model files, default is False, ' + \ ' should be used with --shell option', ) parser.add_option( '-R', '--run', dest='run', metavar='PYTHON_FILE', default='', help='run PYTHON_FILE in web2py environment, ' + \ 'should be used with --shell option', ) (options, args) = parser.parse_args(argv[1:]) if len(sys.argv) == 1: parser.print_help() sys.exit(0) if len(args) > 0: startfile = args[0] else: startfile = '' run(options.shell, options.plain, startfile=startfile, bpython=options.bpython) if __name__ == '__main__': execute_from_command_line()
Python