From 886f84778cd97b4129ef33f4401ef9a6de635f37 Mon Sep 17 00:00:00 2001 From: timnyborg Date: Mon, 15 Dec 2014 11:03:47 +0000 Subject: [PATCH 01/45] Update sqlhtml.py Correcting some bootstrap3 icon classes --- gluon/sqlhtml.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gluon/sqlhtml.py b/gluon/sqlhtml.py index 6a8abffc..a19904a0 100644 --- a/gluon/sqlhtml.py +++ b/gluon/sqlhtml.py @@ -1987,9 +1987,9 @@ class SQLFORM(FORM): buttonback='icon leftarrow icon-arrow-left glyphicon glyphicon-arrow-left', buttonexport='icon downarrow icon-download glyphicon glyphicon-download', buttondelete='icon trash icon-trash glyphicon glyphicon-trash', - buttonedit='icon pen icon-pencil glyphicon glyphicon-arrow-pencil', + buttonedit='icon pen icon-pencil glyphicon glyphicon-pencil', buttontable='icon rightarrow icon-arrow-right glyphicon glyphicon-arrow-right', - buttonview='icon magnifier icon-zoom-in glyphicon glyphicon-arrow-zoom-in', + buttonview='icon magnifier icon-zoom-in glyphicon glyphicon-oom-in', ) elif not isinstance(ui, dict): raise RuntimeError('SQLFORM.grid ui argument must be a dictionary') From 0024307e6c423567cf96752c3c2f5dc6e4b99398 Mon Sep 17 00:00:00 2001 From: Mariano Reingart Date: Mon, 15 Dec 2014 15:45:27 -0300 Subject: [PATCH 02/45] Fix debugger interaction due new DAL Originally, __all__ was used to filter DAL and Field globals, but now the new module doesn't explicity set that attribute, so this filter was removed. Note that using __dict__ as a replacement is not an option, as the new dal module exports a lot of common names like connection, base, etc. --- applications/admin/controllers/debug.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/applications/admin/controllers/debug.py b/applications/admin/controllers/debug.py index c5f9bd4f..8c8522ac 100644 --- a/applications/admin/controllers/debug.py +++ b/applications/admin/controllers/debug.py @@ -72,8 +72,7 @@ def interact(): f_globals = {} for name, value in env['globals'].items(): if name not in gluon.html.__all__ and \ - name not in gluon.validators.__all__ and \ - name not in gluon.dal.__all__: + name not in gluon.validators.__all__: f_globals[name] = pydoc.text.repr(value) else: f_locals = {} From c0536d3b7487e73599b1f2ae1fcb963b91d41e8f Mon Sep 17 00:00:00 2001 From: Tim Nyborg Date: Tue, 16 Dec 2014 11:47:33 +0000 Subject: [PATCH 03/45] Allow map_hyphen to work for application names 1. Handle hyphen -> underscore replacement of the app name early in map_app(), so the application can be identified and its routing rules used (if they exist). Without this, the rewriter fails to find the application with the hyphen in place, and reverts to the default. 2. Disable underscore -> hyphen mapping of app name when creating static URLs, as they will be invalid paths --- gluon/rewrite.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/gluon/rewrite.py b/gluon/rewrite.py index eabefc2c..23a0dac9 100644 --- a/gluon/rewrite.py +++ b/gluon/rewrite.py @@ -878,7 +878,10 @@ class MapUrlIn(object): self.domain_application = None self.domain_controller = None self.domain_function = None - arg0 = self.harg0 + if base.map_hyphen: + arg0 = self.harg0.replace('-', '_') + else: + arg0 = self.harg0 if not base.exclusive_domain and base.applications and arg0 in base.applications: self.application = arg0 elif not base.exclusive_domain and arg0 and not base.applications: @@ -1256,9 +1259,9 @@ class MapUrlOut(object): "Builds a/c/f from components" acf = '' if self.map_hyphen: - self.application = self.application.replace('_', '-') self.controller = self.controller.replace('_', '-') if self.controller != 'static' and not self.controller.startswith('static/'): + self.application = self.application.replace('_', '-') self.function = self.function.replace('_', '-') if not self.omit_application: acf += '/' + self.application From 23ee6bd2cf72498ecec0b8b4f331990ca86e43a2 Mon Sep 17 00:00:00 2001 From: Tim Nyborg Date: Tue, 16 Dec 2014 12:00:23 +0000 Subject: [PATCH 04/45] Update rewrite.py --- gluon/rewrite.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/gluon/rewrite.py b/gluon/rewrite.py index 23a0dac9..661a0d27 100644 --- a/gluon/rewrite.py +++ b/gluon/rewrite.py @@ -878,10 +878,8 @@ class MapUrlIn(object): self.domain_application = None self.domain_controller = None self.domain_function = None - if base.map_hyphen: - arg0 = self.harg0.replace('-', '_') - else: - arg0 = self.harg0 + self.map_hyphen = base.map_hyphen + arg0 = self.harg0 if not base.exclusive_domain and base.applications and arg0 in base.applications: self.application = arg0 elif not base.exclusive_domain and arg0 and not base.applications: From d93810697f19d1c1a72d76d8f25991f8f6779479 Mon Sep 17 00:00:00 2001 From: ilvalle Date: Tue, 16 Dec 2014 20:32:51 +0100 Subject: [PATCH 05/45] fix cache clear with regex and tests --- gluon/cache.py | 6 ++++-- gluon/tests/test_cache.py | 12 ++++++++---- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/gluon/cache.py b/gluon/cache.py index 8cbe14b2..bac5a37f 100644 --- a/gluon/cache.py +++ b/gluon/cache.py @@ -128,10 +128,10 @@ class CacheAbstract(object): Auxiliary function called by `clear` to search and clear cache entries """ r = re.compile(regex) - for key in storage: + for key in storage.keys(): if r.match(str(key)): del storage[key] - break + return class CacheInRam(CacheAbstract): @@ -321,6 +321,8 @@ class CacheOnDisk(CacheAbstract): for filename in filenames: yield filename + def keys(self): + return [filename for dirpath, dirnames, filenames in os.walk(self.folder) for filename in filenames] def get(self, key, default=None): try: diff --git a/gluon/tests/test_cache.py b/gluon/tests/test_cache.py index 39b0605a..1522c6f0 100644 --- a/gluon/tests/test_cache.py +++ b/gluon/tests/test_cache.py @@ -37,7 +37,6 @@ class TestCache(unittest.TestCase): def testCacheInRam(self): # defaults to mode='http' - cache = CacheInRam() self.assertEqual(cache('a', lambda: 1, 0), 1) self.assertEqual(cache('a', lambda: 2, 100), 1) @@ -66,7 +65,6 @@ class TestCache(unittest.TestCase): def testCacheOnDisk(self): # defaults to mode='http' - s = Storage({'application': 'admin', 'folder': 'applications/admin'}) cache = CacheOnDisk(s) @@ -102,8 +100,14 @@ class TestCache(unittest.TestCase): self.assertEqual(prefix('a', lambda: 2, 100), 1) self.assertEqual(cache.ram('prefixa', lambda: 2, 100), 1) - - + def testRegex(self): + cache = CacheInRam() + self.assertEqual(cache('a1', lambda: 1, 0), 1) + self.assertEqual(cache('a2', lambda: 2, 100), 2) + cache.clear(regex=r'a*') + self.assertEqual(cache('a1', lambda: 2, 0), 2) + self.assertEqual(cache('a2', lambda: 3, 100), 3) + return if __name__ == '__main__': setUpModule() # pre-python-2.7 From 8d7207420963f09f333bc21bfb935394cbe3f8b9 Mon Sep 17 00:00:00 2001 From: ilvalle Date: Wed, 17 Dec 2014 17:28:30 +0100 Subject: [PATCH 06/45] issue 2024: response.json sets by default content-type to application/json --- gluon/globals.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/gluon/globals.py b/gluon/globals.py index 7091f40c..f2c13882 100644 --- a/gluon/globals.py +++ b/gluon/globals.py @@ -626,6 +626,8 @@ class Response(Storage): return self.stream(stream, chunk_size=chunk_size, request=request) def json(self, data, default=None): + if 'Content-Type' not in self.headers: + self.headers['Content-Type'] = contenttype('.json') return json(data, default=default or custom_json) def xmlrpc(self, request, methods): From 952890d9cc4256c1628b5df01375821fa7279ab9 Mon Sep 17 00:00:00 2001 From: ilvalle Date: Thu, 18 Dec 2014 09:34:46 +0100 Subject: [PATCH 07/45] set directly 'application/json' to avoid a call to contenttype --- gluon/globals.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gluon/globals.py b/gluon/globals.py index f2c13882..166a8f8b 100644 --- a/gluon/globals.py +++ b/gluon/globals.py @@ -627,7 +627,7 @@ class Response(Storage): def json(self, data, default=None): if 'Content-Type' not in self.headers: - self.headers['Content-Type'] = contenttype('.json') + self.headers['Content-Type'] = 'application/json' return json(data, default=default or custom_json) def xmlrpc(self, request, methods): From 9b490340e52c46c75d5f668de5fecc76e1e47f4a Mon Sep 17 00:00:00 2001 From: Jack Kuan Date: Thu, 18 Dec 2014 10:15:13 -1000 Subject: [PATCH 08/45] Fix the problem with chunked encoding with an empty body. When the response body is empty, rocket won't send the final zero-length terminating chunk for chunked encoding. I think this causes the browser to wait for the connection close in order to tell the end of the response. --- gluon/rocket.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/gluon/rocket.py b/gluon/rocket.py index 373c46b3..eb7c5c57 100644 --- a/gluon/rocket.py +++ b/gluon/rocket.py @@ -1850,12 +1850,13 @@ class WSGIWorker(Worker): if data: self.write(data, sections) + if not self.headers_sent: + # Send headers if the body was empty + self.send_headers('', sections) + if self.chunked: # If chunked, send our final chunk length self.conn.sendall(b('0\r\n\r\n')) - elif not self.headers_sent: - # Send headers if the body was empty - self.send_headers('', sections) # Don't capture exceptions here. The Worker class handles # them appropriately. From 913234382069f1990e964e5a82f8f8b44c3a8e2e Mon Sep 17 00:00:00 2001 From: niphlod Date: Thu, 18 Dec 2014 23:48:10 +0100 Subject: [PATCH 09/45] better assignment (tasks go to not running workers only). Thanks @PengfeiYu - pep8 adjustments - tasks were assigned to all ACTIVE workers... if a worker is busy processing a task, there's no point on assigning tasks to it --- gluon/scheduler.py | 54 +++++++++++++++++++++++++++++----------------- 1 file changed, 34 insertions(+), 20 deletions(-) diff --git a/gluon/scheduler.py b/gluon/scheduler.py index 254c442f..91ae2e92 100644 --- a/gluon/scheduler.py +++ b/gluon/scheduler.py @@ -87,11 +87,17 @@ if 'WEB2PY_PATH' not in os.environ: os.environ['WEB2PY_PATH'] = path try: - from gluon.contrib.simplejson import loads, dumps -except: + # try external module from simplejson import loads, dumps +except ImportError: + try: + # try stdlib (Python >= 2.6) + from json import loads, dumps + except: + # fallback to pure-Python module + from gluon.contrib.simplejson import loads, dumps -IDENTIFIER = "%s#%s" % (socket.gethostname(),os.getpid()) +IDENTIFIER = "%s#%s" % (socket.gethostname(), os.getpid()) logger = logging.getLogger('web2py.scheduler.%s' % IDENTIFIER) @@ -160,6 +166,7 @@ class TaskReport(object): def __str__(self): return '' % self.status + class JobGraph(object): """Experimental: with JobGraph you can specify dependencies amongs tasks""" @@ -170,7 +177,9 @@ class JobGraph(object): def add_deps(self, task_parent, task_child): """Creates a dependency between task_parent and task_child""" - self.db.scheduler_task_deps.insert(task_parent=task_parent, task_child=task_child, job_name=self.job_name) + self.db.scheduler_task_deps.insert(task_parent=task_parent, + task_child=task_child, + job_name=self.job_name) def validate(self, job_name): """Validates if all tasks job_name can be completed, i.e. there @@ -195,16 +204,18 @@ class JobGraph(object): try: rtn = [] for k, v in nested_dict.items(): - v.discard(k) # Ignore self dependencies + v.discard(k) # Ignore self dependencies extra_items_in_deps = reduce(set.union, nested_dict.values()) - set(nested_dict.keys()) nested_dict.update(dict((item, set()) for item in extra_items_in_deps)) while True: - ordered = set(item for item,dep in nested_dict.items() if not dep) + ordered = set(item for item, dep in nested_dict.items() if not dep) if not ordered: break rtn.append(ordered) - nested_dict = dict((item, (dep - ordered)) for item, dep in nested_dict.items() - if item not in ordered) + nested_dict = dict( + (item, (dep - ordered)) for item, dep in nested_dict.items() + if item not in ordered + ) assert not nested_dict, "A cyclic dependency exists amongst %r" % nested_dict db.commit() return rtn @@ -212,6 +223,7 @@ class JobGraph(object): db.rollback() return None + def demo_function(*argv, **kwargs): """ test function """ for i in range(argv[0]): @@ -268,7 +280,7 @@ def executor(queue, task, out): def write(self, data): self.out_queue.put(data) - W2P_TASK = Storage({'id' : task.task_id, 'uuid' : task.uuid}) + W2P_TASK = Storage({'id': task.task_id, 'uuid': task.uuid}) stdout = LogOutput(out) try: if task.app: @@ -293,7 +305,7 @@ def executor(queue, task, out): raise NameError( "name '%s' not found in scheduler's environment" % f) #Inject W2P_TASK into environment - _env.update({'W2P_TASK' : W2P_TASK}) + _env.update({'W2P_TASK': W2P_TASK}) #Inject W2P_TASK into current from gluon import current current.W2P_TASK = W2P_TASK @@ -357,8 +369,7 @@ class MetaScheduler(threading.Thread): start = time.time() - while p.is_alive() and ( - not task.timeout or time.time() - start < task.timeout): + while p.is_alive() and (not task.timeout or time.time() - start < task.timeout): if tout: try: logger.debug(' partial output saved') @@ -568,7 +579,7 @@ class Scheduler(MetaScheduler): queue=0, distribution=None, workers=0) - ) #dict holding statistics + ) # dict holding statistics from gluon import current current._scheduler = self @@ -740,7 +751,7 @@ class Scheduler(MetaScheduler): contention and retries `assign_task` after 0.5 seconds """ logger.debug('Assigning tasks...') - db.commit() #db.commit() only for Mysql + db.commit() # db.commit() only for Mysql x = 0 while x < 10: try: @@ -761,7 +772,7 @@ class Scheduler(MetaScheduler): contention and retries `pop_task` after 0.5 seconds """ db = self.db - db.commit() #another nifty db.commit() only for Mysql + db.commit() # another nifty db.commit() only for Mysql x = 0 while x < 10: try: @@ -1077,6 +1088,8 @@ class Scheduler(MetaScheduler): #build workers as dict of groups wkgroups = {} for w in all_workers: + if w.worker_stats['status'] == 'RUNNING': + continue group_names = w.group_names for gname in group_names: if gname not in wkgroups: @@ -1090,8 +1103,9 @@ class Scheduler(MetaScheduler): db( (st.status.belongs((QUEUED, ASSIGNED))) & (st.stop_time < now) - ).update(status=EXPIRED) + ).update(status=EXPIRED) + #calculate dependencies deps_with_no_deps = db( (sd.can_visit == False) & (~sd.task_child.belongs( @@ -1163,7 +1177,7 @@ class Scheduler(MetaScheduler): if not task.task_name: d['task_name'] = task.function_name db( - (st.id==task.id) & + (st.id == task.id) & (st.status.belongs((QUEUED, ASSIGNED))) ).update(**d) wkgroups[gname]['workers'][myw]['c'] += 1 @@ -1207,8 +1221,8 @@ class Scheduler(MetaScheduler): else: for group in group_names: workers = self.db( - (ws.group_names.contains(group)) & - (~ws.status.belongs(exclusion)) + (ws.group_names.contains(group)) & + (~ws.status.belongs(exclusion)) )._select(ws.id, limitby=(0,limit)) self.db(ws.id.belongs(workers)).update(status=action) @@ -1339,7 +1353,7 @@ class Scheduler(MetaScheduler): **dict(orderby=orderby, left=left, limitby=(0, 1)) - ).first() + ).first() if row and output: row.result = row.scheduler_run.run_result and \ loads(row.scheduler_run.run_result, From 9825bbc92685dc5878a2a208236c39f927579ced Mon Sep 17 00:00:00 2001 From: ilvalle Date: Fri, 19 Dec 2014 14:42:17 +0100 Subject: [PATCH 10/45] fix issue 1931: preserve vars in grid search --- gluon/sqlhtml.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/gluon/sqlhtml.py b/gluon/sqlhtml.py index 6a8abffc..74fdb036 100644 --- a/gluon/sqlhtml.py +++ b/gluon/sqlhtml.py @@ -2385,6 +2385,8 @@ class SQLFORM(FORM): spanel_id = '%s_query_fields' % prefix sfields_id = '%s_query_panel' % prefix skeywords_id = '%s_keywords' % prefix + ## hidden fields to presever keywords in url after the submit + hidden_fields = [INPUT(_type='hidden', _value=value, _name=key) for key, value in request.get_vars.items() if key not in ['keywords', 'page']] search_widget = lambda sfield, url: CAT(FORM( INPUT(_name='keywords', _value=keywords, _id=skeywords_id,_class='form-control', @@ -2393,7 +2395,9 @@ class SQLFORM(FORM): INPUT(_type='submit', _value=T('Search'), _class="btn btn-default"), INPUT(_type='submit', _value=T('Clear'), _class="btn btn-default", _onclick="jQuery('#%s').val('');" % skeywords_id), + *hidden_fields, _method="GET", _action=url), search_menu) + # TODO vars from the url should be removed, they are not used by the submit form = search_widget and search_widget(sfields, url()) or '' console.append(add) console.append(form) From 39af574e7f7edfbcbb52678ce19ecc72f7c6dfe0 Mon Sep 17 00:00:00 2001 From: Jack Kuan Date: Fri, 19 Dec 2014 23:44:55 -1000 Subject: [PATCH 11/45] Avoid sending the terminating chunk in case it's a HEAD request. --- gluon/rocket.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gluon/rocket.py b/gluon/rocket.py index eb7c5c57..97f317bd 100644 --- a/gluon/rocket.py +++ b/gluon/rocket.py @@ -1854,7 +1854,7 @@ class WSGIWorker(Worker): # Send headers if the body was empty self.send_headers('', sections) - if self.chunked: + if self.chunked and self.request_method != 'HEAD': # If chunked, send our final chunk length self.conn.sendall(b('0\r\n\r\n')) From 207f53fd6f7e32e5d225eec4e52e5f8fb850bbec Mon Sep 17 00:00:00 2001 From: ilvalle Date: Sat, 20 Dec 2014 17:47:55 +0100 Subject: [PATCH 12/45] fix issue 2029: response.stream bug with spaces in filename --- gluon/globals.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gluon/globals.py b/gluon/globals.py index 7091f40c..2ca5e098 100644 --- a/gluon/globals.py +++ b/gluon/globals.py @@ -551,7 +551,7 @@ class Response(Storage): else: attname = filename headers["Content-Disposition"] = \ - "attachment;filename=%s" % attname + 'attachment;filename="%s"' % attname if not request: request = current.request From ce025a6b8e55fa7f928fe28fdaaa602b85ac7868 Mon Sep 17 00:00:00 2001 From: niphlod Date: Sun, 21 Dec 2014 20:30:18 +0100 Subject: [PATCH 13/45] new module appconfig.py --- gluon/contrib/appconfig.py | 123 +++++++++++++++++++++++++++++++++++ gluon/tests/test_contribs.py | 38 ++++++++++- 2 files changed, 158 insertions(+), 3 deletions(-) create mode 100644 gluon/contrib/appconfig.py diff --git a/gluon/contrib/appconfig.py b/gluon/contrib/appconfig.py new file mode 100644 index 00000000..972247f6 --- /dev/null +++ b/gluon/contrib/appconfig.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +Read from configuration files easily without hurting performances + +USAGE: +During development you can load a config file either in .ini or .json +format (by default app/private/appconfig.ini or app/private/appconfig.json) +The result is a dict holding the configured values. Passing reload=True +is meant only for development: in production, leave reload to False and all +values will be cached + +from gluon.contrib.appconfig import AppConfig +myconfig = AppConfig(path_to_configfile, reload=False) + +print myconfig['db']['uri'] + +The returned dict can walk with "dot notation" an arbitrarely nested dict + +print myconfig.take('db.uri') + +You can even pass a cast function, i.e. + +print myconfig.take('auth.expiration', cast=int) + +Once the value has been fetched (and casted) it won't change until the process +is restarted (or reload=True is passed). + +""" +import thread +import os +from ConfigParser import SafeConfigParser +from gluon import current +from gluon.serializers import json_parser + +locker = thread.allocate_lock() + + +def AppConfig(*args, **vars): + + locker.acquire() + reload_ = vars.pop('reload', False) + try: + instance_name = 'AppConfig_' + current.request.application + if reload_ or not hasattr(AppConfig, instance_name): + setattr(AppConfig, instance_name, AppConfigLoader(*args, **vars)) + return getattr(AppConfig, instance_name).settings + finally: + locker.release() + + +class AppConfigDict(dict): + """ + dict that has a .take() method to fetch nested values and puts + them into cache + """ + + def __init__(self, *args, **kwargs): + dict.__init__(self, *args, **kwargs) + self.int_cache = {} + + def take(self, path, cast=None): + parts = path.split('.') + if path in self.int_cache: + return self.int_cache[path] + value = self + walking = [] + for part in parts: + if part not in value: + raise BaseException("%s not in config [%s]" % + (part, '-->'.join(walking))) + value = value[part] + walking.append(part) + if cast is None: + self.int_cache[path] = value + else: + try: + value = cast(value) + self.int_cache[path] = value + except (ValueError, TypeError): + raise BaseException("%s can't be converted to %s" % + (value, cast)) + return value + + +class AppConfigLoader(object): + + def __init__(self, configfile=None): + if not configfile: + priv_folder = os.path.join(current.request.folder, 'private') + configfile = os.path.join(priv_folder, 'appconfig.ini') + if not os.path.isfile(configfile): + configfile = os.path.join(priv_folder, 'appconfig.json') + if not os.path.isfile(configfile): + configfile = None + if not configfile or not os.path.isfile(configfile): + raise BaseException("Config file not found") + self.file = configfile + self.ctype = os.path.splitext(configfile)[1][1:] + self.settings = None + self.read_config() + + def read_config_ini(self): + config = SafeConfigParser() + config.read(self.file) + settings = {} + for section in config.sections(): + settings[section] = {} + for option in config.options(section): + settings[section][option] = config.get(section, option) + self.settings = AppConfigDict(settings) + + def read_config_json(self): + with open(self.file, 'r') as c: + self.settings = AppConfigDict(json_parser.load(c)) + + def read_config(self): + if self.settings is None: + try: + getattr(self, 'read_config_' + self.ctype)() + except AttributeError: + raise BaseException("Unsupported config file format") + return self.settings diff --git a/gluon/tests/test_contribs.py b/gluon/tests/test_contribs.py index 22f3978d..ed98082c 100644 --- a/gluon/tests/test_contribs.py +++ b/gluon/tests/test_contribs.py @@ -4,14 +4,24 @@ """ Unit tests for contribs """ import unittest +import os from fix_path import fix_sys_path fix_sys_path(__file__) +from gluon.storage import Storage +import gluon.contrib.fpdf as fpdf +import gluon.contrib.pyfpdf as pyfpdf +from gluon.contrib.appconfig import AppConfig -from utils import md5_hash -import contrib.fpdf as fpdf -import contrib.pyfpdf as pyfpdf + +def setUpModule(): + pass + + +def tearDownModule(): + if os.path.isfile('appconfig.json'): + os.unlink('appconfig.json') class TestContribs(unittest.TestCase): @@ -35,6 +45,28 @@ class TestContribs(unittest.TestCase): self.assertTrue(fpdf.FPDF_VERSION in pdf_out, 'version string') self.assertTrue('hello world' in pdf_out, 'sample message') + def test_appconfig(self): + """ + Test for the appconfig module + """ + from gluon import current + s = Storage({'application': 'admin', + 'folder': 'applications/admin'}) + current.request = s + simple_config = '{"config1" : "abc", "config2" : "bcd", "config3" : { "key1" : 1, "key2" : 2} }' + with open('appconfig.json', 'w') as g: + g.write(simple_config) + myappconfig = AppConfig('appconfig.json') + self.assertEqual(myappconfig['config1'], 'abc') + self.assertEqual(myappconfig['config2'], 'bcd') + self.assertEqual(myappconfig.take('config1'), 'abc') + self.assertEqual(myappconfig.take('config3.key1', cast=str), '1') + # once parsed, can't be casted to other types + self.assertEqual(myappconfig.take('config3.key1', cast=int), '1') + + self.assertEqual(myappconfig.take('config3.key2'), 2) + + current.request = {} if __name__ == '__main__': unittest.main() From cbe37bf60283149ddce13e1394f1fdc9144052e1 Mon Sep 17 00:00:00 2001 From: Erik Montes Date: Mon, 22 Dec 2014 20:41:49 -0800 Subject: [PATCH 14/45] class typo fix --- gluon/sqlhtml.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gluon/sqlhtml.py b/gluon/sqlhtml.py index 69862779..2058f291 100644 --- a/gluon/sqlhtml.py +++ b/gluon/sqlhtml.py @@ -1989,7 +1989,7 @@ class SQLFORM(FORM): buttondelete='icon trash icon-trash glyphicon glyphicon-trash', buttonedit='icon pen icon-pencil glyphicon glyphicon-pencil', buttontable='icon rightarrow icon-arrow-right glyphicon glyphicon-arrow-right', - buttonview='icon magnifier icon-zoom-in glyphicon glyphicon-oom-in', + buttonview='icon magnifier icon-zoom-in glyphicon glyphicon-zoom-in', ) elif not isinstance(ui, dict): raise RuntimeError('SQLFORM.grid ui argument must be a dictionary') From 29661ad881f6a21ccbaa95e6747c07491c6a30ee Mon Sep 17 00:00:00 2001 From: ilvalle Date: Tue, 23 Dec 2014 17:49:03 +0100 Subject: [PATCH 15/45] fix as_json serialization --- gluon/serializers.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/gluon/serializers.py b/gluon/serializers.py index a2ebfa03..97372773 100644 --- a/gluon/serializers.py +++ b/gluon/serializers.py @@ -100,6 +100,8 @@ def custom_json(o): return str(o) elif isinstance(o, XmlComponent): return str(o) + elif isinstance(o, set): + return list(o) elif hasattr(o, 'as_list') and callable(o.as_list): return o.as_list() elif hasattr(o, 'as_dict') and callable(o.as_dict): From 80261f52ed4ca7cdf7eb76fdfba81b381a067eb5 Mon Sep 17 00:00:00 2001 From: Mariano Reingart Date: Tue, 23 Dec 2014 16:58:04 -0300 Subject: [PATCH 16/45] Fix incorrect namespace in SOAP webservice response --- gluon/contrib/pysimplesoap/server.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gluon/contrib/pysimplesoap/server.py b/gluon/contrib/pysimplesoap/server.py index fb971494..b3175936 100755 --- a/gluon/contrib/pysimplesoap/server.py +++ b/gluon/contrib/pysimplesoap/server.py @@ -235,7 +235,7 @@ class SoapDispatcher(object): body.marshall("%s:Fault" % soap_ns, fault, ns=False) else: # return normal value - res = body.add_child("%sResponse" % name, ns=prefix) + res = body.add_child("%sResponse" % name, ns=self.namespace) if not prefix: res['xmlns'] = self.namespace # add target namespace From c0b32eaeecdcf25d4a446abb883cffa4a972d94f Mon Sep 17 00:00:00 2001 From: niphlod Date: Tue, 23 Dec 2014 21:24:27 +0100 Subject: [PATCH 17/45] more consistent badges with shields.io --- README.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.markdown b/README.markdown index e18a1361..306d5601 100644 --- a/README.markdown +++ b/README.markdown @@ -15,13 +15,13 @@ Then edit ./app.yaml and replace "yourappname" with yourappname. ## Documentation (readthedocs.org) -[![Docs Status](https://readthedocs.org/projects/web2py/badge/?version=latest)](http://web2py.rtfd.org/) +[![Docs Status](https://readthedocs.org/projects/web2py/badge/?version=latest&style=flat-square)](http://web2py.rtfd.org/) ## Tests -[![Build Status](https://travis-ci.org/web2py/web2py.png)](https://travis-ci.org/web2py/web2py) +[![Build Status](https://img.shields.io/travis/web2py/web2py.svg?style=flat-square)](https://travis-ci.org/web2py/web2py) -[![Coverage Status](https://coveralls.io/repos/web2py/web2py/badge.png)](https://coveralls.io/r/web2py/web2py) +[![Coverage Status](https://img.shields.io/coveralls/web2py/web2py.svg?style=flat-square)](https://coveralls.io/r/web2py/web2py) ## Installation Instructions From d7bc489e71d006010269dadf41deae8ee351258b Mon Sep 17 00:00:00 2001 From: ilvalle Date: Sun, 28 Dec 2014 17:19:17 +0100 Subject: [PATCH 18/45] fix issue 2011: capital letters in it.py --- applications/admin/languages/it.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/applications/admin/languages/it.py b/applications/admin/languages/it.py index 6b8040ef..87bb2efc 100644 --- a/applications/admin/languages/it.py +++ b/applications/admin/languages/it.py @@ -325,7 +325,7 @@ 'unable to uninstall "%s"': 'impossibile disinstallare "%s"', 'unable to upgrade because "%s"': 'impossibile aggiornare perché "%s"', 'uncheck all': 'smarca tutti', -'Uninstall': 'disinstalla', +'Uninstall': 'Disinstalla', 'update': 'aggiorna', 'update all languages': 'aggiorna tutti i linguaggi', 'Update:': 'Aggiorna:', @@ -348,7 +348,7 @@ 'Versioning': 'Versioning', 'View': 'Vista', 'view': 'vista', -'Views': 'viste', +'Views': 'Viste', 'views': 'viste', 'Web Framework': 'Web Framework', 'web2py is up to date': 'web2py è aggiornato', From e6de16b1118238fedd8eac9427ac7c11770ce121 Mon Sep 17 00:00:00 2001 From: ilvalle Date: Sat, 3 Jan 2015 11:58:08 +0100 Subject: [PATCH 19/45] fix issue 2003: double translation --- gluon/storage.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gluon/storage.py b/gluon/storage.py index 2c94079c..e12ee971 100644 --- a/gluon/storage.py +++ b/gluon/storage.py @@ -195,7 +195,7 @@ class Messages(Settings): def __getattr__(self, key): value = self[key] if isinstance(value, str): - return str(self.T(value)) + return self.T(value) return value class FastStorage(dict): From 3e1a918707a41250fd9f90306dbc396e4f953b82 Mon Sep 17 00:00:00 2001 From: ilvalle Date: Sat, 3 Jan 2015 14:11:06 +0100 Subject: [PATCH 20/45] Fix expression evaluation with postgres --- gluon/dal/adapters/base.py | 5 +++-- gluon/dal/adapters/postgres.py | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/gluon/dal/adapters/base.py b/gluon/dal/adapters/base.py index aad58af9..050edb68 100644 --- a/gluon/dal/adapters/base.py +++ b/gluon/dal/adapters/base.py @@ -76,7 +76,8 @@ class BaseAdapter(ConnectionPool): dbpath = None folder = None connector = lambda *args, **kwargs: None # __init__ should override this - + TRUE_exp = '1' + FALSE_exp = '0' TRUE = 'T' FALSE = 'F' T_SEP = ' ' @@ -909,7 +910,7 @@ class BaseAdapter(ConnectionPool): return ','.join(self.represent(item,field_type) \ for item in expression) elif isinstance(expression, bool): - return '1' if expression else '0' + return self.db._adapter.TRUE_exp if expression else self.db._adapter.FALSE_exp else: return str(expression) diff --git a/gluon/dal/adapters/postgres.py b/gluon/dal/adapters/postgres.py index 7e81d6c8..7e8c32fd 100644 --- a/gluon/dal/adapters/postgres.py +++ b/gluon/dal/adapters/postgres.py @@ -104,7 +104,8 @@ class PostgreSQLAdapter(BaseAdapter): self.srid = srid self.find_or_make_work_folder() self._last_insert = None # for INSERT ... RETURNING ID - + self.TRUE_exp = 'TRUE' + self.FALSE_exp = 'FALSE' ruri = uri.split('://',1)[1] m = self.REGEX_URI.match(ruri) if not m: From 132dfbcb19554cec7fd468921e8910adf35dc41a Mon Sep 17 00:00:00 2001 From: kelson Date: Sat, 3 Jan 2015 14:59:13 -0500 Subject: [PATCH 21/45] added support for POST variable passing to LOAD function A new post_vars parameter allows controllers to pass POST varaibles through LOAD as appropriate. GET variables are currently passed by default (via vars). --- gluon/compileapp.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gluon/compileapp.py b/gluon/compileapp.py index e12bb200..9ada3cfb 100644 --- a/gluon/compileapp.py +++ b/gluon/compileapp.py @@ -127,7 +127,7 @@ class mybuiltin(object): def LOAD(c=None, f='index', args=None, vars=None, extension=None, target=None, ajax=False, ajax_trap=False, url=None, user_signature=False, timeout=None, times=1, - content='loading...', **attr): + content='loading...', post_vars=Storage(), **attr): """ LOADs a component into the action's document Args: @@ -202,7 +202,7 @@ def LOAD(c=None, f='index', args=None, vars=None, other_request.args = List(args) other_request.vars = vars other_request.get_vars = vars - other_request.post_vars = Storage() + other_request.post_vars = post_vars other_response = Response() other_request.env.path_info = '/' + \ '/'.join([request.application, c, f] + From 1815864a672db8aef047ede80bd63da40d8ba4c1 Mon Sep 17 00:00:00 2001 From: enricapbes Date: Tue, 6 Jan 2015 10:38:53 +0100 Subject: [PATCH 22/45] Catalan translation Added translation to catalan language --- applications/welcome/languages/ca.py | 1 + 1 file changed, 1 insertion(+) create mode 100644 applications/welcome/languages/ca.py diff --git a/applications/welcome/languages/ca.py b/applications/welcome/languages/ca.py new file mode 100644 index 00000000..593ca2cf --- /dev/null +++ b/applications/welcome/languages/ca.py @@ -0,0 +1 @@ +ads From 16c0e1a4b8ab8363c67f0b2730c98bb7b76de4fe Mon Sep 17 00:00:00 2001 From: enricapbes Date: Tue, 6 Jan 2015 10:39:47 +0100 Subject: [PATCH 23/45] Update ca.py --- applications/welcome/languages/ca.py | 434 ++++++++++++++++++++++++++- 1 file changed, 433 insertions(+), 1 deletion(-) diff --git a/applications/welcome/languages/ca.py b/applications/welcome/languages/ca.py index 593ca2cf..7579cc37 100644 --- a/applications/welcome/languages/ca.py +++ b/applications/welcome/languages/ca.py @@ -1 +1,433 @@ -ads +# -*- coding: utf-8 -*- +{ +'!langcode!': 'es', +'!langname!': 'Español', +'"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', +'%(nrows)s records found': '%(nrows)s registros encontrados', +'%s %%{position}': '%s %%{posición}', +'%s %%{row} deleted': '%s %%{fila} %%{eliminada}', +'%s %%{row} updated': '%s %%{fila} %%{actualizada}', +'%s selected': '%s %%{seleccionado}', +'%Y-%m-%d': '%d/%m/%Y', +'%Y-%m-%d %H:%M:%S': '%d/%m/%Y %H:%M:%S', +'(something like "it-it")': '(algo como "eso-eso")', +'@markmin\x01An error occured, please [[reload %s]] the page': 'Ha ocurrido un error, por favor [[recargar %s]] la página', +'@markmin\x01Number of entries: **%s**': 'Número de entradas: **%s**', +'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', +'About': 'Acerca de', +'about': 'acerca de', +'About application': 'Acerca de la aplicación', +'Access Control': 'Control de Acceso', +'Add': 'Añadir', +'additional code for your application': 'código adicional para su aplicación', +'admin disabled because no admin password': 'admin deshabilitado 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', +'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', +'Administrative interface': 'Interfaz administrativa', +'Administrative Interface': 'Interfaz Administrativa', +'Administrator Password:': 'Contraseña del Administrador:', +'Ajax Recipes': 'Recetas AJAX', +'An error occured, please %s the page': 'Ha ocurrido un error, por favor %s la página', +'And': 'Y', +'and rename it (required):': 'y renómbrela (requerido):', +'and rename it:': ' y renómbrelo:', +'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', +'Apply changes': 'Aplicar cambios', +'Appointment': 'Nombramiento', +'Are you sure you want to delete file "%s"?': '¿Está seguro que desea eliminar el archivo "%s"?', +'Are you sure you want to delete this object?': '¿Está seguro que desea borrar este objeto?', +'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"?', +'at': 'en', +'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 está ejecutandose!', +'Authentication': 'Autenticación', +'Authentication failed at client DB!': '¡La autenticación ha fallado en la BDD cliente!', +'Authentication failed at main DB!': '¡La autenticación ha fallado en la BDD principal!', +'Available Databases and Tables': 'Bases de datos y tablas disponibles', +'Back': 'Atrás', +'Buy this book': 'Compra este libro', +'Cache': 'Caché', +'cache': 'caché', +'Cache Keys': 'Llaves de la Caché', +'cache, errors and sessions cleaned': 'caché, errores y sesiones eliminados', +'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 create file': 'no es posible crear archivo', +'cannot upload file "%(filename)s"': 'no es posible subir archivo "%(filename)s"', +'Change Password': 'Cambie la Contraseña', +'Change password': 'Cambie la contraseña', +'change password': 'cambie la contraseña', +'check all': 'marcar todos', +'Check to delete': 'Marque para eliminar', +'choose one': 'escoja uno', +'clean': 'limpiar', +'Clear': 'Limpiar', +'Clear CACHE?': '¿Limpiar CACHÉ?', +'Clear DISK': 'Limpiar DISCO', +'Clear RAM': 'Limpiar RAM', +'Click on the link %(link)s to reset your password': 'Pulse en el enlace %(link)s para reiniciar su contraseña', +'click to check for upgrades': 'haga clic para buscar actualizaciones', +'client': 'cliente', +'Client IP': 'IP del Cliente', +'Close': 'Cerrar', +'Community': 'Comunidad', +'compile': 'compilar', +'compiled application removed': 'aplicación compilada eliminada', +'Components and Plugins': 'Componentes y Plugins', +'contains': 'contiene', +'Controller': 'Controlador', +'Controllers': 'Controladores', +'controllers': 'controladores', +'Copyright': 'Copyright', +'create file with filename:': 'cree archivo con nombre:', +'Create new application': 'Cree una nueva aplicación', +'create new application:': 'nombre de la nueva aplicación:', +'Created By': 'Creado Por', +'Created On': 'Creado En', +'CSV (hidden cols)': 'CSV (columnas ocultas)', +'Current request': 'Solicitud en curso', +'Current response': 'Respuesta en curso', +'Current session': 'Sesión en curso', +'currently saved or': 'actualmente guardado o', +'customize me!': '¡Adáptame!', +'data uploaded': 'datos subidos', +'Database': 'Base de datos', +'Database %s select': 'selección en base de datos %s', +'database administration': 'administración de base de datos', +'Database Administration (appadmin)': 'Administración de Base de Datos (appadmin)', +'Date and Time': 'Fecha y Hora', +'DB': 'BDD', +'db': 'bdd', +'DB Model': 'Modelo BDD', +'defines tables': 'define tablas', +'Delete': 'Eliminar', +'delete': 'eliminar', +'delete all checked': 'eliminar marcados', +'Delete:': 'Eliminar:', +'Demo': 'Demostración', +'Deploy on Google App Engine': 'Despliegue en Google App Engine', +'Deployment Recipes': 'Recetas de despliegue', +'Description': 'Descripción', +'design': 'diseño', +'DESIGN': 'DISEÑO', +'Design for': 'Diseño por', +'detecting': 'detectando', +'DISK': 'DISCO', +'Disk Cache Keys': 'Llaves de Caché en Disco', +'Disk Cleared': 'Disco limpiado', +'Documentation': 'Documentación', +"Don't know what to do?": '¿No sabe que hacer?', +'done!': '¡hecho!', +'Download': 'Descargas', +'E-mail': 'Correo electrónico', +'edit': 'editar', +'EDIT': 'EDITAR', +'Edit': 'Editar', +'Edit application': 'Editar aplicación', +'edit controller': 'editar controlador', +'Edit current record': 'Edite el registro actual', +'Edit Profile': 'Editar Perfil', +'edit profile': 'editar perfil', +'Edit This App': 'Edite esta App', +'Editing file': 'Editando archivo', +'Editing file "%s"': 'Editando archivo "%s"', +'Email and SMS': 'Correo electrónico y SMS', +'Email sent': 'Correo electrónico enviado', +'End of impersonation': 'Fin de suplantación', +'enter a number between %(min)g and %(max)g': 'introduzca un número entre %(min)g y %(max)g', +'enter a value': 'introduzca un valor', +'enter an integer between %(min)g and %(max)g': 'introduzca un entero entre %(min)g y %(max)g', +'enter date and time as %(format)s': 'introduzca fecha y hora como %(format)s', +'Error logs for "%(app)s"': 'Bitácora de errores en "%(app)s"', +'errors': 'errores', +'Errors': 'Errores', +'Errors in form, please check it out.': 'Hay errores en el formulario, por favor comprúebelo.', +'export as csv file': 'exportar como archivo CSV', +'Export:': 'Exportar:', +'exposes': 'expone', +'extends': 'extiende', +'failed to reload module': 'la recarga del módulo ha fallado', +'FAQ': 'FAQ', +'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', +'First name': 'Nombre', +'Forgot username?': '¿Olvidó el nombre de usuario?', +'Forms and Validators': 'Formularios y validadores', +'Free Applications': 'Aplicaciones Libres', +'Functions with no doctests will result in [passed] tests.': 'Funciones sin doctests equivalen a pruebas [aceptadas].', +'Group %(group_id)s created': 'Grupo %(group_id)s creado', +'Group ID': 'ID de Grupo', +'Group uniquely assigned to user %(id)s': 'Grupo asignado únicamente al usuario %(id)s', +'Groups': 'Grupos', +'Hello World': 'Hola Mundo', +'help': 'ayuda', +'Home': 'Inicio', +'How did you get here?': '¿Cómo llegaste aquí?', +'htmledit': 'htmledit', +'Impersonate': 'Suplantar', +'import': 'importar', +'Import/Export': 'Importar/Exportar', +'in': 'en', +'includes': 'incluye', +'Index': 'Índice', +'insert new': 'inserte nuevo', +'insert new %s': 'inserte nuevo %s', +'Installed applications': 'Aplicaciones instaladas', +'Insufficient privileges': 'Privilegios insuficientes', +'internal error': 'error interno', +'Internal State': 'Estado Interno', +'Introduction': 'Introducción', +'Invalid action': 'Acción inválida', +'Invalid email': 'Correo electrónico inválido', +'invalid expression': 'expresión inválida', +'Invalid login': 'Inicio de sesión inválido', +'invalid password': 'contraseña inválida', +'Invalid Query': 'Consulta inválida', +'invalid request': 'solicitud inválida', +'Invalid reset password': 'Reinicio de contraseña inválido', +'invalid ticket': 'tiquete inválido', +'Is Active': 'Está Activo', +'Key': 'Llave', +'language file "%(filename)s" created/updated': 'archivo de lenguaje "%(filename)s" creado/actualizado', +'Language files (static strings) updated': 'Archivos de lenguaje (cadenas estáticas) actualizados', +'languages': 'lenguajes', +'Languages': 'Lenguajes', +'languages updated': 'lenguajes actualizados', +'Last name': 'Apellido', +'Last saved on:': 'Guardado en:', +'Layout': 'Diseño de página', +'Layout Plugins': 'Plugins de diseño', +'Layouts': 'Diseños de páginas', +'License for': 'Licencia para', +'Live Chat': 'Chat en vivo', +'loading...': 'cargando...', +'Logged in': 'Sesión iniciada', +'Logged out': 'Sesión finalizada', +'Login': 'Inicio de sesión', +'login': 'inicio de sesión', +'Login disabled by administrator': 'Inicio de sesión deshabilitado por el administrador', +'Login to the Administrative Interface': 'Inicio de sesión para la Interfaz Administrativa', +'logout': 'fin de sesión', +'Logout': 'Fin de sesión', +'Lost Password': 'Contraseña perdida', +'Lost password?': '¿Olvidó la contraseña?', +'lost password?': '¿olvidó la contraseña?', +'Main Menu': 'Menú principal', +'Manage Cache': 'Gestionar la Caché', +'Menu Model': 'Modelo "menu"', +'merge': 'combinar', +'Models': 'Modelos', +'models': 'modelos', +'Modified By': 'Modificado Por', +'Modified On': 'Modificado En', +'Modules': 'Módulos', +'modules': 'módulos', +'must be YYYY-MM-DD HH:MM:SS!': '¡debe ser DD/MM/YYYY HH:MM:SS!', +'must be YYYY-MM-DD!': '¡debe ser DD/MM/YYYY!', +'My Sites': 'Mis Sitios', +'Name': 'Nombre', +'New': 'Nuevo', +'New %(entity)s': 'Nuevo %(entity)s', +'new application "%s" created': 'nueva aplicación "%s" creada', +'New password': 'Contraseña nueva', +'New Record': 'Registro nuevo', +'new record inserted': 'nuevo registro insertado', +'next 100 rows': '100 filas siguientes', +'NO': 'NO', +'No databases in this application': 'No hay bases de datos en esta aplicación', +'No records found': 'No se han encontrado registros', +'Not authorized': 'No autorizado', +'not in': 'no en', +'Object or table name': 'Nombre del objeto o tabla', +'Old password': 'Contraseña vieja', +'Online examples': 'Ejemplos en línea', +'Or': 'O', +'or import from csv file': 'o importar desde archivo CSV', +'or provide application url:': 'o provea URL de la aplicación:', +'Origin': 'Origen', +'Original/Translation': 'Original/Traducción', +'Other Plugins': 'Otros Plugins', +'Other Recipes': 'Otras Recetas', +'Overview': 'Resumen', +'pack all': 'empaquetar todo', +'pack compiled': 'empaquetar compilados', +'Password': 'Contraseña', +'Password changed': 'Contraseña cambiada', +"Password fields don't match": 'Los campos de contraseña no coinciden', +'Password reset': 'Reinicio de contraseña', +'Peeking at file': 'Visualizando archivo', +'Phone': 'Teléfono', +'please input your password again': 'por favor introduzca su contraseña otra vez', +'Plugins': 'Plugins', +'Powered by': 'Este sitio usa', +'Preface': 'Prefacio', +'previous 100 rows': '100 filas anteriores', +'Profile': 'Perfil', +'Profile updated': 'Perfil actualizado', +'Python': 'Python', +'Query Not Supported: %s': 'Consulta No Soportada: %s', +'Query:': 'Consulta:', +'Quick Examples': 'Ejemplos Rápidos', +'RAM': 'RAM', +'RAM Cache Keys': 'Llaves de la Caché en RAM', +'Ram Cleared': 'Ram Limpiada', +'Recipes': 'Recetas', +'Record': 'Registro', +'Record %(id)s created': 'Registro %(id)s creado', +'Record Created': 'Registro Creado', +'record does not exist': 'el registro no existe', +'Record ID': 'ID de Registro', +'Record id': 'Id de registro', +'register': 'regístrese', +'Register': 'Regístrese', +'Registration identifier': 'Identificador de Registro', +'Registration key': 'Llave de registro', +'Registration successful': 'Registro con éxito', +'reload': 'recargar', +'Remember me (for 30 days)': 'Recuérdame (durante 30 días)', +'remove compiled': 'eliminar compiladas', +'Request reset password': 'Solicitar reinicio de contraseña', +'Reset password': 'Reiniciar contraseña', +'Reset Password key': 'Restaurar Llave de la Contraseña', +'Resolve Conflict file': 'archivo Resolución de Conflicto', +'restore': 'restaurar', +'Retrieve username': 'Recuperar nombre de usuario', +'revert': 'revertir', +'Role': 'Rol', +'Rows in Table': 'Filas en la tabla', +'Rows selected': 'Filas seleccionadas', +'save': 'guardar', +'Saved file hash:': 'Hash del archivo guardado:', +'Search': 'Buscar', +'Semantic': 'Semántica', +'Services': 'Servicios', +'session expired': 'sesión expirada', +'shell': 'terminal', +'site': 'sitio', +'Size of cache:': 'Tamaño de la Caché:', +'some files could not be removed': 'algunos archivos no pudieron ser removidos', +'start': 'inicio', +'starts with': 'comienza por', +'state': 'estado', +'static': 'estáticos', +'Static files': 'Archivos estáticos', +'Statistics': 'Estadísticas', +'Stylesheet': 'Hoja de estilo', +'Submit': 'Enviar', +'submit': 'enviar', +'Success!': '¡Correcto!', +'Support': 'Soporte', +'Sure you want to delete this object?': '¿Está seguro que desea eliminar este objeto?', +'Table': 'tabla', +'Table name': 'Nombre de la tabla', +'test': 'probar', +'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 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 Core': 'El Núcleo', +'the data representation, define database tables and sets': 'la representación de datos, define tablas y conjuntos de base de datos', +'The output of the file is a dictionary that was rendered by the view %s': 'La salida de dicha función es un diccionario que es desplegado por la vista %s', +'the presentations layer, views are also known as templates': 'la capa de presentación, las vistas también son llamadas plantillas', +'The Views': 'Las Vistas', +'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', +'these files are served without processing, your images go here': 'estos archivos son servidos sin procesar, sus imágenes van aquí', +'This App': 'Esta Aplicación', +'This email already has an account': 'Este correo electrónico ya tiene una cuenta', +'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', +'Time in Cache (h:m:s)': 'Tiempo en Caché (h:m:s)', +'Timestamp': 'Marca de tiempo', +'to previous version.': 'a la versión previa.', +'To emulate a breakpoint programatically, write:': 'Emular un punto de ruptura programáticamente, escribir:', +'to use the debugger!': '¡usar el depurador!', +'toggle breakpoint': 'alternar punto de ruptura', +'Toggle comment': 'Alternar comentario', +'Toggle Fullscreen': 'Alternar pantalla completa', +'too short': 'demasiado corto', +'translation strings for the application': 'cadenas de caracteres de traducción para la aplicación', +'try': 'intente', +'try something like': 'intente algo como', +'TSV (Excel compatible)': 'TSV (compatible Excel)', +'TSV (Excel compatible, hidden cols)': 'TSV (compatible Excel, columnas ocultas)', +'Twitter': 'Twitter', +'Unable to check for upgrades': 'No es posible verificar la existencia de actualizaciones', +'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 download': 'No es posible la descarga', +'Unable to download app': 'No es posible descarga la aplicación', +'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', +'unknown': 'desconocido', +'update': 'actualizar', +'update all languages': 'actualizar todos los lenguajes', +'Update:': 'Actualice:', +'upload application:': 'subir aplicación:', +'Upload existing application': 'Suba esta aplicación', +'upload file:': 'suba archivo:', +'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)s is impersonating %(other_id)s': 'El usuario %(id)s está suplantando %(other_id)s', +'User %(id)s Logged-in': 'El usuario %(id)s inició la sesión', +'User %(id)s Logged-out': 'El usuario %(id)s finalizó la sesión', +'User %(id)s Password changed': 'Contraseña del usuario %(id)s cambiada', +'User %(id)s Password reset': 'Contraseña del usuario %(id)s reiniciada', +'User %(id)s Profile updated': 'Actualizado el perfil del usuario %(id)s', +'User %(id)s Registered': 'Usuario %(id)s Registrado', +'User %(id)s Username retrieved': 'Se ha recuperado el nombre de usuario del usuario %(id)s', +'User %(username)s Logged-in': 'El usuario %(username)s inició la sesión', +"User '%(username)s' Logged-in": "El usuario '%(username)s' inició la sesión", +"User '%(username)s' Logged-out": "El usuario '%(username)s' finalizó la sesión", +'User Id': 'Id de Usuario', +'User ID': 'ID de Usuario', +'User Logged-out': 'El usuario finalizó la sesión', +'Username': 'Nombre de usuario', +'Username retrieve': 'Recuperar nombre de usuario', +'value already in database or empty': 'el valor ya existe en la base de datos o está vacío', +'value not allowed': 'valor no permitido', +'value not in database': 'el valor no está en la base de datos', +'Verify Password': 'Verificar Contraseña', +'Version': 'Versión', +'versioning': 'versiones', +'Videos': 'Vídeos', +'View': 'Vista', +'view': 'vista', +'View %(entity)s': 'Ver %(entity)s', +'Views': 'Vistas', +'views': 'vistas', +'web2py is up to date': 'web2py está actualizado', +'web2py Recent Tweets': 'Tweets Recientes de web2py', +'Welcome': 'Bienvenido', +'Welcome %s': 'Bienvenido %s', +'Welcome to web2py': 'Bienvenido a web2py', +'Welcome to web2py!': '¡Bienvenido a web2py!', +'Which called the function %s located in the file %s': 'La cual llamó la función %s localizada en el archivo %s', +'Working...': 'Trabajando...', +'YES': 'SÍ', +'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 %s': 'Usted visitó la url %s', +'Your username is: %(username)s': 'Su nombre de usuario es: %(username)s', +} From f396094daf3d4a061deae3a03c860d92aa820f3d Mon Sep 17 00:00:00 2001 From: enricapbes Date: Tue, 6 Jan 2015 10:47:11 +0100 Subject: [PATCH 24/45] Update ca.py --- applications/welcome/languages/ca.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/applications/welcome/languages/ca.py b/applications/welcome/languages/ca.py index 7579cc37..c0e4ec8a 100644 --- a/applications/welcome/languages/ca.py +++ b/applications/welcome/languages/ca.py @@ -1,16 +1,16 @@ # -*- coding: utf-8 -*- { -'!langcode!': 'es', -'!langname!': 'Español', -'"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', -'%(nrows)s records found': '%(nrows)s registros encontrados', -'%s %%{position}': '%s %%{posición}', +'!langcode!': 'ca', +'!langname!': 'Català', +'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"actualizi" és una expressió opcional com "camp1=\'nou_valor\'". No es poden actualitzar o eliminar resultats de un JOIN', +'%(nrows)s records found': '%(nrows)s registres trobats', +'%s %%{position}': '%s %%{posició}', '%s %%{row} deleted': '%s %%{fila} %%{eliminada}', -'%s %%{row} updated': '%s %%{fila} %%{actualizada}', -'%s selected': '%s %%{seleccionado}', +'%s %%{row} updated': '%s %%{fila} %%{actualitzada}', +'%s selected': '%s %%{seleccionat}', '%Y-%m-%d': '%d/%m/%Y', '%Y-%m-%d %H:%M:%S': '%d/%m/%Y %H:%M:%S', -'(something like "it-it")': '(algo como "eso-eso")', +'(something like "it-it")': '(similar a "això-això")', '@markmin\x01An error occured, please [[reload %s]] the page': 'Ha ocurrido un error, por favor [[recargar %s]] la página', '@markmin\x01Number of entries: **%s**': 'Número de entradas: **%s**', 'A new version of web2py is available': 'Hay una nueva versión de web2py disponible', From 83b94b8207eb49c5e0e31ba7b205713f8c72abac Mon Sep 17 00:00:00 2001 From: mdipierro Date: Tue, 6 Jan 2015 11:17:38 -0600 Subject: [PATCH 25/45] 2.9.12-beta --- Makefile | 2 +- gluon/tools.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 8bf38b2c..3d4cb666 100644 --- a/Makefile +++ b/Makefile @@ -37,7 +37,7 @@ update: echo "remember that pymysql was tweaked" src: ### Use semantic versioning - echo 'Version 2.10.0-beta+timestamp.'`date +%Y.%m.%d.%H.%M.%S` > VERSION + echo 'Version 2.9.12-beta+timestamp.'`date +%Y.%m.%d.%H.%M.%S` > VERSION ### rm -f all junk files make clean ### clean up baisc apps diff --git a/gluon/tools.py b/gluon/tools.py index 481d18ed..0b1dbd10 100644 --- a/gluon/tools.py +++ b/gluon/tools.py @@ -842,6 +842,7 @@ class Recaptcha(DIV): comment = '', ajax=False ): + request = request or current.request self.request_vars = request and request.vars or current.request.vars self.remote_addr = request.env.remote_addr self.public_key = public_key From eb8cc3fc7615de57f80c38a57e347250df394c61 Mon Sep 17 00:00:00 2001 From: enricapbes Date: Tue, 6 Jan 2015 21:22:43 +0100 Subject: [PATCH 26/45] Update ca.py --- applications/welcome/languages/ca.py | 616 ++++++++++----------------- 1 file changed, 230 insertions(+), 386 deletions(-) diff --git a/applications/welcome/languages/ca.py b/applications/welcome/languages/ca.py index c0e4ec8a..659ea48b 100644 --- a/applications/welcome/languages/ca.py +++ b/applications/welcome/languages/ca.py @@ -11,423 +11,267 @@ '%Y-%m-%d': '%d/%m/%Y', '%Y-%m-%d %H:%M:%S': '%d/%m/%Y %H:%M:%S', '(something like "it-it")': '(similar a "això-això")', -'@markmin\x01An error occured, please [[reload %s]] the page': 'Ha ocurrido un error, por favor [[recargar %s]] la página', -'@markmin\x01Number of entries: **%s**': 'Número de entradas: **%s**', -'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', -'About': 'Acerca de', -'about': 'acerca de', -'About application': 'Acerca de la aplicación', -'Access Control': 'Control de Acceso', -'Add': 'Añadir', -'additional code for your application': 'código adicional para su aplicación', -'admin disabled because no admin password': 'admin deshabilitado 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', -'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', -'Administrative interface': 'Interfaz administrativa', -'Administrative Interface': 'Interfaz Administrativa', -'Administrator Password:': 'Contraseña del Administrador:', -'Ajax Recipes': 'Recetas AJAX', -'An error occured, please %s the page': 'Ha ocurrido un error, por favor %s la página', -'And': 'Y', -'and rename it (required):': 'y renómbrela (requerido):', -'and rename it:': ' y renómbrelo:', +'@markmin\x01An error occured, please [[reload %s]] the page': 'Hi ha hagut un error, si us plau [[recarregui %s]] la pàgina', +'@markmin\x01Number of entries: **%s**': "Nombre d'entrades: **%s**", +'A new version of web2py is available': 'Hi ha una nova versió de wep2py disponible', +'A new version of web2py is available: %s': 'Hi ha una nova versió de wep2py disponible: %s', +'About': 'Sobre', +'about': 'sobre', +'About application': "Sobre l'aplicació", +'Access Control': "Control d'Accés", +'Add': 'Afegir', +'Add Record': 'Afegeix registre', +'additional code for your application': '`codi addicional per a la seva aplicació', +'admin disabled because no admin password': 'admin inhabilitat per falta de contrasenya', +'admin disabled because not supported on google app engine': 'admin inhabilitat, no és suportat en GAE', +'admin disabled because unable to access password file': 'admin inhabilitat, impossible accedir al fitxer con la contrasenya', +'Admin is disabled because insecure channel': 'Admin inhabilitat, el canal no és segur', +'Admin is disabled because unsecure channel': 'Admin inhabilitat, el canal no és segur', +'Administrative interface': 'Interfície administrativa', +'Administrative Interface': 'Interfície Administrativa', +'administrative interface': 'interfície administrativa', +'Administrator Password:': 'Contrasenya del Administrador:', +'Ajax Recipes': 'Receptes AJAX', +'An error occured, please %s the page': 'Hi ha hagut un error, per favor %s la pàgina', +'And': 'I', +'and rename it (required):': 'i renombri-la (requerit):', +'and rename it:': " i renombri'l:", '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', -'Apply changes': 'Aplicar cambios', -'Appointment': 'Nombramiento', -'Are you sure you want to delete file "%s"?': '¿Está seguro que desea eliminar el archivo "%s"?', -'Are you sure you want to delete this object?': '¿Está seguro que desea borrar este objeto?', -'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"?', -'at': 'en', -'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.': 'ATENCION: Inicio de sesión requiere una conexión segura (HTTPS) o localhost.', +'appadmin is disabled because insecure channel': 'admin inhabilitat, el canal no és segur', +'application "%s" uninstalled': 'aplicació "%s" desinstal·lada', +'application compiled': 'aplicació compilada', +'application is compiled and cannot be designed': 'la aplicació està compilada i no pot ser modificada', +'Apply changes': 'Aplicar canvis', +'Appointment': 'Nomenament', +'Are you sure you want to delete file "%s"?': 'Està segur que vol eliminar el arxiu "%s"?', +'Are you sure you want to delete this object?': 'Està segur que vol esborrar aquest objecte?', +'Are you sure you want to uninstall application "%s"': '¿Està segur que vol desinstalar la aplicació "%s"', +'Are you sure you want to uninstall application "%s"?': '¿Està segur que vol desinstalar la aplicació "%s"?', +'at': 'a', +'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.': 'ATENCIÓ: Inici de sessió requereix una connexió 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 está ejecutandose!', -'Authentication': 'Autenticación', -'Authentication failed at client DB!': '¡La autenticación ha fallado en la BDD cliente!', -'Authentication failed at main DB!': '¡La autenticación ha fallado en la BDD principal!', -'Available Databases and Tables': 'Bases de datos y tablas disponibles', -'Back': 'Atrás', -'Buy this book': 'Compra este libro', +'ATTENTION: you cannot edit the running application!': 'ATENCIO: no pot modificar la aplicació que està ejecutant-se!', +'Authentication': 'Autenticació', +'Authentication failed at client DB!': '¡La autenticació ha fallat en la BDD client!', +'Authentication failed at main DB!': '¡La autenticació ha fallat en la BDD principal!', +'Available Databases and Tables': 'Bases de dades i taules disponibles', +'Back': 'Endarrera', +'Buy this book': 'Compra aquest lllibre', 'Cache': 'Caché', 'cache': 'caché', -'Cache Keys': 'Llaves de la Caché', -'cache, errors and sessions cleaned': 'caché, errores y sesiones eliminados', -'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 create file': 'no es posible crear archivo', -'cannot upload file "%(filename)s"': 'no es posible subir archivo "%(filename)s"', -'Change Password': 'Cambie la Contraseña', -'Change password': 'Cambie la contraseña', -'change password': 'cambie la contraseña', -'check all': 'marcar todos', -'Check to delete': 'Marque para eliminar', -'choose one': 'escoja uno', -'clean': 'limpiar', -'Clear': 'Limpiar', -'Clear CACHE?': '¿Limpiar CACHÉ?', -'Clear DISK': 'Limpiar DISCO', -'Clear RAM': 'Limpiar RAM', -'Click on the link %(link)s to reset your password': 'Pulse en el enlace %(link)s para reiniciar su contraseña', -'click to check for upgrades': 'haga clic para buscar actualizaciones', +'Cache Cleared': 'Caché Netejada', +'Cache Keys': 'Claus de la Caché', +'cache, errors and sessions cleaned': 'caché, errors i sessions eliminats', +'Cannot be empty': 'No pot estar buit', +'Cannot compile: there are errors in your app. Debug it, correct errors and try again.': 'No se pot compilar: hi ha errors en la seva aplicació. Depuri, corregeixi errors i torni a intentar-ho.', +'cannot upload file "%(filename)s"': 'no és possible pujar fitxer "%(filename)s"', +'Change Password': 'Canviï la Contrasenya', +'Change password': 'Canviï la contrasenya', +'change password': 'canviï la contrasenya', +'Changelog': 'Changelog', +'check all': 'marcar tots', +'Check to delete': 'Marqui per a eliminar', +'choose one': 'escolliu un', +'clean': 'neteja', +'Clear': 'Netejar', +'Clear CACHE?': 'Netejar Memòrica Cau?', +'Clear DISK': 'Netejar DISC', +'Clear RAM': 'Netejar RAM', +'Click on the link %(link)s to reset your password': "Cliqui en l'enllaç %(link)s per a reiniciar la seva contrasenya", +'click to check for upgrades': 'feu clic per buscar actualitzacions', 'client': 'cliente', -'Client IP': 'IP del Cliente', -'Close': 'Cerrar', -'Community': 'Comunidad', +'Client IP': 'IP del Client', +'Close': 'Tancar', +'Comma-separated export including columns not shown; fields from other tables are exported as raw values for faster export': 'Comma-separated export including columns not shown; fields from other tables are exported as raw values for faster export', +'Comma-separated export of visible columns. Fields from other tables are exported as they appear on-screen but this may be slow for many rows': 'Comma-separated export of visible columns. Fields from other tables are exported as they appear on-screen but this may be slow for many rows', +'Community': 'Comunitat', 'compile': 'compilar', -'compiled application removed': 'aplicación compilada eliminada', -'Components and Plugins': 'Componentes y Plugins', -'contains': 'contiene', +'compiled application removed': 'aplicació compilada eliminada', +'Components and Plugins': 'Components i Plugins', +'contains': 'conté', 'Controller': 'Controlador', -'Controllers': 'Controladores', -'controllers': 'controladores', +'Controllers': 'Controladors', +'controllers': 'controladors', 'Copyright': 'Copyright', -'create file with filename:': 'cree archivo con nombre:', -'Create new application': 'Cree una nueva aplicación', -'create new application:': 'nombre de la nueva aplicación:', -'Created By': 'Creado Por', -'Created On': 'Creado En', -'CSV (hidden cols)': 'CSV (columnas ocultas)', -'Current request': 'Solicitud en curso', -'Current response': 'Respuesta en curso', -'Current session': 'Sesión en curso', -'currently saved or': 'actualmente guardado o', -'customize me!': '¡Adáptame!', -'data uploaded': 'datos subidos', -'Database': 'Base de datos', -'Database %s select': 'selección en base de datos %s', -'database administration': 'administración de base de datos', -'Database Administration (appadmin)': 'Administración de Base de Datos (appadmin)', -'Date and Time': 'Fecha y Hora', +'Correo electrónico invàlid': 'Correu electrònic invàlid', +'create file with filename:': 'crear el fitxer amb el nom:', +'Create new application': 'Crear una nova aplicació', +'create new application:': 'crear una nova aplicació:', +'Create New Page': 'Crear Pàgina Nova', +'Create Page from Slug': 'Create Page from Slug', +'Created By': 'Creat Per', +'Created On': 'Creat a', +'CSV': 'CSV', +'CSV (hidden cols)': 'CSV (columnas ocultes)', +'Current request': 'Sol·licitud en curs', +'Current response': 'Resposta en curs', +'Current session': 'Sessió en curs', +'currently saved or': 'actualment guardat o', +'customize me!': "¡Adapta'm!", +'data uploaded': 'dades pujades', +'Database': 'Base de dades', +'Database %s select': 'selecció a base de dades %s', +'database administration': 'administració de base de dades', +'Database Administration (appadmin)': 'Administració de Base de Dades (appadmin)', +'Date and Time': 'Data i Hora', 'DB': 'BDD', 'db': 'bdd', -'DB Model': 'Modelo BDD', -'defines tables': 'define tablas', +'DB Model': 'Model BDD', +'defines tables': 'defineix taules', 'Delete': 'Eliminar', 'delete': 'eliminar', -'delete all checked': 'eliminar marcados', +'delete all checked': 'eliminar marcats', 'Delete:': 'Eliminar:', -'Demo': 'Demostración', -'Deploy on Google App Engine': 'Despliegue en Google App Engine', -'Deployment Recipes': 'Recetas de despliegue', -'Description': 'Descripción', -'design': 'diseño', -'DESIGN': 'DISEÑO', -'Design for': 'Diseño por', -'detecting': 'detectando', -'DISK': 'DISCO', -'Disk Cache Keys': 'Llaves de Caché en Disco', -'Disk Cleared': 'Disco limpiado', -'Documentation': 'Documentación', -"Don't know what to do?": '¿No sabe que hacer?', -'done!': '¡hecho!', -'Download': 'Descargas', -'E-mail': 'Correo electrónico', +'Demo': 'Demostració', +'Deploy on Google App Engine': 'Desplegament a Google App Engine', +'Deployment Recipes': 'Receptes de desplegament', +'Description': 'Descripció', +'design': 'diseny', +'DESIGN': 'DISENY', +'Design for': 'Diseny per a', +'detecting': 'detectant', +'DISK': 'DISC', +'Disk Cache Keys': 'Claus de Caché en Disc', +'Disk Cleared': 'Disc netejat', +'Documentation': 'Documentació', +"Don't know what to do?": 'No sap què fer?', +'done!': '¡fet!', +'Download': 'Descàrregues', +'E-mail': 'Correu electrònic', 'edit': 'editar', 'EDIT': 'EDITAR', 'Edit': 'Editar', -'Edit application': 'Editar aplicación', +'Edit application': 'Editar aplicació', 'edit controller': 'editar controlador', -'Edit current record': 'Edite el registro actual', +'Edit current record': 'Editar el registre actual', +'Edit Menu': 'Editar Menu', +'Edit Page': 'Editar Pàgina', +'Edit Page Media': 'Edit Page Media', 'Edit Profile': 'Editar Perfil', 'edit profile': 'editar perfil', -'Edit This App': 'Edite esta App', -'Editing file': 'Editando archivo', -'Editing file "%s"': 'Editando archivo "%s"', -'Email and SMS': 'Correo electrónico y SMS', -'Email sent': 'Correo electrónico enviado', -'End of impersonation': 'Fin de suplantación', -'enter a number between %(min)g and %(max)g': 'introduzca un número entre %(min)g y %(max)g', -'enter a value': 'introduzca un valor', -'enter an integer between %(min)g and %(max)g': 'introduzca un entero entre %(min)g y %(max)g', -'enter date and time as %(format)s': 'introduzca fecha y hora como %(format)s', -'Error logs for "%(app)s"': 'Bitácora de errores en "%(app)s"', -'errors': 'errores', -'Errors': 'Errores', -'Errors in form, please check it out.': 'Hay errores en el formulario, por favor comprúebelo.', -'export as csv file': 'exportar como archivo CSV', +'Edit This App': 'Editi aquesta App', +'Editing file': 'Editant fitxer', +'Editing file "%s"': 'Editant fitxer "%s"', +'El fitxer ha de ser PDF': 'El fitxer ha de ser PDF', +'El fitxer ha de ser PDF o XML': 'El fitxer ha de ser PDF o XML', +'Email': 'Email', +'Email and SMS': 'Correu electrònic i SMS', +'Email sent': 'Correu electrònic enviat', +'End of impersonation': 'Fi de suplantació', +'enter a number between %(min)g and %(max)g': 'introdueixi un número entre %(min)g i %(max)g', +'Enter a valid email address': 'Entri una adreça email vàlida', +'enter a value': 'entri un valor', +'Enter a value': 'Entri un valor', +'Enter an integer between %(min)g and %(max)g': 'Entri un numero enter entre %(min)g i %(max)g', +'enter an integer between %(min)g and %(max)g': 'entri numero enter entre %(min)g i %(max)g', +'enter date and time as %(format)s': 'entri data i hora com %(format)s', +'Enter from %(min)g to %(max)g characters': 'Entri des de %(min)g a %(max)g caràcters', +'Enter valid filename': 'Entri nom de fitxer vàlid', +'Error logs for "%(app)s"': 'Bitàcora de errors a "%(app)s"', +'errors': 'errors', +'Errors': 'Errors', +'Errors in form, please check it out.': 'Hi ha errors en el formulari, per favor comprovi-ho.', +'export as csv file': 'exportar com fitxer CSV', 'Export:': 'Exportar:', -'exposes': 'expone', -'extends': 'extiende', -'failed to reload module': 'la recarga del módulo ha fallado', +'exposes': 'exposa', +'extends': 'extén', +'failed to reload module': 'la recàrrega del mòdul ha fallat', 'FAQ': 'FAQ', -'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', -'First name': 'Nombre', -'Forgot username?': '¿Olvidó el nombre de usuario?', -'Forms and Validators': 'Formularios y validadores', -'Free Applications': 'Aplicaciones Libres', -'Functions with no doctests will result in [passed] tests.': 'Funciones sin doctests equivalen a pruebas [aceptadas].', -'Group %(group_id)s created': 'Grupo %(group_id)s creado', -'Group ID': 'ID de Grupo', -'Group uniquely assigned to user %(id)s': 'Grupo asignado únicamente al usuario %(id)s', -'Groups': 'Grupos', -'Hello World': 'Hola Mundo', -'help': 'ayuda', -'Home': 'Inicio', -'How did you get here?': '¿Cómo llegaste aquí?', +'file': 'fitxer', +'file "%(filename)s" created': 'fitxer "%(filename)s" creat', +'file "%(filename)s" deleted': 'fitxer "%(filename)s" eliminat', +'file "%(filename)s" uploaded': 'fitxer "%(filename)s" pujat', +'file "%(filename)s" was not deleted': 'fitxer "%(filename)s" no fou eliminat', +'file "%s" of %s restored': 'fitxer "%s" de %s restaurat', +'file ## download': 'file ', +'file changed on disk': 'fitxer modificat en el disco', +'file does not exist': 'fitxer no existeix', +'file saved on %(time)s': 'fitxer guardat a %(time)s', +'file saved on %s': 'fitxer guardat a %s', +'First name': 'Nom', +'Forgot username?': 'Ha oblidat el nom de usuari?', +'Forms and Validators': 'Formularis i validadors', +'Free Applications': 'Aplicacions Lliures', +'Functions with no doctests will result in [passed] tests.': 'Funcions sense doctests equivalen a pruebas [aceptades].', +'Group %(group_id)s created': 'Grupo %(group_id)s creat', +'Group ID': 'ID de Grup', +'Group uniquely assigned to user %(id)s': 'Grup assignat únicament al usuari %(id)s', +'Groups': 'Grups', +'Hello': 'Hola', +'Hello World': 'Hola Món', +'help': 'ajuda', +'Home': 'Inici', +'Hosted by': 'Hosted by', +'How did you get here?': 'Com has arribat aquí?', +'HTML': 'HTML', +'HTML export of visible columns': 'HTML export de columnes visibles', 'htmledit': 'htmledit', 'Impersonate': 'Suplantar', 'import': 'importar', 'Import/Export': 'Importar/Exportar', -'in': 'en', -'includes': 'incluye', -'Index': 'Índice', -'insert new': 'inserte nuevo', -'insert new %s': 'inserte nuevo %s', -'Installed applications': 'Aplicaciones instaladas', -'Insufficient privileges': 'Privilegios insuficientes', -'internal error': 'error interno', -'Internal State': 'Estado Interno', -'Introduction': 'Introducción', -'Invalid action': 'Acción inválida', -'Invalid email': 'Correo electrónico inválido', -'invalid expression': 'expresión inválida', -'Invalid login': 'Inicio de sesión inválido', -'invalid password': 'contraseña inválida', -'Invalid Query': 'Consulta inválida', -'invalid request': 'solicitud inválida', -'Invalid reset password': 'Reinicio de contraseña inválido', -'invalid ticket': 'tiquete inválido', -'Is Active': 'Está Activo', -'Key': 'Llave', -'language file "%(filename)s" created/updated': 'archivo de lenguaje "%(filename)s" creado/actualizado', -'Language files (static strings) updated': 'Archivos de lenguaje (cadenas estáticas) actualizados', -'languages': 'lenguajes', -'Languages': 'Lenguajes', -'languages updated': 'lenguajes actualizados', -'Last name': 'Apellido', -'Last saved on:': 'Guardado en:', -'Layout': 'Diseño de página', -'Layout Plugins': 'Plugins de diseño', -'Layouts': 'Diseños de páginas', -'License for': 'Licencia para', -'Live Chat': 'Chat en vivo', -'loading...': 'cargando...', -'Logged in': 'Sesión iniciada', -'Logged out': 'Sesión finalizada', -'Login': 'Inicio de sesión', -'login': 'inicio de sesión', -'Login disabled by administrator': 'Inicio de sesión deshabilitado por el administrador', -'Login to the Administrative Interface': 'Inicio de sesión para la Interfaz Administrativa', -'logout': 'fin de sesión', -'Logout': 'Fin de sesión', -'Lost Password': 'Contraseña perdida', -'Lost password?': '¿Olvidó la contraseña?', -'lost password?': '¿olvidó la contraseña?', +'in': 'a', +'includes': 'inclou', +'Index': 'Índex', +'insert new': 'inserti nou', +'insert new %s': 'inserti nou %s', +'Installed applications': 'Aplicacions instalades', +'Insufficient privileges': 'Privilegis insuficients', +'internal error': 'error intern', +'Internal State': 'Estat Intern', +'Introduction': 'Introducció', +'Invalid action': 'Acció invàlida', +'Invalid email': 'Correo electrónico invàlid', +'invalid expression': 'expressió invàlida', +'Invalid login': 'Inici de sessió invàlida', +'invalid password': 'contrasenya invàlida', +'Invalid Query': 'Consulta invàlida', +'invalid request': 'sol·licitud invàlida', +'Invalid reset password': 'Reinici de contrasenya invàlid', +'invalid ticket': 'tiquet invàlid', +'Is Active': 'Està Actiu', +'Key': 'Clau', +'language file "%(filename)s" created/updated': 'fitxer de llenguatge "%(filename)s" creat/actualitzat', +'Language files (static strings) updated': 'Fitxers de llenguatge (cadenes estàtiques) actualitzats', +'languages': 'llenguatges', +'Languages': 'Llenguatges', +'languages updated': 'llenguatges actualitzats', +'Last name': 'Cognom', +'Last saved on:': 'Guardat a:', +'Layout': 'Diseny de pàgina', +'Layout Plugins': 'Plugins de disseny', +'Layouts': 'Dissenys de pàgines', +'License for': 'Llicència per a', +'Live Chat': 'Xat en viu', +'loading...': 'carregant...', +'Log In': 'Log In', +'Log Out': 'Log Out', +'Logged in': 'Sessió iniciada', +'Logged out': 'Sessió finalitzada', +'Login': 'Inici de sessió', +'login': 'inici de sessió', +'Login disabled by administrator': 'Inici de sessió inhabilitat pel administrador', +'Login to the Administrative Interface': 'Inici de sessió per a la Interfície Administrativa', +'logout': 'fi de sessió', +'Logout': 'Fi de sessió', +'Lost Password': 'Contrasenya perdida', +'Lost password?': 'Ha oblidat la contrasenya?', +'lost password?': '¿ha oblidat la contrasenya?', 'Main Menu': 'Menú principal', +'Manage %(action)s': 'Manage %(action)s', +'Manage Access Control': 'Manage Access Control', 'Manage Cache': 'Gestionar la Caché', -'Menu Model': 'Modelo "menu"', +'Menu Model': 'Model "menu"', 'merge': 'combinar', -'Models': 'Modelos', -'models': 'modelos', -'Modified By': 'Modificado Por', -'Modified On': 'Modificado En', -'Modules': 'Módulos', -'modules': 'módulos', +'Models': 'Models', +'models': 'models', +'Modified By': 'Modificat Per', +'Modified On': 'Modificat A', +'Modules': 'Mòduls', +'modules': 'mòduls', 'must be YYYY-MM-DD HH:MM:SS!': '¡debe ser DD/MM/YYYY HH:MM:SS!', 'must be YYYY-MM-DD!': '¡debe ser DD/MM/YYYY!', -'My Sites': 'Mis Sitios', +'My Sites': 'Els Meus Llocs', 'Name': 'Nombre', 'New': 'Nuevo', 'New %(entity)s': 'Nuevo %(entity)s', -'new application "%s" created': 'nueva aplicación "%s" creada', -'New password': 'Contraseña nueva', -'New Record': 'Registro nuevo', -'new record inserted': 'nuevo registro insertado', -'next 100 rows': '100 filas siguientes', -'NO': 'NO', -'No databases in this application': 'No hay bases de datos en esta aplicación', -'No records found': 'No se han encontrado registros', -'Not authorized': 'No autorizado', -'not in': 'no en', -'Object or table name': 'Nombre del objeto o tabla', -'Old password': 'Contraseña vieja', -'Online examples': 'Ejemplos en línea', -'Or': 'O', -'or import from csv file': 'o importar desde archivo CSV', -'or provide application url:': 'o provea URL de la aplicación:', -'Origin': 'Origen', -'Original/Translation': 'Original/Traducción', -'Other Plugins': 'Otros Plugins', -'Other Recipes': 'Otras Recetas', -'Overview': 'Resumen', -'pack all': 'empaquetar todo', -'pack compiled': 'empaquetar compilados', -'Password': 'Contraseña', -'Password changed': 'Contraseña cambiada', -"Password fields don't match": 'Los campos de contraseña no coinciden', -'Password reset': 'Reinicio de contraseña', -'Peeking at file': 'Visualizando archivo', -'Phone': 'Teléfono', -'please input your password again': 'por favor introduzca su contraseña otra vez', -'Plugins': 'Plugins', -'Powered by': 'Este sitio usa', -'Preface': 'Prefacio', -'previous 100 rows': '100 filas anteriores', -'Profile': 'Perfil', -'Profile updated': 'Perfil actualizado', -'Python': 'Python', -'Query Not Supported: %s': 'Consulta No Soportada: %s', -'Query:': 'Consulta:', -'Quick Examples': 'Ejemplos Rápidos', -'RAM': 'RAM', -'RAM Cache Keys': 'Llaves de la Caché en RAM', -'Ram Cleared': 'Ram Limpiada', -'Recipes': 'Recetas', -'Record': 'Registro', -'Record %(id)s created': 'Registro %(id)s creado', -'Record Created': 'Registro Creado', -'record does not exist': 'el registro no existe', -'Record ID': 'ID de Registro', -'Record id': 'Id de registro', -'register': 'regístrese', -'Register': 'Regístrese', -'Registration identifier': 'Identificador de Registro', -'Registration key': 'Llave de registro', -'Registration successful': 'Registro con éxito', -'reload': 'recargar', -'Remember me (for 30 days)': 'Recuérdame (durante 30 días)', -'remove compiled': 'eliminar compiladas', -'Request reset password': 'Solicitar reinicio de contraseña', -'Reset password': 'Reiniciar contraseña', -'Reset Password key': 'Restaurar Llave de la Contraseña', -'Resolve Conflict file': 'archivo Resolución de Conflicto', -'restore': 'restaurar', -'Retrieve username': 'Recuperar nombre de usuario', -'revert': 'revertir', -'Role': 'Rol', -'Rows in Table': 'Filas en la tabla', -'Rows selected': 'Filas seleccionadas', -'save': 'guardar', -'Saved file hash:': 'Hash del archivo guardado:', -'Search': 'Buscar', -'Semantic': 'Semántica', -'Services': 'Servicios', -'session expired': 'sesión expirada', -'shell': 'terminal', -'site': 'sitio', -'Size of cache:': 'Tamaño de la Caché:', -'some files could not be removed': 'algunos archivos no pudieron ser removidos', -'start': 'inicio', -'starts with': 'comienza por', -'state': 'estado', -'static': 'estáticos', -'Static files': 'Archivos estáticos', -'Statistics': 'Estadísticas', -'Stylesheet': 'Hoja de estilo', -'Submit': 'Enviar', -'submit': 'enviar', -'Success!': '¡Correcto!', -'Support': 'Soporte', -'Sure you want to delete this object?': '¿Está seguro que desea eliminar este objeto?', -'Table': 'tabla', -'Table name': 'Nombre de la tabla', -'test': 'probar', -'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 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 Core': 'El Núcleo', -'the data representation, define database tables and sets': 'la representación de datos, define tablas y conjuntos de base de datos', -'The output of the file is a dictionary that was rendered by the view %s': 'La salida de dicha función es un diccionario que es desplegado por la vista %s', -'the presentations layer, views are also known as templates': 'la capa de presentación, las vistas también son llamadas plantillas', -'The Views': 'Las Vistas', -'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', -'these files are served without processing, your images go here': 'estos archivos son servidos sin procesar, sus imágenes van aquí', -'This App': 'Esta Aplicación', -'This email already has an account': 'Este correo electrónico ya tiene una cuenta', -'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', -'Time in Cache (h:m:s)': 'Tiempo en Caché (h:m:s)', -'Timestamp': 'Marca de tiempo', -'to previous version.': 'a la versión previa.', -'To emulate a breakpoint programatically, write:': 'Emular un punto de ruptura programáticamente, escribir:', -'to use the debugger!': '¡usar el depurador!', -'toggle breakpoint': 'alternar punto de ruptura', -'Toggle comment': 'Alternar comentario', -'Toggle Fullscreen': 'Alternar pantalla completa', -'too short': 'demasiado corto', -'translation strings for the application': 'cadenas de caracteres de traducción para la aplicación', -'try': 'intente', -'try something like': 'intente algo como', -'TSV (Excel compatible)': 'TSV (compatible Excel)', -'TSV (Excel compatible, hidden cols)': 'TSV (compatible Excel, columnas ocultas)', -'Twitter': 'Twitter', -'Unable to check for upgrades': 'No es posible verificar la existencia de actualizaciones', -'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 download': 'No es posible la descarga', -'Unable to download app': 'No es posible descarga la aplicación', -'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', -'unknown': 'desconocido', -'update': 'actualizar', -'update all languages': 'actualizar todos los lenguajes', -'Update:': 'Actualice:', -'upload application:': 'subir aplicación:', -'Upload existing application': 'Suba esta aplicación', -'upload file:': 'suba archivo:', -'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)s is impersonating %(other_id)s': 'El usuario %(id)s está suplantando %(other_id)s', -'User %(id)s Logged-in': 'El usuario %(id)s inició la sesión', -'User %(id)s Logged-out': 'El usuario %(id)s finalizó la sesión', -'User %(id)s Password changed': 'Contraseña del usuario %(id)s cambiada', -'User %(id)s Password reset': 'Contraseña del usuario %(id)s reiniciada', -'User %(id)s Profile updated': 'Actualizado el perfil del usuario %(id)s', -'User %(id)s Registered': 'Usuario %(id)s Registrado', -'User %(id)s Username retrieved': 'Se ha recuperado el nombre de usuario del usuario %(id)s', -'User %(username)s Logged-in': 'El usuario %(username)s inició la sesión', -"User '%(username)s' Logged-in": "El usuario '%(username)s' inició la sesión", -"User '%(username)s' Logged-out": "El usuario '%(username)s' finalizó la sesión", -'User Id': 'Id de Usuario', -'User ID': 'ID de Usuario', -'User Logged-out': 'El usuario finalizó la sesión', -'Username': 'Nombre de usuario', -'Username retrieve': 'Recuperar nombre de usuario', -'value already in database or empty': 'el valor ya existe en la base de datos o está vacío', -'value not allowed': 'valor no permitido', -'value not in database': 'el valor no está en la base de datos', -'Verify Password': 'Verificar Contraseña', -'Version': 'Versión', -'versioning': 'versiones', -'Videos': 'Vídeos', -'View': 'Vista', -'view': 'vista', -'View %(entity)s': 'Ver %(entity)s', -'Views': 'Vistas', -'views': 'vistas', -'web2py is up to date': 'web2py está actualizado', -'web2py Recent Tweets': 'Tweets Recientes de web2py', -'Welcome': 'Bienvenido', -'Welcome %s': 'Bienvenido %s', -'Welcome to web2py': 'Bienvenido a web2py', -'Welcome to web2py!': '¡Bienvenido a web2py!', -'Which called the function %s located in the file %s': 'La cual llamó la función %s localizada en el archivo %s', -'Working...': 'Trabajando...', -'YES': 'SÍ', -'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 %s': 'Usted visitó la url %s', -'Your username is: %(username)s': 'Su nombre de usuario es: %(username)s', } From 8c1ca50205d19d4076587dff92a91dcdaab6c888 Mon Sep 17 00:00:00 2001 From: enricapbes Date: Tue, 6 Jan 2015 21:29:57 +0100 Subject: [PATCH 27/45] Update ca.py --- applications/welcome/languages/ca.py | 218 ++++++++++++++++++++++++++- 1 file changed, 217 insertions(+), 1 deletion(-) diff --git a/applications/welcome/languages/ca.py b/applications/welcome/languages/ca.py index 659ea48b..6f830149 100644 --- a/applications/welcome/languages/ca.py +++ b/applications/welcome/languages/ca.py @@ -1,3 +1,4 @@ + # -*- coding: utf-8 -*- { '!langcode!': 'ca', @@ -273,5 +274,220 @@ 'My Sites': 'Els Meus Llocs', 'Name': 'Nombre', 'New': 'Nuevo', -'New %(entity)s': 'Nuevo %(entity)s', +'New %(entity)s': 'Nou %(entity)s', +'new application "%s" created': 'nova aplicació "%s" creada', +'New password': 'Contrasenya nova', +'New Record': 'Registre nou', +'new record inserted': 'nou registre insertat', +'New Search': 'Cerca nova', +'next %s rows': 'següents %s files', +'next 100 rows': '100 files següents', +'NO': 'NO', +'No databases in this application': 'No hi ha bases de dades en esta aplicació', +'No records found': "No s'han trobat registres", +'Not authorized': 'No autoritzat', +'not in': 'no a', +'Object or table name': 'Nom del objecte o taula', +'Old password': 'Contrasenya anterior', +'Online examples': 'Ejemples en línia', +'Or': 'O', +'or import from csv file': 'o importar desde fitxer CSV', +'or provide application url:': 'o proveeix URL de la aplicació:', +'Origin': 'Origen', +'Original/Translation': 'Original/Traducció', +'Other Plugins': 'Altres Plugins', +'Other Recipes': 'Altres Receptes', +'Overview': 'Resum', +'pack all': 'empaquetar tot', +'pack compiled': 'empaquetar compilats', +'Password': 'Contrasenya', +'Password changed': 'Contrasenya cambiada', +"Password fields don't match": 'Els camps de contrasenya no coincideixen', +'Password reset': 'Reinici de contrasenya', +'Peeking at file': 'Visualitzant fitxer', +'Permission': 'Permís', +'Permissions': 'Permisos', +'Phone': 'Telèfon', +'please input your password again': 'si us plau, entri un altre cop la seva contrasenya', +'Plugins': 'Plugins', +'Powered by': 'Aquest lloc utilitza', +'Preface': 'Prefaci', +'Presentar Factures': 'Presentar Factures', +'Presentar factures': 'Presentar factures', +'previous %s rows': '%s files prèvies', +'previous 100 rows': '100 files anteriors', +'Profile': 'Perfil', +'Profile updated': 'Perfil actualitzat', +'pygraphviz library not found': 'pygraphviz library not found', +'Python': 'Python', +'Query Not Supported: %s': 'Consulta No Suportada: %s', +'Query:': 'Consulta:', +'Quick Examples': 'Exemple Ràpids', +'RAM': 'RAM', +'RAM Cache Keys': 'Claus de la Caché en RAM', +'Ram Cleared': 'Ram Netjeda', +'Recipes': 'Receptes', +'Record': 'Registre', +'Record %(id)s created': 'Registre %(id)s creat', +'Record Created': 'Registre Creat', +'record does not exist': 'el registre no existe', +'Record ID': 'ID de Registre', +'Record id': 'Id de registre', +'Ref APB': 'Ref APB', +'register': "registri's", +'Register': "Registri's", +'Registration identifier': 'Identificador de Registre', +'Registration key': 'Clau de registre', +'Registration successful': 'Registre amb èxit', +'reload': 'recarregar', +'Remember me (for 30 days)': "Recordi'm (durant 30 dies)", +'remove compiled': 'eliminar compilades', +'Request reset password': 'Sol·licitud de restabliment de contrasenya', +'Reset password': 'Reiniciar contrasenya', +'Reset Password key': 'Restaurar Clau de la Contrasenya', +'Resolve Conflict file': 'Resolgui el Conflicte de fitxer', +'restore': 'restaurar', +'Retrieve username': 'Recuperar nom de usuari', +'revert': 'revertir', +'Role': 'Rol', +'Roles': 'Rols', +'Rows in Table': 'Files a la taula', +'Rows selected': 'Files seleccionades', +'save': 'guardar', +'Save model as...': 'Save model as...', +'Saved file hash:': 'Hash del fitxer guardat:', +'Search': 'Buscar', +'Search Pages': 'Search Pages', +'Semantic': 'Semàntica', +'Services': 'Serveis', +'session expired': 'sessió expirada', +'shell': 'terminal', +'Sign Up': 'Sign Up', +'site': 'lloc', +'Size of cache:': 'Mida de la Caché:', +'Slug': 'Slug', +'some files could not be removed': 'algunos archivos no pudieron ser removidos', +'Spreadsheet-optimised export of tab-separated content including hidden columns. May be slow': 'Spreadsheet-optimised export of tab-separated content including hidden columns. May be slow', +'Spreadsheet-optimised export of tab-separated content, visible columns only. May be slow.': 'Spreadsheet-optimised export of tab-separated content, visible columns only. May be slow.', +'start': 'inici', +'Start building a new search': 'Start building a new search', +'starts with': 'comença per', +'state': 'estat', +'static': 'estàtics', +'Static files': 'Fitxers estàtics', +'Statistics': 'Estadístiques', +'Stylesheet': "Fulla d'estil", +'Submit': 'Enviar', +'submit': 'enviar', +'Success!': 'Correcte!', +'Support': 'Suport', +'Sure you want to delete this object?': '¿Està segur que vol eliminar aquest objecte?', +'Table': 'taula', +'Table name': 'Nom de la taula', +'test': 'provar', +'Testing application': 'Provant aplicació', +'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" és una condición com "db.tabla1.campo1==\'valor\'". Algo com "db.tabla1.campo1==db.tabla2.campo2" resulta en un JOIN SQL.', +'the application logic, each URL path is mapped in one exposed function in the controller': 'la lògica de la aplicació, cada ruta URL es mapeja en una funció exposada en el controlador', +'The Core': 'El Nucli', +'the data representation, define database tables and sets': 'la representació de dades, defineix taules i conjunts de base de dades', +'The output of the file is a dictionary that was rendered by the view %s': 'El resultat de aquesta funció és un diccionari que és desplegat per la vista %s', +'the presentations layer, views are also known as templates': 'la capa de presentació, les vistes també són anomenades plantilles', +'The Views': 'Les Vistes', +'There are no controllers': 'No hi ha controladors', +'There are no models': 'No hi ha models', +'There are no modules': 'No hi ha mòduls', +'There are no static files': 'No hi ha fitxers estàtics', +'There are no translators, only default language is supported': 'No hi ha traductors, només el llenguatge per defecte és suportat', +'There are no views': 'No hi ha vistes', +'these files are served without processing, your images go here': 'aquests fitxers són servits sense processar, les seves imatges van aquí', +'This App': 'Aquesta Aplicació', +'This email already has an account': 'Aquest correu electrònic ja té un compte', +'This is a copy of the scaffolding application': 'Aquesta és una còpia de la aplicació de bastiment', +'This is the %(filename)s template': 'Aquesta és la plantilla %(filename)s', +'Ticket': 'Tiquet', +'Time in Cache (h:m:s)': 'Temps en Caché (h:m:s)', +'Timestamp': 'Marca de temps', +'Title': 'Títol', +'to previous version.': 'a la versió prèvia.', +'To emulate a breakpoint programatically, write:': 'Emular un punto de ruptura programàticament, escribir:', +'to use the debugger!': 'usar el depurador!', +'toggle breakpoint': 'alternar punt de ruptura', +'Toggle comment': 'Alternar comentari', +'Toggle Fullscreen': 'Alternar pantalla completa', +'too short': 'massa curt', +'Traceback': 'Traceback', +'translation strings for the application': 'cadenes de caracters de traducció per a la aplicació', +'try': 'intenti', +'try something like': 'intenti algo com', +'TSV (Excel compatible)': 'TSV (compatible Excel)', +'TSV (Excel compatible, hidden cols)': 'TSV (compatible Excel, columnes ocultes)', +'TSV (Spreadsheets)': 'TSV (Fulls de càlcul)', +'TSV (Spreadsheets, hidden cols)': 'TSV (Fulls de càlcul, columnes amagades)', +'Twitter': 'Twitter', +'Unable to check for upgrades': 'No és possible verificar la existencia de actualitzacions', +'unable to create application "%s"': 'no és possible crear la aplicació "%s"', +'unable to delete file "%(filename)s"': 'no és possible eliminar el fitxer "%(filename)s"', +'Unable to download': 'No és possible la descàrrega', +'Unable to download app': 'No és possible descarregar la aplicació', +'unable to parse csv file': 'no és possible analitzar el fitxer CSV', +'unable to uninstall "%s"': 'no és possible instalar "%s"', +'uncheck all': 'desmarcar tots', +'uninstall': 'desinstalar', +'unknown': 'desconocido', +'update': 'actualitzar', +'update all languages': 'actualitzar tots els llenguatges', +'Update:': 'Actualizi:', +'upload application:': 'pujar aplicació:', +'Upload existing application': 'Puji aquesta aplicació', +'upload file:': 'puji fitxer:', +'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Use (...)&(...) para AND, (...)|(...) para OR, i ~(...) para NOT, para crear consultas més complexes.', +'User': 'Usuari', +'User %(id)s is impersonating %(other_id)s': 'El usuari %(id)s està suplantant %(other_id)s', +'User %(id)s Logged-in': 'El usuari %(id)s inicià la sessió', +'User %(id)s Logged-out': 'El usuari %(id)s finalitzà la sessió', +'User %(id)s Password changed': 'Contrasenya del usuari %(id)s canviada', +'User %(id)s Password reset': 'Contrasenya del usuari %(id)s reiniciada', +'User %(id)s Profile updated': 'Actualitzat el perfil del usuari %(id)s', +'User %(id)s Registered': 'Usuari %(id)s Registrat', +'User %(id)s Username retrieved': 'Se ha recuperat el nom de usuari del usuari %(id)s', +'User %(username)s Logged-in': 'El usuari %(username)s inicià la sessió', +"User '%(username)s' Logged-in": "El usuari '%(username)s' inicià la sessió", +"User '%(username)s' Logged-out": "El usuari '%(username)s' finalitzà la sessió", +'User Id': 'Id de Usuari', +'User ID': 'ID de Usuari', +'User Logged-out': 'El usuari finalitzà la sessió', +'Username': 'Nom de usuari', +'Username retrieve': 'Recuperar nom de usuari', +'Users': 'Usuaris', +'Value already in database or empty': 'El valor ya existeix en la base de dades o està buit', +'value already in database or empty': 'el valor ya existeix en la base de dades o està buit', +'value not allowed': 'valor no permès', +'Value not in database': 'El valor no està a la base de dades', +'value not in database': 'el valor no està a la base de dades', +'Verify Password': 'Verificar Contrasenya', +'Version': 'Versió', +'versioning': 'versions', +'Videos': 'Videos', +'View': 'Vista', +'view': 'vista', +'View %(entity)s': 'Veure %(entity)s', +'View Page': 'View Page', +'Views': 'Vistes', +'views': 'vistes', +'web2py is up to date': 'web2py està actualitzat', +'web2py Recent Tweets': 'Tweets Recents de web2py', +'Welcome': 'Benvingut', +'Welcome %s': 'Benvingut %s', +'Welcome to web2py': 'Benvingut a web2py', +'Welcome to web2py!': '¡Benvingut a web2py!', +'Which called the function %s located in the file %s': 'La qual va cridar la funció %s localitzada en el fitxer %s', +'Wiki Page': 'Wiki Page', +'Working...': 'Treballant ...', +'XML': 'XML', +'XML export of columns shown': 'XML export of columns shown', +'YES': 'SÍ', +'You are successfully running web2py': 'Vostè està executant web2py amb èxit', +'You can modify this application and adapt it to your needs': 'Vostè pot modificar aquesta aplicació i adaptar-la a les seves necessitats', +'You visited the url %s': 'Vostè va visitar la url %s', +'Your username is: %(username)s': 'El seu nom de usuari és: %(username)s', } From 3d4de72b9cebf79f2484ba0c8855ca314f07a80b Mon Sep 17 00:00:00 2001 From: enricapbes Date: Tue, 6 Jan 2015 21:30:25 +0100 Subject: [PATCH 28/45] Update ca.py --- applications/welcome/languages/ca.py | 1 - 1 file changed, 1 deletion(-) diff --git a/applications/welcome/languages/ca.py b/applications/welcome/languages/ca.py index 6f830149..e0f3109e 100644 --- a/applications/welcome/languages/ca.py +++ b/applications/welcome/languages/ca.py @@ -1,4 +1,3 @@ - # -*- coding: utf-8 -*- { '!langcode!': 'ca', From 15c3ac1cb90515e320c32bbc681b30345f065acf Mon Sep 17 00:00:00 2001 From: mdipierro Date: Tue, 6 Jan 2015 22:59:05 -0600 Subject: [PATCH 29/45] fixed Makefile for new dal --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 3d4cb666..14ff4d92 100644 --- a/Makefile +++ b/Makefile @@ -61,7 +61,7 @@ src: ### build web2py_src.zip echo '' > NEWINSTALL mv web2py_src.zip web2py_src_old.zip | echo 'no old' - cd ..; zip -r web2py/web2py_src.zip web2py/web2py.py web2py/anyserver.py web2py/gluon/*.py web2py/gluon/contrib/* web2py/extras/* web2py/handlers/* web2py/examples/* web2py/README.markdown web2py/LICENSE web2py/CHANGELOG web2py/NEWINSTALL web2py/VERSION web2py/MANIFEST.in web2py/scripts/*.sh web2py/scripts/*.py web2py/applications/admin web2py/applications/examples/ web2py/applications/welcome web2py/applications/__init__.py web2py/site-packages/__init__.py web2py/gluon/tests/*.sh web2py/gluon/tests/*.py + cd ..; zip -r web2py/web2py_src.zip web2py/web2py.py web2py/anyserver.py web2py/gluon/*.py web2py/gluon/dal/* web2py/gluon/contrib/* web2py/extras/* web2py/handlers/* web2py/examples/* web2py/README.markdown web2py/LICENSE web2py/CHANGELOG web2py/NEWINSTALL web2py/VERSION web2py/MANIFEST.in web2py/scripts/*.sh web2py/scripts/*.py web2py/applications/admin web2py/applications/examples/ web2py/applications/welcome web2py/applications/__init__.py web2py/site-packages/__init__.py web2py/gluon/tests/*.sh web2py/gluon/tests/*.py mdp: make src From f76a780d505549d30ba2226ccbd1ad4eca9a2786 Mon Sep 17 00:00:00 2001 From: mdipierro Date: Wed, 7 Jan 2015 10:39:17 -0600 Subject: [PATCH 30/45] fixed import of reserved_sql_keywords --- gluon/dal/base.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gluon/dal/base.py b/gluon/dal/base.py index 4c9eeb3d..743bee83 100644 --- a/gluon/dal/base.py +++ b/gluon/dal/base.py @@ -440,7 +440,7 @@ class DAL(object): self._uri_hash = table_hash or hashlib_md5(adapter.uri).hexdigest() self.check_reserved = check_reserved if self.check_reserved: - from reserved_sql_keywords import ADAPTERS as RSK + from gluon.reserved_sql_keywords import ADAPTERS as RSK self.RSK = RSK self._migrate = migrate self._fake_migrate = fake_migrate From daf382c4fbc50995acaa7c3cdc34cedb9af48af0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leonel=20C=C3=A2mara?= Date: Wed, 7 Jan 2015 21:36:15 +0000 Subject: [PATCH 31/45] fixes issue 2025 - Encode filenames using base32 if you're running on windows to avoid invalid characters. --- gluon/cache.py | 43 +++++++++++++++++++++++++++++++++++++------ 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/gluon/cache.py b/gluon/cache.py index bac5a37f..3a03a19c 100644 --- a/gluon/cache.py +++ b/gluon/cache.py @@ -246,11 +246,11 @@ 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. + This is implemented as a key value store where each key corresponds to a + single file in disk which is replaced when the value changes. - Disk cache provides persistance when web2py is started/stopped but it slower - than `CacheInRam` + Disk cache provides persistance when web2py is started/stopped but it is + slower than `CacheInRam` Values stored in disk cache must be pickable. """ @@ -259,8 +259,11 @@ class CacheOnDisk(CacheAbstract): """ Implements a key based storage in disk. """ + def __init__(self, folder): self.folder = folder + self.key_filter_in = lambda key: key + self.key_filter_out = lambda key: key # Check the best way to do atomic file replacement. if sys.version_info >= (3, 3): self.replace = os.replace @@ -287,6 +290,25 @@ class CacheOnDisk(CacheAbstract): # POSIX rename() is always atomic self.replace = os.rename + # Make sure we use valid filenames. + if sys.platform == "win32": + import base64 + def key_filter_in_windows(key): + """ + Windows doesn't allow \ / : * ? "< > | in filenames. + To go around this encode the keys with base32. + """ + return base64.b32encode(key) + + def key_filter_out_windows(key): + """ + We need to decode the keys so regex based removal works. + """ + return base64.b32decode(key) + + self.key_filter_in = key_filter_in_windows + self.key_filter_out = key_filter_out_windows + def __setitem__(self, key, value): tmp_name, tmp_path = tempfile.mkstemp(dir=self.folder) @@ -295,6 +317,7 @@ class CacheOnDisk(CacheAbstract): pickle.dump((time.time(), value), tmp, pickle.HIGHEST_PROTOCOL) finally: tmp.close() + key = self.key_filter_in(key) fullfilename = os.path.join(self.folder, recfile.generate(key)) if not os.path.exists(os.path.dirname(fullfilename)): os.makedirs(os.path.dirname(fullfilename)) @@ -302,27 +325,33 @@ class CacheOnDisk(CacheAbstract): def __getitem__(self, key): + key = self.key_filter_in(key) if recfile.exists(key, path=self.folder): timestamp, value = pickle.load(recfile.open(key, 'rb', path=self.folder)) return value else: raise KeyError + def __contains__(self, key): + key = self.key_filter_in(key) return recfile.exists(key, path=self.folder) def __delitem__(self, key): + key = self.key_filter_in(key) recfile.remove(key, path=self.folder) def __iter__(self): for dirpath, dirnames, filenames in os.walk(self.folder): for filename in filenames: - yield filename + yield self.key_filter_out(filename) + def keys(self): - return [filename for dirpath, dirnames, filenames in os.walk(self.folder) for filename in filenames] + return list(self.__iter__()) + def get(self, key, default=None): try: @@ -335,6 +364,7 @@ class CacheOnDisk(CacheAbstract): for key in self: del self[key] + def __init__(self, request=None, folder=None): self.initialized = False self.request = request @@ -389,6 +419,7 @@ class CacheOnDisk(CacheAbstract): return value + def clear(self, regex=None): self.initialize() storage = self.storage From 6be1f624b9c576d852ed0fb3f254baf3135c83de Mon Sep 17 00:00:00 2001 From: Anssi Hannula Date: Sat, 10 Jan 2015 03:44:51 +0200 Subject: [PATCH 32/45] GoogleSQLAdapter: Fix NDB orderby without limitby broken in 2.9.6 Commit 8d648f6137cea5 ("restore beahvior in gae that if no limitby, returns iterator") made select_raw() store the query iterator in a wrong variable ("rows", which is unused, should be "items"), causing unsorted results to be returned. Fix the assignment. --- gluon/dal/adapters/google.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gluon/dal/adapters/google.py b/gluon/dal/adapters/google.py index 86c3ef3c..00e75cc1 100644 --- a/gluon/dal/adapters/google.py +++ b/gluon/dal/adapters/google.py @@ -507,7 +507,7 @@ class GoogleDatastoreAdapter(NoSQLAdapter): db['_lastcursor'] = cursor else: # if a limit is not specified, always return an iterator - rows = query + items = query return (items, tablename, projection or db[tablename].fields) From c5c5b5708ec1d6af269e6c41e0203fa84fab852d Mon Sep 17 00:00:00 2001 From: ilvalle Date: Sat, 10 Jan 2015 18:11:00 +0100 Subject: [PATCH 33/45] fix issue 2023: common_filter issue in _enable_record_versioning --- gluon/dal/objects.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/gluon/dal/objects.py b/gluon/dal/objects.py index 44730709..9a44329e 100644 --- a/gluon/dal/objects.py +++ b/gluon/dal/objects.py @@ -428,8 +428,9 @@ class Table(object): if tn == name or getattr(db[tn],'_ot',None)==name]) query = self._common_filter if query: - newquery = query & newquery - self._common_filter = newquery + self._common_filter = lambda q: reduce(AND, [query(q), newquery(q)]) + else: + self._common_filter = newquery def _validate(self, **vars): errors = Row() From 1c281cc163194ded601dba63fbc721cfac976094 Mon Sep 17 00:00:00 2001 From: ilvalle Date: Sun, 11 Jan 2015 21:44:20 +0100 Subject: [PATCH 34/45] Initial tests for auth --- gluon/tests/__init__.py | 7 ++-- gluon/tests/test_tools.py | 83 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+), 3 deletions(-) create mode 100644 gluon/tests/test_tools.py diff --git a/gluon/tests/__init__.py b/gluon/tests/__init__.py index 9d66896e..6f809695 100644 --- a/gluon/tests/__init__.py +++ b/gluon/tests/__init__.py @@ -1,5 +1,5 @@ -import os, sys - +import os +import sys from test_http import * from test_cache import * from test_contenttype import * @@ -16,6 +16,7 @@ from test_validators import * from test_utils import * from test_contribs import * from test_web import * +from test_tools import * if sys.version[:3] == '2.7': @@ -28,4 +29,4 @@ NOSQL = any([name in (os.getenv("DB") or "") if NOSQL: from test_dal_nosql import * else: - from test_dal import * \ No newline at end of file + from test_dal import * diff --git a/gluon/tests/test_tools.py b/gluon/tests/test_tools.py new file mode 100644 index 00000000..de148db9 --- /dev/null +++ b/gluon/tests/test_tools.py @@ -0,0 +1,83 @@ +#!/bin/python +# -*- coding: utf-8 -*- + +""" + Unit tests for gluon.tools +""" +import os +import sys +if sys.version < "2.7": + import unittest2 as unittest +else: + import unittest + +from fix_path import fix_sys_path + +fix_sys_path(__file__) + +DEFAULT_URI = os.getenv('DB', 'sqlite:memory') + +from gluon.dal import DAL, Field +from dal.objects import Table +from tools import Auth +from gluon.globals import Request, Response, Session +from storage import Storage +from languages import translator +from gluon.http import HTTP + +python_version = sys.version[:3] +IS_IMAP = "imap" in DEFAULT_URI + +@unittest.skipIf(IS_IMAP, "TODO: Imap raises 'Connection refused'") +class testAuth(unittest.TestCase): + + def testRun(self): + # setup + request = Request(env={}) + request.application = 'a' + request.controller = 'c' + request.function = 'f' + request.folder = 'applications/admin' + response = Response() + session = Session() + T = translator('', 'en') + session.connect(request, response) + from gluon.globals import current + current.request = request + current.response = response + current.session = session + current.T = T + db = DAL(DEFAULT_URI, check_reserved=['all']) + auth = Auth(db) + auth.define_tables(username=True, signature=False) + self.assertTrue('auth_user' in db) + self.assertTrue('auth_group' in db) + self.assertTrue('auth_membership' in db) + self.assertTrue('auth_permission' in db) + self.assertTrue('auth_event' in db) + db.define_table('t0', Field('tt'), auth.signature) + auth.enable_record_versioning(db) + self.assertTrue('t0_archive' in db) + for f in ['login', 'register', 'retrieve_password', + 'retrieve_username']: + html_form = getattr(auth, f)().xml() + self.assertTrue('name="_formkey"' in html_form) + + for f in ['logout', 'verify_email', 'reset_password', + 'change_password', 'profile', 'groups']: + self.assertRaisesRegexp(HTTP, "303*", getattr(auth, f)) + + self.assertRaisesRegexp(HTTP, "401*", auth.impersonate) + + try: + for t in ['t0_archive', 't0', 'auth_cas', 'auth_event', + 'auth_membership', 'auth_permission', 'auth_group', + 'auth_user']: + db[t].drop() + except SyntaxError as e: + # GAE doesn't support drop + pass + return + +if __name__ == '__main__': + unittest.main() From 2af5e02c5f760f0fa06587bacb5605973975bbb0 Mon Sep 17 00:00:00 2001 From: mdipierro Date: Mon, 12 Jan 2015 20:06:05 -0600 Subject: [PATCH 35/45] fixed issue #2032, thanks Paolo --- gluon/dal/objects.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/gluon/dal/objects.py b/gluon/dal/objects.py index 44730709..2eff6ab8 100644 --- a/gluon/dal/objects.py +++ b/gluon/dal/objects.py @@ -427,9 +427,12 @@ class Table(object): for tn in db._adapter.tables(query) if tn == name or getattr(db[tn],'_ot',None)==name]) query = self._common_filter - if query: + if query: + self._common_filter = \ + lambda q: reduce(AND, [query(q), newquery(q)]) newquery = query & newquery - self._common_filter = newquery + else: + self._common_filter = newquery def _validate(self, **vars): errors = Row() From b872cced3343089c081d6ee426a597bd066b8c3d Mon Sep 17 00:00:00 2001 From: mdipierro Date: Mon, 12 Jan 2015 20:39:14 -0600 Subject: [PATCH 36/45] fixed issue 2001, thanks Anthony --- VERSION | 2 +- gluon/tools.py | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/VERSION b/VERSION index ce54ce20..70772022 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -Version 2.10.0-beta+timestamp.2014.10.16.15.58.50 +Version 2.9.12-beta+timestamp.2015.01.12.20.38.57 diff --git a/gluon/tools.py b/gluon/tools.py index 0b1dbd10..8db8d0ae 100644 --- a/gluon/tools.py +++ b/gluon/tools.py @@ -1258,7 +1258,8 @@ class Auth(object): def __init__(self, environment=None, db=None, mailer=True, hmac_key=None, controller='default', function='user', cas_provider=None, signature=True, secure=False, - csrf_prevention=True, propagate_extension=None): + csrf_prevention=True, propagate_extension=None, + url_index=None): ## next two lines for backward compatibility if not db and environment and isinstance(environment, DAL): @@ -1295,7 +1296,7 @@ class Auth(object): del session.auth # ## what happens after login? - url_index = URL(controller, 'index') + url_index = url_index or URL(controller, 'index') url_login = URL(controller, function, args='login', extension = propagate_extension) # ## what happens after registration? From 15bf3e2ededab97d3183fd315d3e4c5136c97470 Mon Sep 17 00:00:00 2001 From: mdipierro Date: Mon, 12 Jan 2015 20:53:28 -0600 Subject: [PATCH 37/45] fixed issue 1991, thanks Mark --- VERSION | 2 +- gluon/html.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/VERSION b/VERSION index 70772022..1ff6dcfe 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -Version 2.9.12-beta+timestamp.2015.01.12.20.38.57 +Version 2.9.12-beta+timestamp.2015.01.12.20.53.19 diff --git a/gluon/html.py b/gluon/html.py index ee491479..7b88a87f 100644 --- a/gluon/html.py +++ b/gluon/html.py @@ -850,7 +850,7 @@ class DIV(XmlComponent): """ components = [] for c in self.components: - if isinstance(c, allowed_parents): + if isinstance(c, (allowed_parents,CAT)): pass elif wrap_lambda: c = wrap_lambda(c) From 57c5fb64f6d056d67302a3377d814f14f2a29104 Mon Sep 17 00:00:00 2001 From: mdipierro Date: Mon, 12 Jan 2015 21:00:49 -0600 Subject: [PATCH 38/45] fixed issue 1978, thanks mbelletti --- VERSION | 2 +- gluon/sqlhtml.py | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/VERSION b/VERSION index 1ff6dcfe..8cc74977 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -Version 2.9.12-beta+timestamp.2015.01.12.20.53.19 +Version 2.9.12-beta+timestamp.2015.01.12.21.00.43 diff --git a/gluon/sqlhtml.py b/gluon/sqlhtml.py index 2058f291..28c37615 100644 --- a/gluon/sqlhtml.py +++ b/gluon/sqlhtml.py @@ -2348,7 +2348,9 @@ class SQLFORM(FORM): # expcolumns is all cols to be exported including virtual fields rows.colnames = expcolumns oExp = clazz(rows) - filename = '.'.join(('rows', oExp.file_ext)) + export_filename = \ + request.vars.get('_export_filename') or 'rows' + filename = '.'.join((export_filename, oExp.file_ext)) response.headers['Content-Type'] = oExp.content_type response.headers['Content-Disposition'] = \ 'attachment;filename=' + filename + ';' From 1c2358671db99839be4e7370ab87fffda960c6e6 Mon Sep 17 00:00:00 2001 From: Andrew Willimott Date: Wed, 14 Jan 2015 14:28:43 +1300 Subject: [PATCH 39/45] Initial simple change for adding geospatial support to Teradata adaptor. --- gluon/dal/adapters/teradata.py | 1 + 1 file changed, 1 insertion(+) diff --git a/gluon/dal/adapters/teradata.py b/gluon/dal/adapters/teradata.py index f8b8f9e7..817af60b 100644 --- a/gluon/dal/adapters/teradata.py +++ b/gluon/dal/adapters/teradata.py @@ -31,6 +31,7 @@ class TeradataAdapter(BaseAdapter): 'list:integer': 'VARCHAR(4000)', 'list:string': 'VARCHAR(4000)', 'list:reference': 'VARCHAR(4000)', + 'geometry': 'ST_GEOMETRY', # http://www.info.teradata.com/HTMLPubs/DB_TTU_14_00/index.html#page/Database_Management/B035_1094_111A/ch14.055.160.html 'big-id': 'BIGINT GENERATED ALWAYS AS IDENTITY', # Teradata Specific 'big-reference': 'BIGINT', 'reference FK': ' REFERENCES %(foreign_key)s', From aaf1dd614acde834d5afa1f6d8651960a758ec45 Mon Sep 17 00:00:00 2001 From: Radu Ioan Fericean Date: Wed, 14 Jan 2015 14:16:42 +0200 Subject: [PATCH 40/45] fix issuer comparison the issuer looks like gmail.login.persona.org and the expected value was login.persona.org --- gluon/contrib/login_methods/browserid_account.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gluon/contrib/login_methods/browserid_account.py b/gluon/contrib/login_methods/browserid_account.py index 8214276f..5698f746 100644 --- a/gluon/contrib/login_methods/browserid_account.py +++ b/gluon/contrib/login_methods/browserid_account.py @@ -73,7 +73,7 @@ class BrowserID(object): auth_info_json = fetch(self.verify_url, data=verify_data) j = json.loads(auth_info_json) epoch_time = int(time.time() * 1000) # we need 13 digit epoch time - if j["status"] == "okay" and j["audience"] == audience and j['issuer'] == issuer and j['expires'] >= epoch_time: + if j["status"] == "okay" and j["audience"] == audience and j['issuer'].endswith(issuer) and j['expires'] >= epoch_time: return dict(email=j['email']) elif self.on_login_failure: #print "status: ", j["status"]=="okay", j["status"] From bda69b0e88362ca39a8104bdd81d2f73044af368 Mon Sep 17 00:00:00 2001 From: mdipierro Date: Thu, 15 Jan 2015 09:47:57 -0600 Subject: [PATCH 41/45] mail timeout --- VERSION | 2 +- gluon/tools.py | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/VERSION b/VERSION index 8cc74977..dcf9788c 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -Version 2.9.12-beta+timestamp.2015.01.12.21.00.43 +Version 2.9.12-beta+timestamp.2015.01.15.09.47.52 diff --git a/gluon/tools.py b/gluon/tools.py index 8db8d0ae..d718f1f4 100644 --- a/gluon/tools.py +++ b/gluon/tools.py @@ -136,6 +136,7 @@ class Mail(object): mail.settings.server mail.settings.sender mail.settings.login + mail.settings.timeout = 60 # seconds (default) When server is 'logging', email is logged but not sent (debug mode) @@ -265,6 +266,7 @@ class Mail(object): settings.sender = sender settings.login = login settings.tls = tls + settings.timeout = 60 # seconds settings.hostname = None settings.ssl = False settings.cipher_type = None @@ -787,10 +789,11 @@ class Mail(object): subject=subject, body=text, **xcc) else: smtp_args = self.settings.server.split(':') + kwargs = dict(timeout = self.settings.timeout) if self.settings.ssl: - server = smtplib.SMTP_SSL(*smtp_args) + server = smtplib.SMTP_SSL(*smtp_args, **kwargs) else: - server = smtplib.SMTP(*smtp_args) + server = smtplib.SMTP(*smtp_args, **kwargs) if self.settings.tls and not self.settings.ssl: server.ehlo(self.settings.hostname) server.starttls() From c6cc06f6c033ae8a8d24bbe6a677d26414ba96e3 Mon Sep 17 00:00:00 2001 From: mdipierro Date: Thu, 15 Jan 2015 09:58:13 -0600 Subject: [PATCH 42/45] fixed grid export with custom search, thanks Prasad Muley --- VERSION | 2 +- gluon/sqlhtml.py | 15 ++++++++++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/VERSION b/VERSION index dcf9788c..3374f8b2 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -Version 2.9.12-beta+timestamp.2015.01.15.09.47.52 +Version 2.9.12-beta+timestamp.2015.01.15.09.58.09 diff --git a/gluon/sqlhtml.py b/gluon/sqlhtml.py index 28c37615..6e32aa22 100644 --- a/gluon/sqlhtml.py +++ b/gluon/sqlhtml.py @@ -2326,7 +2326,7 @@ class SQLFORM(FORM): expcolumns.append(str(field)) if export_type in exportManager and exportManager[export_type]: - if keywords: + if keywords and not callable(searchable): try: #the query should be constructed using searchable #fields but not virtual fields @@ -2339,6 +2339,19 @@ class SQLFORM(FORM): except Exception, e: response.flash = T('Internal Error') rows = [] + elif callable(searchable): + #use custom_query using searchable + try: + #the query should be constructed using searchable + #fields but not virtual fields + sfields = reduce(lambda a, b: a + b, + [[f for f in t if f.readable and not isinstance(f, Field.Virtual)] for t in tables]) + dbset = dbset(searchable(sfields, keywords)) + rows = dbset.select(left=left, orderby=orderby, + cacheable=True, *selectable_columns) + except Exception, e: + response.flash = T('Internal Error') + rows = [] else: rows = dbset.select(left=left, orderby=orderby, cacheable=True, *selectable_columns) From 5958704509ca8cd37def98822a46ecd741b99068 Mon Sep 17 00:00:00 2001 From: Prasad Muley Date: Thu, 15 Jan 2015 15:37:09 +0530 Subject: [PATCH 43/45] Fix: Exporting from a SQLFORM.grid with customized search queries issues #2006 --- gluon/sqlhtml.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/gluon/sqlhtml.py b/gluon/sqlhtml.py index 28c37615..df9e8f0f 100644 --- a/gluon/sqlhtml.py +++ b/gluon/sqlhtml.py @@ -2332,8 +2332,12 @@ class SQLFORM(FORM): #fields but not virtual fields sfields = reduce(lambda a, b: a + b, [[f for f in t if f.readable and not isinstance(f, Field.Virtual)] for t in tables]) - dbset = dbset(SQLFORM.build_query( - sfields, keywords)) + #use custom_query using searchable + if callable(searchable): + dbset = dbset(searchable(sfields, keywords)) + else: + dbset = dbset(SQLFORM.build_query( + sfields, keywords)) rows = dbset.select(left=left, orderby=orderby, cacheable=True, *selectable_columns) except Exception, e: From 35840bc572c58724756e58ab3ad48dd8a10ceae0 Mon Sep 17 00:00:00 2001 From: Prasad Muley Date: Fri, 16 Jan 2015 21:01:33 +0530 Subject: [PATCH 44/45] Fix: Exporting from a SQLFORM.grid with customized search queries Massimo manually applied older diff file. He also merged my newer diff file. So Optimized code --- gluon/sqlhtml.py | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/gluon/sqlhtml.py b/gluon/sqlhtml.py index e3171010..df9e8f0f 100644 --- a/gluon/sqlhtml.py +++ b/gluon/sqlhtml.py @@ -2326,7 +2326,7 @@ class SQLFORM(FORM): expcolumns.append(str(field)) if export_type in exportManager and exportManager[export_type]: - if keywords and not callable(searchable): + if keywords: try: #the query should be constructed using searchable #fields but not virtual fields @@ -2343,19 +2343,6 @@ class SQLFORM(FORM): except Exception, e: response.flash = T('Internal Error') rows = [] - elif callable(searchable): - #use custom_query using searchable - try: - #the query should be constructed using searchable - #fields but not virtual fields - sfields = reduce(lambda a, b: a + b, - [[f for f in t if f.readable and not isinstance(f, Field.Virtual)] for t in tables]) - dbset = dbset(searchable(sfields, keywords)) - rows = dbset.select(left=left, orderby=orderby, - cacheable=True, *selectable_columns) - except Exception, e: - response.flash = T('Internal Error') - rows = [] else: rows = dbset.select(left=left, orderby=orderby, cacheable=True, *selectable_columns) From 5bc5d0496ea83f9e8dd9822151872bd039ddd17e Mon Sep 17 00:00:00 2001 From: mdipierro Date: Sat, 17 Jan 2015 00:07:10 -0600 Subject: [PATCH 45/45] R-2.9.12 --- CHANGELOG | 18 + Makefile | 2 +- VERSION | 2 +- applications/admin/controllers/default.py | 51 +- applications/admin/languages/cs.py | 960 ++++++------ applications/admin/models/0.py | 2 - applications/admin/models/menu.py | 1 - .../admin/models/plugin_statebutton.py | 5 +- extras/build_web2py/setup_app.py | 4 +- extras/build_web2py/setup_exe.py | 64 +- gluon/__init__.py | 2 +- gluon/cache.py | 1386 ++++++++--------- gluon/compileapp.py | 4 +- gluon/contrib/hypermedia.py | 21 +- gluon/contrib/memdb.py | 12 +- gluon/contrib/mockimaplib.py | 7 +- gluon/contrib/pbkdf2_ctypes.py | 8 +- gluon/contrib/pypyodbc.py | 816 +++++----- gluon/contrib/stripe.py | 44 +- gluon/contrib/webclient.py | 1 - gluon/contrib/websocket_messaging.py | 4 +- gluon/custom_import.py | 2 +- gluon/dal/_load.py | 4 +- gluon/dal/objects.py | 7 +- gluon/fileutils.py | 8 +- gluon/html.py | 2 +- gluon/main.py | 4 +- gluon/recfile.py | 126 +- gluon/shell.py | 2 +- gluon/template.py | 2 +- gluon/tests/fix_path.py | 2 +- gluon/tests/test_contribs.py | 2 +- gluon/tests/test_dal_nosql.py | 3 +- gluon/tests/test_router.py | 44 +- gluon/tests/test_routes.py | 4 +- gluon/tools.py | 63 +- gluon/utils.py | 1 - handlers/web2py_on_gevent.py | 17 +- scripts/cpdb.py | 20 +- scripts/extract_oracle_models.py | 2 +- scripts/import_static.py | 10 +- scripts/service/linux.py | 65 +- scripts/service/service.py | 56 +- scripts/sessions2trash.py | 4 +- 44 files changed, 1934 insertions(+), 1930 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 9997466d..f6329e6b 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,21 @@ +## 2.9.12 + +- Tornado HTTPS support, thanks Diego +- Modular DAL, thanks Giovanni +- Added coverage support, thanks Niphlod +- More tests, thanks Niphlod and Paolo Valleri +- Added support for show_if in readonly sqlform, thanks Paolo +- Improved scheduler, thanks Niphlod +- Email timeout support +- Made web2py's custom_import work with circular imports, thanks Jack Kuan +- Added Portuguese, Catalan, and Burmese translations +- Allow map_hyphen to work for application names, thanks Tim Nyborg +- New module appconfig.py, thanks Niphlod +- Added geospatial support to Teradata adaptor, thanks Andrew Willimott +- Many bug fixes + + + ## 2.9.6 - 2.9.10 - fixed support of GAE + SQL diff --git a/Makefile b/Makefile index 14ff4d92..42f7375b 100644 --- a/Makefile +++ b/Makefile @@ -37,7 +37,7 @@ update: echo "remember that pymysql was tweaked" src: ### Use semantic versioning - echo 'Version 2.9.12-beta+timestamp.'`date +%Y.%m.%d.%H.%M.%S` > VERSION + echo 'Version 2.9.12-stable+timestamp.'`date +%Y.%m.%d.%H.%M.%S` > VERSION ### rm -f all junk files make clean ### clean up baisc apps diff --git a/VERSION b/VERSION index 3374f8b2..3af04ccf 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -Version 2.9.12-beta+timestamp.2015.01.15.09.58.09 +Version 2.9.12-stable+timestamp.2015.01.17.00.07.04 diff --git a/applications/admin/controllers/default.py b/applications/admin/controllers/default.py index 547d6c94..4623c517 100644 --- a/applications/admin/controllers/default.py +++ b/applications/admin/controllers/default.py @@ -589,7 +589,7 @@ def edit(): if 'settings' in request.vars: if request.post_vars: #save new preferences post_vars = request.post_vars.items() - # Since unchecked checkbox are not serialized, we must set them as false by hand to store the correct preference in the settings + # Since unchecked checkbox are not serialized, we must set them as false by hand to store the correct preference in the settings post_vars+= [(opt, 'false') for opt in preferences if opt not in request.post_vars ] if config.save(post_vars): response.headers["web2py-component-flash"] = T('Preferences saved correctly') @@ -775,12 +775,12 @@ def edit(): view_link=view_link, editviewlinks=editviewlinks, id=IS_SLUG()(filename)[0], - force= True if (request.vars.restore or + force= True if (request.vars.restore or request.vars.revert) else False) plain_html = response.render('default/edit_js.html', file_details) file_details['plain_html'] = plain_html if is_mobile: - return response.render('default.mobile/edit.html', + return response.render('default.mobile/edit.html', file_details, editor_settings=preferences) else: return response.json(file_details) @@ -1278,7 +1278,7 @@ def create_file(): path = abspath(request.vars.location) else: if request.vars.dir: - request.vars.location += request.vars.dir + '/' + request.vars.location += request.vars.dir + '/' app = get_app(name=request.vars.location.split('/')[0]) path = apath(request.vars.location, r=request) filename = re.sub('[^\w./-]+', '_', request.vars.filename) @@ -1387,7 +1387,7 @@ def create_file(): from gluon import *\n""")[1:] elif (path[-8:] == '/static/') or (path[-9:] == '/private/'): - if (request.vars.plugin and + if (request.vars.plugin and not filename.startswith('plugin_%s/' % request.vars.plugin)): filename = 'plugin_%s/%s' % (request.vars.plugin, filename) text = '' @@ -1434,37 +1434,37 @@ def create_file(): """ % URL('edit', args=[app,request.vars.dir,filename]) return '' else: - redirect(request.vars.sender + anchor) + redirect(request.vars.sender + anchor) def listfiles(app, dir, regexp='.*\.py$'): - files = sorted( + files = sorted( listdir(apath('%(app)s/%(dir)s/' % {'app':app, 'dir':dir}, r=request), regexp)) - files = [x.replace('\\', '/') for x in files if not x.endswith('.bak')] - return files - + files = [x.replace('\\', '/') for x in files if not x.endswith('.bak')] + return files + def editfile(path,file,vars={}, app = None): - args=(path,file) if 'app' in vars else (app,path,file) - url = URL('edit', args=args, vars=vars) - return A(file, _class='editor_filelink', _href=url, _style='word-wrap: nowrap;') - + args=(path,file) if 'app' in vars else (app,path,file) + url = URL('edit', args=args, vars=vars) + return A(file, _class='editor_filelink', _href=url, _style='word-wrap: nowrap;') + def files_menu(): - app = request.vars.app or 'welcome' - dirs=[{'name':'models', 'reg':'.*\.py$'}, + app = request.vars.app or 'welcome' + dirs=[{'name':'models', 'reg':'.*\.py$'}, {'name':'controllers', 'reg':'.*\.py$'}, {'name':'views', 'reg':'[\w/\-]+(\.\w+)+$'}, {'name':'modules', 'reg':'.*\.py$'}, {'name':'static', 'reg': '[^\.#].*'}, {'name':'private', 'reg':'.*\.py$'}] - result_files = [] - for dir in dirs: - result_files.append(TAG[''](LI(dir['name'], _class="nav-header component", _onclick="collapse('" + dir['name'] + "_files');"), - LI(UL(*[LI(editfile(dir['name'], f, dict(id=dir['name'] + f.replace('.','__')), app), _style="overflow:hidden", _id=dir['name']+"__"+f.replace('.','__')) - for f in listfiles(app, dir['name'], regexp=dir['reg'])], - _class="nav nav-list small-font"), - _id=dir['name'] + '_files', _style="display: none;"))) - return dict(result_files = result_files) - + result_files = [] + for dir in dirs: + result_files.append(TAG[''](LI(dir['name'], _class="nav-header component", _onclick="collapse('" + dir['name'] + "_files');"), + LI(UL(*[LI(editfile(dir['name'], f, dict(id=dir['name'] + f.replace('.','__')), app), _style="overflow:hidden", _id=dir['name']+"__"+f.replace('.','__')) + for f in listfiles(app, dir['name'], regexp=dir['reg'])], + _class="nav nav-list small-font"), + _id=dir['name'] + '_files', _style="display: none;"))) + return dict(result_files = result_files) + def upload_file(): """ File uploading handler """ if request.vars and not request.vars.token == session.token: @@ -1941,4 +1941,3 @@ def install_plugin(): T('unable to install plugin "%s"', filename) redirect(URL(f="plugins", args=[app,])) return dict(form=form, app=app, plugin=plugin, source=source) - diff --git a/applications/admin/languages/cs.py b/applications/admin/languages/cs.py index 9c8c7b63..1b9481ef 100644 --- a/applications/admin/languages/cs.py +++ b/applications/admin/languages/cs.py @@ -1,480 +1,480 @@ -# -*- coding: utf-8 -*- -{ -'!langcode!': 'cs-cz', -'!langname!': 'čeština', -'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': 'Kolonka "Upravit" je nepovinný výraz, například "pole1=\'nováhodnota\'". Výsledky databázového JOINu nemůžete mazat ani upravovat.', -'"User Exception" debug mode. An error ticket could be issued!': '"User Exception" debug mode. An error ticket could be issued!', -'%%{Row} in Table': '%%{řádek} v tabulce', -'%%{Row} selected': 'označených %%{řádek}', -'%s %%{row} deleted': '%s smazaných %%{záznam}', -'%s %%{row} updated': '%s upravených %%{záznam}', -'%s selected': '%s označených', -'%Y-%m-%d': '%d.%m.%Y', -'%Y-%m-%d %H:%M:%S': '%d.%m.%Y %H:%M:%S', -'(requires internet access)': '(vyžaduje připojení k internetu)', -'(requires internet access, experimental)': '(requires internet access, experimental)', -'(something like "it-it")': '(například "cs-cs")', -'@markmin\x01(file **gluon/contrib/plural_rules/%s.py** is not found)': '(soubor **gluon/contrib/plural_rules/%s.py** nenalezen)', -'@markmin\x01Searching: **%s** %%{file}': 'Hledání: **%s** %%{soubor}', -'About': 'O programu', -'About application': 'O aplikaci', -'Access Control': 'Řízení přístupu', -'Add breakpoint': 'Přidat bod přerušení', -'Additional code for your application': 'Další kód pro Vaši aplikaci', -'Admin design page': 'Admin design page', -'Admin language': 'jazyk rozhraní', -'Administrative interface': 'pro administrátorské rozhraní klikněte sem', -'Administrative Interface': 'Administrátorské rozhraní', -'administrative interface': 'rozhraní pro správu', -'Administrator Password:': 'Administrátorské heslo:', -'Ajax Recipes': 'Recepty s ajaxem', -'An error occured, please %s the page': 'An error occured, please %s the page', -'and rename it:': 'a přejmenovat na:', -'appadmin': 'appadmin', -'appadmin is disabled because insecure channel': 'appadmin je zakázaná bez zabezpečeného spojení', -'Application': 'Application', -'application "%s" uninstalled': 'application "%s" odinstalována', -'application compiled': 'aplikace zkompilována', -'Application name:': 'Název aplikace:', -'are not used': 'nepoužita', -'are not used yet': 'ještě nepoužita', -'Are you sure you want to delete this object?': 'Opravdu chcete odstranit tento objekt?', -'Are you sure you want to uninstall application "%s"?': 'Opravdu chcete odinstalovat aplikaci "%s"?', -'arguments': 'arguments', -'at char %s': 'at char %s', -'at line %s': 'at line %s', -'ATTENTION:': 'ATTENTION:', -'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.', -'Available Databases and Tables': 'Dostupné databáze a tabulky', -'back': 'zpět', -'Back to wizard': 'Back to wizard', -'Basics': 'Basics', -'Begin': 'Začít', -'breakpoint': 'bod přerušení', -'Breakpoints': 'Body přerušení', -'breakpoints': 'body přerušení', -'Buy this book': 'Koupit web2py knihu', -'Cache': 'Cache', -'cache': 'cache', -'Cache Keys': 'Klíče cache', -'cache, errors and sessions cleaned': 'cache, chyby a relace byly pročištěny', -'can be a git repo': 'může to být git repo', -'Cancel': 'Storno', -'Cannot be empty': 'Nemůže být prázdné', -'Change Admin Password': 'Změnit heslo pro správu', -'Change admin password': 'Změnit heslo pro správu aplikací', -'Change password': 'Změna hesla', -'check all': 'vše označit', -'Check for upgrades': 'Zkusit aktualizovat', -'Check to delete': 'Označit ke smazání', -'Check to delete:': 'Označit ke smazání:', -'Checking for upgrades...': 'Zjišťuji, zda jsou k dispozici aktualizace...', -'Clean': 'Pročistit', -'Clear CACHE?': 'Vymazat CACHE?', -'Clear DISK': 'Vymazat DISK', -'Clear RAM': 'Vymazat RAM', -'Click row to expand traceback': 'Pro rozbalení stopy, klikněte na řádek', -'Click row to view a ticket': 'Pro zobrazení chyby (ticketu), klikněte na řádku...', -'Client IP': 'IP adresa klienta', -'code': 'code', -'Code listing': 'Code listing', -'collapse/expand all': 'vše sbalit/rozbalit', -'Community': 'Komunita', -'Compile': 'Zkompilovat', -'compiled application removed': 'zkompilovaná aplikace smazána', -'Components and Plugins': 'Komponenty a zásuvné moduly', -'Condition': 'Podmínka', -'continue': 'continue', -'Controller': 'Kontrolér (Controller)', -'Controllers': 'Kontroléry', -'controllers': 'kontroléry', -'Copyright': 'Copyright', -'Count': 'Počet', -'Create': 'Vytvořit', -'create file with filename:': 'vytvořit soubor s názvem:', -'created by': 'vytvořil', -'Created By': 'Vytvořeno - kým', -'Created On': 'Vytvořeno - kdy', -'crontab': 'crontab', -'Current request': 'Aktuální požadavek', -'Current response': 'Aktuální odpověď', -'Current session': 'Aktuální relace', -'currently running': 'právě běží', -'currently saved or': 'uloženo nebo', -'customize me!': 'upravte mě!', -'data uploaded': 'data nahrána', -'Database': 'Rozhraní databáze', -'Database %s select': 'databáze %s výběr', -'Database administration': 'Database administration', -'database administration': 'správa databáze', -'Date and Time': 'Datum a čas', -'day': 'den', -'db': 'db', -'DB Model': 'Databázový model', -'Debug': 'Ladění', -'defines tables': 'defines tables', -'Delete': 'Smazat', -'delete': 'smazat', -'delete all checked': 'smazat vše označené', -'delete plugin': 'delete plugin', -'Delete this file (you will be asked to confirm deletion)': 'Smazat tento soubor (budete požádán o potvrzení mazání)', -'Delete:': 'Smazat:', -'deleted after first hit': 'smazat po prvním dosažení', -'Demo': 'Demo', -'Deploy': 'Nahrát', -'Deploy on Google App Engine': 'Nahrát na Google App Engine', -'Deploy to OpenShift': 'Nahrát na OpenShift', -'Deployment Recipes': 'Postupy pro deployment', -'Description': 'Popis', -'design': 'návrh', -'Detailed traceback description': 'Podrobný výpis prostředí', -'details': 'podrobnosti', -'direction: ltr': 'směr: ltr', -'Disable': 'Zablokovat', -'DISK': 'DISK', -'Disk Cache Keys': 'Klíče diskové cache', -'Disk Cleared': 'Disk smazán', -'docs': 'dokumentace', -'Documentation': 'Dokumentace', -"Don't know what to do?": 'Nevíte kudy kam?', -'done!': 'hotovo!', -'Download': 'Stáhnout', -'download layouts': 'stáhnout moduly rozvržení stránky', -'download plugins': 'stáhnout zásuvné moduly', -'E-mail': 'E-mail', -'Edit': 'Upravit', -'edit all': 'edit all', -'Edit application': 'Správa aplikace', -'edit controller': 'edit controller', -'Edit current record': 'Upravit aktuální záznam', -'Edit Profile': 'Upravit profil', -'edit views:': 'upravit pohled:', -'Editing file "%s"': 'Úprava souboru "%s"', -'Editing Language file': 'Úprava jazykového souboru', -'Editing Plural Forms File': 'Editing Plural Forms File', -'Email and SMS': 'Email a SMS', -'Enable': 'Odblokovat', -'enter a number between %(min)g and %(max)g': 'zadejte číslo mezi %(min)g a %(max)g', -'enter an integer between %(min)g and %(max)g': 'zadejte celé číslo mezi %(min)g a %(max)g', -'Error': 'Chyba', -'Error logs for "%(app)s"': 'Seznam výskytu chyb pro aplikaci "%(app)s"', -'Error snapshot': 'Snapshot chyby', -'Error ticket': 'Ticket chyby', -'Errors': 'Chyby', -'Exception %(extype)s: %(exvalue)s': 'Exception %(extype)s: %(exvalue)s', -'Exception %s': 'Exception %s', -'Exception instance attributes': 'Prvky instance výjimky', -'Expand Abbreviation': 'Expand Abbreviation', -'export as csv file': 'exportovat do .csv souboru', -'exposes': 'vystavuje', -'exposes:': 'vystavuje funkce:', -'extends': 'rozšiřuje', -'failed to compile file because:': 'soubor se nepodařilo zkompilovat, protože:', -'FAQ': 'Často kladené dotazy', -'File': 'Soubor', -'file': 'soubor', -'file "%(filename)s" created': 'file "%(filename)s" created', -'file saved on %(time)s': 'soubor uložen %(time)s', -'file saved on %s': 'soubor uložen %s', -'Filename': 'Název souboru', -'filter': 'filtr', -'Find Next': 'Najít další', -'Find Previous': 'Najít předchozí', -'First name': 'Křestní jméno', -'Forgot username?': 'Zapomněl jste svoje přihlašovací jméno?', -'forgot username?': 'zapomněl jste svoje přihlašovací jméno?', -'Forms and Validators': 'Formuláře a validátory', -'Frames': 'Frames', -'Free Applications': 'Aplikace zdarma', -'Functions with no doctests will result in [passed] tests.': 'Functions with no doctests will result in [passed] tests.', -'Generate': 'Vytvořit', -'Get from URL:': 'Stáhnout z internetu:', -'Git Pull': 'Git Pull', -'Git Push': 'Git Push', -'Globals##debug': 'Globální proměnné', -'go!': 'OK!', -'Goto': 'Goto', -'graph model': 'graph model', -'Group %(group_id)s created': 'Skupina %(group_id)s vytvořena', -'Group ID': 'ID skupiny', -'Groups': 'Skupiny', -'Hello World': 'Ahoj světe', -'Help': 'Nápověda', -'Hide/Show Translated strings': 'Skrýt/Zobrazit přeložené texty', -'Hits': 'Kolikrát dosaženo', -'Home': 'Domovská stránka', -'honored only if the expression evaluates to true': 'brát v potaz jen když se tato podmínka vyhodnotí kladně', -'How did you get here?': 'Jak jste se sem vlastně dostal?', -'If start the upgrade, be patient, it may take a while to download': 'If start the upgrade, be patient, it may take a while to download', -'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': 'import', -'Import/Export': 'Import/Export', -'includes': 'zahrnuje', -'Index': 'Index', -'insert new': 'vložit nový záznam ', -'insert new %s': 'vložit nový záznam %s', -'inspect attributes': 'inspect attributes', -'Install': 'Instalovat', -'Installed applications': 'Nainstalované aplikace', -'Interaction at %s line %s': 'Interakce v %s, na řádce %s', -'Interactive console': 'Interaktivní příkazová řádka', -'Internal State': 'Vnitřní stav', -'Introduction': 'Úvod', -'Invalid email': 'Neplatný email', -'Invalid password': 'Nesprávné heslo', -'invalid password.': 'neplatné heslo', -'Invalid Query': 'Neplatný dotaz', -'invalid request': 'Neplatný požadavek', -'Is Active': 'Je aktivní', -'It is %s %%{day} today.': 'Dnes je to %s %%{den}.', -'Key': 'Klíč', -'Key bindings': 'Vazby klíčů', -'Key bindings for ZenCoding Plugin': 'Key bindings for ZenCoding Plugin', -'languages': 'jazyky', -'Languages': 'Jazyky', -'Last name': 'Příjmení', -'Last saved on:': 'Naposledy uloženo:', -'Layout': 'Rozvržení stránky (layout)', -'Layout Plugins': 'Moduly rozvržení stránky (Layout Plugins)', -'Layouts': 'Rozvržení stránek', -'License for': 'Licence pro', -'Line number': 'Číslo řádku', -'LineNo': 'Č.řádku', -'Live Chat': 'Online pokec', -'loading...': 'nahrávám...', -'locals': 'locals', -'Locals##debug': 'Lokální proměnné', -'Logged in': 'Přihlášení proběhlo úspěšně', -'Logged out': 'Odhlášení proběhlo úspěšně', -'Login': 'Přihlásit se', -'login': 'přihlásit se', -'Login to the Administrative Interface': 'Přihlásit se do Správce aplikací', -'logout': 'odhlásit se', -'Logout': 'Odhlásit se', -'Lost Password': 'Zapomněl jste heslo', -'Lost password?': 'Zapomněl jste heslo?', -'lost password?': 'zapomněl jste heslo?', -'Manage': 'Manage', -'Manage Cache': 'Manage Cache', -'Menu Model': 'Model rozbalovací nabídky', -'Models': 'Modely', -'models': 'modely', -'Modified By': 'Změněno - kým', -'Modified On': 'Změněno - kdy', -'Modules': 'Moduly', -'modules': 'moduly', -'My Sites': 'Správa aplikací', -'Name': 'Jméno', -'new application "%s" created': 'nová aplikace "%s" vytvořena', -'New Application Wizard': 'Nový průvodce aplikací', -'New application wizard': 'Nový průvodce aplikací', -'New password': 'Nové heslo', -'New Record': 'Nový záznam', -'new record inserted': 'nový záznam byl založen', -'New simple application': 'Vytvořit primitivní aplikaci', -'next': 'next', -'next 100 rows': 'dalších 100 řádků', -'No databases in this application': 'V této aplikaci nejsou žádné databáze', -'No Interaction yet': 'Ještě žádná interakce nenastala', -'No ticket_storage.txt found under /private folder': 'Soubor ticket_storage.txt v adresáři /private nenalezen', -'Object or table name': 'Objekt či tabulka', -'Old password': 'Původní heslo', -'online designer': 'online návrhář', -'Online examples': 'Příklady online', -'Open new app in new window': 'Open new app in new window', -'or alternatively': 'or alternatively', -'Or Get from URL:': 'Or Get from URL:', -'or import from csv file': 'nebo importovat z .csv souboru', -'Origin': 'Původ', -'Original/Translation': 'Originál/Překlad', -'Other Plugins': 'Ostatní moduly', -'Other Recipes': 'Ostatní zásuvné moduly', -'Overview': 'Přehled', -'Overwrite installed app': 'Přepsat instalovanou aplikaci', -'Pack all': 'Zabalit', -'Pack compiled': 'Zabalit zkompilované', -'pack plugin': 'pack plugin', -'password': 'heslo', -'Password': 'Heslo', -"Password fields don't match": 'Hesla se neshodují', -'Peeking at file': 'Peeking at file', -'Please': 'Prosím', -'Plugin "%s" in application': 'Plugin "%s" in application', -'plugins': 'zásuvné moduly', -'Plugins': 'Zásuvné moduly', -'Plural Form #%s': 'Plural Form #%s', -'Plural-Forms:': 'Množná čísla:', -'Powered by': 'Poháněno', -'Preface': 'Předmluva', -'previous 100 rows': 'předchozích 100 řádků', -'Private files': 'Soukromé soubory', -'private files': 'soukromé soubory', -'profile': 'profil', -'Project Progress': 'Vývoj projektu', -'Python': 'Python', -'Query:': 'Dotaz:', -'Quick Examples': 'Krátké příklady', -'RAM': 'RAM', -'RAM Cache Keys': 'Klíče RAM Cache', -'Ram Cleared': 'RAM smazána', -'Readme': 'Nápověda', -'Recipes': 'Postupy jak na to', -'Record': 'Záznam', -'record does not exist': 'záznam neexistuje', -'Record ID': 'ID záznamu', -'Record id': 'id záznamu', -'refresh': 'obnovte', -'register': 'registrovat', -'Register': 'Zaregistrovat se', -'Registration identifier': 'Registrační identifikátor', -'Registration key': 'Registrační klíč', -'reload': 'reload', -'Reload routes': 'Znovu nahrát cesty', -'Remember me (for 30 days)': 'Zapamatovat na 30 dní', -'Remove compiled': 'Odstranit zkompilované', -'Removed Breakpoint on %s at line %s': 'Bod přerušení smazán - soubor %s na řádce %s', -'Replace': 'Zaměnit', -'Replace All': 'Zaměnit vše', -'request': 'request', -'Reset Password key': 'Reset registračního klíče', -'response': 'response', -'restart': 'restart', -'restore': 'obnovit', -'Retrieve username': 'Získat přihlašovací jméno', -'return': 'return', -'revert': 'vrátit se k původnímu', -'Role': 'Role', -'Rows in Table': 'Záznamy v tabulce', -'Rows selected': 'Záznamů zobrazeno', -'rules are not defined': 'pravidla nejsou definována', -"Run tests in this file (to run all files, you may also use the button labelled 'test')": "Spustí testy v tomto souboru (ke spuštění všech testů, použijte tlačítko 'test')", -'Running on %s': 'Běží na %s', -'Save': 'Uložit', -'Save file:': 'Save file:', -'Save via Ajax': 'Uložit pomocí Ajaxu', -'Saved file hash:': 'hash uloženého souboru:', -'Semantic': 'Modul semantic', -'Services': 'Služby', -'session': 'session', -'session expired': 'session expired', -'Set Breakpoint on %s at line %s: %s': 'Bod přerušení nastaven v souboru %s na řádce %s: %s', -'shell': 'příkazová řádka', -'Singular Form': 'Singular Form', -'Site': 'Správa aplikací', -'Size of cache:': 'Velikost cache:', -'skip to generate': 'skip to generate', -'Sorry, could not find mercurial installed': 'Bohužel mercurial není nainstalován.', -'Start a new app': 'Vytvořit novou aplikaci', -'Start searching': 'Začít hledání', -'Start wizard': 'Spustit průvodce', -'state': 'stav', -'Static': 'Static', -'static': 'statické soubory', -'Static files': 'Statické soubory', -'Statistics': 'Statistika', -'Step': 'Step', -'step': 'step', -'stop': 'stop', -'Stylesheet': 'CSS styly', -'submit': 'odeslat', -'Submit': 'Odeslat', -'successful': 'úspěšně', -'Support': 'Podpora', -'Sure you want to delete this object?': 'Opravdu chcete smazat tento objekt?', -'Table': 'tabulka', -'Table name': 'Název tabulky', -'Temporary': 'Dočasný', -'test': 'test', -'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.': '"Dotaz" je podmínka, například "db.tabulka1.pole1==\'hodnota\'". Podmínka "db.tabulka1.pole1==db.tabulka2.pole2" pak vytvoří SQL JOIN.', -'The application logic, each URL path is mapped in one exposed function in the controller': 'Logika aplikace: každá URL je mapována na funkci vystavovanou kontrolérem.', -'The Core': 'Jádro (The Core)', -'The data representation, define database tables and sets': 'Reprezentace dat: definovat tabulky databáze a záznamy', -'The output of the file is a dictionary that was rendered by the view %s': 'Výstup ze souboru je slovník, který se zobrazil v pohledu %s.', -'The presentations layer, views are also known as templates': 'Prezentační vrstva: pohledy či templaty (šablony)', -'The Views': 'Pohledy (The Views)', -'There are no controllers': 'There are no controllers', -'There are no modules': 'There are no modules', -'There are no plugins': 'Žádné moduly nejsou instalovány.', -'There are no private files': 'Žádné soukromé soubory neexistují.', -'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 not served, they are only available from within your app': 'Tyto soubory jsou klientům nepřístupné. K dispozici jsou pouze v rámci aplikace.', -'These files are served without processing, your images go here': 'Tyto soubory jsou servírovány bez přídavné logiky, sem patří např. obrázky.', -'This App': 'Tato aplikace', -'This is a copy of the scaffolding application': 'Toto je kopie aplikace skelet.', -'This is an experimental feature and it needs more testing. If you decide to upgrade you do it at your own risk': 'This is an experimental feature and it needs more testing. If you decide to upgrade you do it at your own risk', -'This is the %(filename)s template': 'This is the %(filename)s template', -'this page to see if a breakpoint was hit and debug interaction is required.': 'tuto stránku, abyste uviděli, zda se dosáhlo bodu přerušení.', -'Ticket': 'Ticket', -'Ticket ID': 'Ticket ID', -'Time in Cache (h:m:s)': 'Čas v Cache (h:m:s)', -'Timestamp': 'Časové razítko', -'to previous version.': 'k předchozí verzi.', -'To create a plugin, name a file/folder plugin_[name]': 'Zásuvný modul vytvoříte tak, že pojmenujete soubor/adresář plugin_[jméno modulu]', -'To emulate a breakpoint programatically, write:': 'K nastavení bodu přerušení v kódu programu, napište:', -'to use the debugger!': ', abyste mohli ladící program používat!', -'toggle breakpoint': 'vyp./zap. bod přerušení', -'Toggle Fullscreen': 'Na celou obrazovku a zpět', -'too short': 'Příliš krátké', -'Traceback': 'Traceback', -'Translation strings for the application': 'Překlad textů pro aplikaci', -'try something like': 'try something like', -'Try the mobile interface': 'Zkuste rozhraní pro mobilní zařízení', -'try view': 'try view', -'Twitter': 'Twitter', -'Type python statement in here and hit Return (Enter) to execute it.': 'Type python statement in here and hit Return (Enter) to execute it.', -'Type some Python code in here and hit Return (Enter) to execute it.': 'Type some Python code in here and hit Return (Enter) to execute it.', -'Unable to check for upgrades': 'Unable to check for upgrades', -'unable to parse csv file': 'csv soubor nedá sa zpracovat', -'uncheck all': 'vše odznačit', -'Uninstall': 'Odinstalovat', -'update': 'aktualizovat', -'update all languages': 'aktualizovat všechny jazyky', -'Update:': 'Upravit:', -'Upgrade': 'Upgrade', -'upgrade now': 'upgrade now', -'upgrade now to %s': 'upgrade now to %s', -'upload': 'nahrát', -'Upload': 'Upload', -'Upload a package:': 'Nahrát balík:', -'Upload and install packed application': 'Nahrát a instalovat zabalenou aplikaci', -'upload file:': 'nahrát soubor:', -'upload plugin file:': 'nahrát soubor modulu:', -'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Použijte (...)&(...) pro AND, (...)|(...) pro OR a ~(...) pro NOT pro sestavení složitějších dotazů.', -'User %(id)s Logged-in': 'Uživatel %(id)s přihlášen', -'User %(id)s Logged-out': 'Uživatel %(id)s odhlášen', -'User %(id)s Password changed': 'Uživatel %(id)s změnil heslo', -'User %(id)s Profile updated': 'Uživatel %(id)s upravil profil', -'User %(id)s Registered': 'Uživatel %(id)s se zaregistroval', -'User %(id)s Username retrieved': 'Uživatel %(id)s si nachal zaslat přihlašovací jméno', -'User ID': 'ID uživatele', -'Username': 'Přihlašovací jméno', -'variables': 'variables', -'Verify Password': 'Zopakujte heslo', -'Version': 'Verze', -'Version %s.%s.%s (%s) %s': 'Verze %s.%s.%s (%s) %s', -'Versioning': 'Verzování', -'Videos': 'Videa', -'View': 'Pohled (View)', -'Views': 'Pohledy', -'views': 'pohledy', -'Web Framework': 'Web Framework', -'web2py is up to date': 'Máte aktuální verzi web2py.', -'web2py online debugger': 'Ladící online web2py program', -'web2py Recent Tweets': 'Štěbetání na Twitteru o web2py', -'web2py upgrade': 'web2py upgrade', -'web2py upgraded; please restart it': 'web2py upgraded; please restart it', -'Welcome': 'Vítejte', -'Welcome to web2py': 'Vitejte ve web2py', -'Welcome to web2py!': 'Vítejte ve web2py!', -'Which called the function %s located in the file %s': 'která zavolala funkci %s v souboru (kontroléru) %s.', -'You are successfully running web2py': 'Úspěšně jste spustili web2py.', -'You can also set and remove breakpoint in the edit window, using the Toggle Breakpoint button': 'Nastavovat a mazat body přerušení je též možno v rámci editování zdrojového souboru přes tlačítko Vyp./Zap. bod přerušení', -'You can modify this application and adapt it to your needs': 'Tuto aplikaci si můžete upravit a přizpůsobit ji svým potřebám.', -'You need to set up and reach a': 'Je třeba nejprve nastavit a dojít až na', -'You visited the url %s': 'Navštívili jste stránku %s,', -'Your application will be blocked until you click an action button (next, step, continue, etc.)': 'Aplikace bude blokována než se klikne na jedno z tlačítek (další, krok, pokračovat, atd.)', -'You can inspect variables using the console bellow': 'Níže pomocí příkazové řádky si můžete prohlédnout proměnné', -} +# -*- coding: utf-8 -*- +{ +'!langcode!': 'cs-cz', +'!langname!': 'čeština', +'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': 'Kolonka "Upravit" je nepovinný výraz, například "pole1=\'nováhodnota\'". Výsledky databázového JOINu nemůžete mazat ani upravovat.', +'"User Exception" debug mode. An error ticket could be issued!': '"User Exception" debug mode. An error ticket could be issued!', +'%%{Row} in Table': '%%{řádek} v tabulce', +'%%{Row} selected': 'označených %%{řádek}', +'%s %%{row} deleted': '%s smazaných %%{záznam}', +'%s %%{row} updated': '%s upravených %%{záznam}', +'%s selected': '%s označených', +'%Y-%m-%d': '%d.%m.%Y', +'%Y-%m-%d %H:%M:%S': '%d.%m.%Y %H:%M:%S', +'(requires internet access)': '(vyžaduje připojení k internetu)', +'(requires internet access, experimental)': '(requires internet access, experimental)', +'(something like "it-it")': '(například "cs-cs")', +'@markmin\x01(file **gluon/contrib/plural_rules/%s.py** is not found)': '(soubor **gluon/contrib/plural_rules/%s.py** nenalezen)', +'@markmin\x01Searching: **%s** %%{file}': 'Hledání: **%s** %%{soubor}', +'About': 'O programu', +'About application': 'O aplikaci', +'Access Control': 'Řízení přístupu', +'Add breakpoint': 'Přidat bod přerušení', +'Additional code for your application': 'Další kód pro Vaši aplikaci', +'Admin design page': 'Admin design page', +'Admin language': 'jazyk rozhraní', +'Administrative interface': 'pro administrátorské rozhraní klikněte sem', +'Administrative Interface': 'Administrátorské rozhraní', +'administrative interface': 'rozhraní pro správu', +'Administrator Password:': 'Administrátorské heslo:', +'Ajax Recipes': 'Recepty s ajaxem', +'An error occured, please %s the page': 'An error occured, please %s the page', +'and rename it:': 'a přejmenovat na:', +'appadmin': 'appadmin', +'appadmin is disabled because insecure channel': 'appadmin je zakázaná bez zabezpečeného spojení', +'Application': 'Application', +'application "%s" uninstalled': 'application "%s" odinstalována', +'application compiled': 'aplikace zkompilována', +'Application name:': 'Název aplikace:', +'are not used': 'nepoužita', +'are not used yet': 'ještě nepoužita', +'Are you sure you want to delete this object?': 'Opravdu chcete odstranit tento objekt?', +'Are you sure you want to uninstall application "%s"?': 'Opravdu chcete odinstalovat aplikaci "%s"?', +'arguments': 'arguments', +'at char %s': 'at char %s', +'at line %s': 'at line %s', +'ATTENTION:': 'ATTENTION:', +'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.', +'Available Databases and Tables': 'Dostupné databáze a tabulky', +'back': 'zpět', +'Back to wizard': 'Back to wizard', +'Basics': 'Basics', +'Begin': 'Začít', +'breakpoint': 'bod přerušení', +'Breakpoints': 'Body přerušení', +'breakpoints': 'body přerušení', +'Buy this book': 'Koupit web2py knihu', +'Cache': 'Cache', +'cache': 'cache', +'Cache Keys': 'Klíče cache', +'cache, errors and sessions cleaned': 'cache, chyby a relace byly pročištěny', +'can be a git repo': 'může to být git repo', +'Cancel': 'Storno', +'Cannot be empty': 'Nemůže být prázdné', +'Change Admin Password': 'Změnit heslo pro správu', +'Change admin password': 'Změnit heslo pro správu aplikací', +'Change password': 'Změna hesla', +'check all': 'vše označit', +'Check for upgrades': 'Zkusit aktualizovat', +'Check to delete': 'Označit ke smazání', +'Check to delete:': 'Označit ke smazání:', +'Checking for upgrades...': 'Zjišťuji, zda jsou k dispozici aktualizace...', +'Clean': 'Pročistit', +'Clear CACHE?': 'Vymazat CACHE?', +'Clear DISK': 'Vymazat DISK', +'Clear RAM': 'Vymazat RAM', +'Click row to expand traceback': 'Pro rozbalení stopy, klikněte na řádek', +'Click row to view a ticket': 'Pro zobrazení chyby (ticketu), klikněte na řádku...', +'Client IP': 'IP adresa klienta', +'code': 'code', +'Code listing': 'Code listing', +'collapse/expand all': 'vše sbalit/rozbalit', +'Community': 'Komunita', +'Compile': 'Zkompilovat', +'compiled application removed': 'zkompilovaná aplikace smazána', +'Components and Plugins': 'Komponenty a zásuvné moduly', +'Condition': 'Podmínka', +'continue': 'continue', +'Controller': 'Kontrolér (Controller)', +'Controllers': 'Kontroléry', +'controllers': 'kontroléry', +'Copyright': 'Copyright', +'Count': 'Počet', +'Create': 'Vytvořit', +'create file with filename:': 'vytvořit soubor s názvem:', +'created by': 'vytvořil', +'Created By': 'Vytvořeno - kým', +'Created On': 'Vytvořeno - kdy', +'crontab': 'crontab', +'Current request': 'Aktuální požadavek', +'Current response': 'Aktuální odpověď', +'Current session': 'Aktuální relace', +'currently running': 'právě běží', +'currently saved or': 'uloženo nebo', +'customize me!': 'upravte mě!', +'data uploaded': 'data nahrána', +'Database': 'Rozhraní databáze', +'Database %s select': 'databáze %s výběr', +'Database administration': 'Database administration', +'database administration': 'správa databáze', +'Date and Time': 'Datum a čas', +'day': 'den', +'db': 'db', +'DB Model': 'Databázový model', +'Debug': 'Ladění', +'defines tables': 'defines tables', +'Delete': 'Smazat', +'delete': 'smazat', +'delete all checked': 'smazat vše označené', +'delete plugin': 'delete plugin', +'Delete this file (you will be asked to confirm deletion)': 'Smazat tento soubor (budete požádán o potvrzení mazání)', +'Delete:': 'Smazat:', +'deleted after first hit': 'smazat po prvním dosažení', +'Demo': 'Demo', +'Deploy': 'Nahrát', +'Deploy on Google App Engine': 'Nahrát na Google App Engine', +'Deploy to OpenShift': 'Nahrát na OpenShift', +'Deployment Recipes': 'Postupy pro deployment', +'Description': 'Popis', +'design': 'návrh', +'Detailed traceback description': 'Podrobný výpis prostředí', +'details': 'podrobnosti', +'direction: ltr': 'směr: ltr', +'Disable': 'Zablokovat', +'DISK': 'DISK', +'Disk Cache Keys': 'Klíče diskové cache', +'Disk Cleared': 'Disk smazán', +'docs': 'dokumentace', +'Documentation': 'Dokumentace', +"Don't know what to do?": 'Nevíte kudy kam?', +'done!': 'hotovo!', +'Download': 'Stáhnout', +'download layouts': 'stáhnout moduly rozvržení stránky', +'download plugins': 'stáhnout zásuvné moduly', +'E-mail': 'E-mail', +'Edit': 'Upravit', +'edit all': 'edit all', +'Edit application': 'Správa aplikace', +'edit controller': 'edit controller', +'Edit current record': 'Upravit aktuální záznam', +'Edit Profile': 'Upravit profil', +'edit views:': 'upravit pohled:', +'Editing file "%s"': 'Úprava souboru "%s"', +'Editing Language file': 'Úprava jazykového souboru', +'Editing Plural Forms File': 'Editing Plural Forms File', +'Email and SMS': 'Email a SMS', +'Enable': 'Odblokovat', +'enter a number between %(min)g and %(max)g': 'zadejte číslo mezi %(min)g a %(max)g', +'enter an integer between %(min)g and %(max)g': 'zadejte celé číslo mezi %(min)g a %(max)g', +'Error': 'Chyba', +'Error logs for "%(app)s"': 'Seznam výskytu chyb pro aplikaci "%(app)s"', +'Error snapshot': 'Snapshot chyby', +'Error ticket': 'Ticket chyby', +'Errors': 'Chyby', +'Exception %(extype)s: %(exvalue)s': 'Exception %(extype)s: %(exvalue)s', +'Exception %s': 'Exception %s', +'Exception instance attributes': 'Prvky instance výjimky', +'Expand Abbreviation': 'Expand Abbreviation', +'export as csv file': 'exportovat do .csv souboru', +'exposes': 'vystavuje', +'exposes:': 'vystavuje funkce:', +'extends': 'rozšiřuje', +'failed to compile file because:': 'soubor se nepodařilo zkompilovat, protože:', +'FAQ': 'Často kladené dotazy', +'File': 'Soubor', +'file': 'soubor', +'file "%(filename)s" created': 'file "%(filename)s" created', +'file saved on %(time)s': 'soubor uložen %(time)s', +'file saved on %s': 'soubor uložen %s', +'Filename': 'Název souboru', +'filter': 'filtr', +'Find Next': 'Najít další', +'Find Previous': 'Najít předchozí', +'First name': 'Křestní jméno', +'Forgot username?': 'Zapomněl jste svoje přihlašovací jméno?', +'forgot username?': 'zapomněl jste svoje přihlašovací jméno?', +'Forms and Validators': 'Formuláře a validátory', +'Frames': 'Frames', +'Free Applications': 'Aplikace zdarma', +'Functions with no doctests will result in [passed] tests.': 'Functions with no doctests will result in [passed] tests.', +'Generate': 'Vytvořit', +'Get from URL:': 'Stáhnout z internetu:', +'Git Pull': 'Git Pull', +'Git Push': 'Git Push', +'Globals##debug': 'Globální proměnné', +'go!': 'OK!', +'Goto': 'Goto', +'graph model': 'graph model', +'Group %(group_id)s created': 'Skupina %(group_id)s vytvořena', +'Group ID': 'ID skupiny', +'Groups': 'Skupiny', +'Hello World': 'Ahoj světe', +'Help': 'Nápověda', +'Hide/Show Translated strings': 'Skrýt/Zobrazit přeložené texty', +'Hits': 'Kolikrát dosaženo', +'Home': 'Domovská stránka', +'honored only if the expression evaluates to true': 'brát v potaz jen když se tato podmínka vyhodnotí kladně', +'How did you get here?': 'Jak jste se sem vlastně dostal?', +'If start the upgrade, be patient, it may take a while to download': 'If start the upgrade, be patient, it may take a while to download', +'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': 'import', +'Import/Export': 'Import/Export', +'includes': 'zahrnuje', +'Index': 'Index', +'insert new': 'vložit nový záznam ', +'insert new %s': 'vložit nový záznam %s', +'inspect attributes': 'inspect attributes', +'Install': 'Instalovat', +'Installed applications': 'Nainstalované aplikace', +'Interaction at %s line %s': 'Interakce v %s, na řádce %s', +'Interactive console': 'Interaktivní příkazová řádka', +'Internal State': 'Vnitřní stav', +'Introduction': 'Úvod', +'Invalid email': 'Neplatný email', +'Invalid password': 'Nesprávné heslo', +'invalid password.': 'neplatné heslo', +'Invalid Query': 'Neplatný dotaz', +'invalid request': 'Neplatný požadavek', +'Is Active': 'Je aktivní', +'It is %s %%{day} today.': 'Dnes je to %s %%{den}.', +'Key': 'Klíč', +'Key bindings': 'Vazby klíčů', +'Key bindings for ZenCoding Plugin': 'Key bindings for ZenCoding Plugin', +'languages': 'jazyky', +'Languages': 'Jazyky', +'Last name': 'Příjmení', +'Last saved on:': 'Naposledy uloženo:', +'Layout': 'Rozvržení stránky (layout)', +'Layout Plugins': 'Moduly rozvržení stránky (Layout Plugins)', +'Layouts': 'Rozvržení stránek', +'License for': 'Licence pro', +'Line number': 'Číslo řádku', +'LineNo': 'Č.řádku', +'Live Chat': 'Online pokec', +'loading...': 'nahrávám...', +'locals': 'locals', +'Locals##debug': 'Lokální proměnné', +'Logged in': 'Přihlášení proběhlo úspěšně', +'Logged out': 'Odhlášení proběhlo úspěšně', +'Login': 'Přihlásit se', +'login': 'přihlásit se', +'Login to the Administrative Interface': 'Přihlásit se do Správce aplikací', +'logout': 'odhlásit se', +'Logout': 'Odhlásit se', +'Lost Password': 'Zapomněl jste heslo', +'Lost password?': 'Zapomněl jste heslo?', +'lost password?': 'zapomněl jste heslo?', +'Manage': 'Manage', +'Manage Cache': 'Manage Cache', +'Menu Model': 'Model rozbalovací nabídky', +'Models': 'Modely', +'models': 'modely', +'Modified By': 'Změněno - kým', +'Modified On': 'Změněno - kdy', +'Modules': 'Moduly', +'modules': 'moduly', +'My Sites': 'Správa aplikací', +'Name': 'Jméno', +'new application "%s" created': 'nová aplikace "%s" vytvořena', +'New Application Wizard': 'Nový průvodce aplikací', +'New application wizard': 'Nový průvodce aplikací', +'New password': 'Nové heslo', +'New Record': 'Nový záznam', +'new record inserted': 'nový záznam byl založen', +'New simple application': 'Vytvořit primitivní aplikaci', +'next': 'next', +'next 100 rows': 'dalších 100 řádků', +'No databases in this application': 'V této aplikaci nejsou žádné databáze', +'No Interaction yet': 'Ještě žádná interakce nenastala', +'No ticket_storage.txt found under /private folder': 'Soubor ticket_storage.txt v adresáři /private nenalezen', +'Object or table name': 'Objekt či tabulka', +'Old password': 'Původní heslo', +'online designer': 'online návrhář', +'Online examples': 'Příklady online', +'Open new app in new window': 'Open new app in new window', +'or alternatively': 'or alternatively', +'Or Get from URL:': 'Or Get from URL:', +'or import from csv file': 'nebo importovat z .csv souboru', +'Origin': 'Původ', +'Original/Translation': 'Originál/Překlad', +'Other Plugins': 'Ostatní moduly', +'Other Recipes': 'Ostatní zásuvné moduly', +'Overview': 'Přehled', +'Overwrite installed app': 'Přepsat instalovanou aplikaci', +'Pack all': 'Zabalit', +'Pack compiled': 'Zabalit zkompilované', +'pack plugin': 'pack plugin', +'password': 'heslo', +'Password': 'Heslo', +"Password fields don't match": 'Hesla se neshodují', +'Peeking at file': 'Peeking at file', +'Please': 'Prosím', +'Plugin "%s" in application': 'Plugin "%s" in application', +'plugins': 'zásuvné moduly', +'Plugins': 'Zásuvné moduly', +'Plural Form #%s': 'Plural Form #%s', +'Plural-Forms:': 'Množná čísla:', +'Powered by': 'Poháněno', +'Preface': 'Předmluva', +'previous 100 rows': 'předchozích 100 řádků', +'Private files': 'Soukromé soubory', +'private files': 'soukromé soubory', +'profile': 'profil', +'Project Progress': 'Vývoj projektu', +'Python': 'Python', +'Query:': 'Dotaz:', +'Quick Examples': 'Krátké příklady', +'RAM': 'RAM', +'RAM Cache Keys': 'Klíče RAM Cache', +'Ram Cleared': 'RAM smazána', +'Readme': 'Nápověda', +'Recipes': 'Postupy jak na to', +'Record': 'Záznam', +'record does not exist': 'záznam neexistuje', +'Record ID': 'ID záznamu', +'Record id': 'id záznamu', +'refresh': 'obnovte', +'register': 'registrovat', +'Register': 'Zaregistrovat se', +'Registration identifier': 'Registrační identifikátor', +'Registration key': 'Registrační klíč', +'reload': 'reload', +'Reload routes': 'Znovu nahrát cesty', +'Remember me (for 30 days)': 'Zapamatovat na 30 dní', +'Remove compiled': 'Odstranit zkompilované', +'Removed Breakpoint on %s at line %s': 'Bod přerušení smazán - soubor %s na řádce %s', +'Replace': 'Zaměnit', +'Replace All': 'Zaměnit vše', +'request': 'request', +'Reset Password key': 'Reset registračního klíče', +'response': 'response', +'restart': 'restart', +'restore': 'obnovit', +'Retrieve username': 'Získat přihlašovací jméno', +'return': 'return', +'revert': 'vrátit se k původnímu', +'Role': 'Role', +'Rows in Table': 'Záznamy v tabulce', +'Rows selected': 'Záznamů zobrazeno', +'rules are not defined': 'pravidla nejsou definována', +"Run tests in this file (to run all files, you may also use the button labelled 'test')": "Spustí testy v tomto souboru (ke spuštění všech testů, použijte tlačítko 'test')", +'Running on %s': 'Běží na %s', +'Save': 'Uložit', +'Save file:': 'Save file:', +'Save via Ajax': 'Uložit pomocí Ajaxu', +'Saved file hash:': 'hash uloženého souboru:', +'Semantic': 'Modul semantic', +'Services': 'Služby', +'session': 'session', +'session expired': 'session expired', +'Set Breakpoint on %s at line %s: %s': 'Bod přerušení nastaven v souboru %s na řádce %s: %s', +'shell': 'příkazová řádka', +'Singular Form': 'Singular Form', +'Site': 'Správa aplikací', +'Size of cache:': 'Velikost cache:', +'skip to generate': 'skip to generate', +'Sorry, could not find mercurial installed': 'Bohužel mercurial není nainstalován.', +'Start a new app': 'Vytvořit novou aplikaci', +'Start searching': 'Začít hledání', +'Start wizard': 'Spustit průvodce', +'state': 'stav', +'Static': 'Static', +'static': 'statické soubory', +'Static files': 'Statické soubory', +'Statistics': 'Statistika', +'Step': 'Step', +'step': 'step', +'stop': 'stop', +'Stylesheet': 'CSS styly', +'submit': 'odeslat', +'Submit': 'Odeslat', +'successful': 'úspěšně', +'Support': 'Podpora', +'Sure you want to delete this object?': 'Opravdu chcete smazat tento objekt?', +'Table': 'tabulka', +'Table name': 'Název tabulky', +'Temporary': 'Dočasný', +'test': 'test', +'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.': '"Dotaz" je podmínka, například "db.tabulka1.pole1==\'hodnota\'". Podmínka "db.tabulka1.pole1==db.tabulka2.pole2" pak vytvoří SQL JOIN.', +'The application logic, each URL path is mapped in one exposed function in the controller': 'Logika aplikace: každá URL je mapována na funkci vystavovanou kontrolérem.', +'The Core': 'Jádro (The Core)', +'The data representation, define database tables and sets': 'Reprezentace dat: definovat tabulky databáze a záznamy', +'The output of the file is a dictionary that was rendered by the view %s': 'Výstup ze souboru je slovník, který se zobrazil v pohledu %s.', +'The presentations layer, views are also known as templates': 'Prezentační vrstva: pohledy či templaty (šablony)', +'The Views': 'Pohledy (The Views)', +'There are no controllers': 'There are no controllers', +'There are no modules': 'There are no modules', +'There are no plugins': 'Žádné moduly nejsou instalovány.', +'There are no private files': 'Žádné soukromé soubory neexistují.', +'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 not served, they are only available from within your app': 'Tyto soubory jsou klientům nepřístupné. K dispozici jsou pouze v rámci aplikace.', +'These files are served without processing, your images go here': 'Tyto soubory jsou servírovány bez přídavné logiky, sem patří např. obrázky.', +'This App': 'Tato aplikace', +'This is a copy of the scaffolding application': 'Toto je kopie aplikace skelet.', +'This is an experimental feature and it needs more testing. If you decide to upgrade you do it at your own risk': 'This is an experimental feature and it needs more testing. If you decide to upgrade you do it at your own risk', +'This is the %(filename)s template': 'This is the %(filename)s template', +'this page to see if a breakpoint was hit and debug interaction is required.': 'tuto stránku, abyste uviděli, zda se dosáhlo bodu přerušení.', +'Ticket': 'Ticket', +'Ticket ID': 'Ticket ID', +'Time in Cache (h:m:s)': 'Čas v Cache (h:m:s)', +'Timestamp': 'Časové razítko', +'to previous version.': 'k předchozí verzi.', +'To create a plugin, name a file/folder plugin_[name]': 'Zásuvný modul vytvoříte tak, že pojmenujete soubor/adresář plugin_[jméno modulu]', +'To emulate a breakpoint programatically, write:': 'K nastavení bodu přerušení v kódu programu, napište:', +'to use the debugger!': ', abyste mohli ladící program používat!', +'toggle breakpoint': 'vyp./zap. bod přerušení', +'Toggle Fullscreen': 'Na celou obrazovku a zpět', +'too short': 'Příliš krátké', +'Traceback': 'Traceback', +'Translation strings for the application': 'Překlad textů pro aplikaci', +'try something like': 'try something like', +'Try the mobile interface': 'Zkuste rozhraní pro mobilní zařízení', +'try view': 'try view', +'Twitter': 'Twitter', +'Type python statement in here and hit Return (Enter) to execute it.': 'Type python statement in here and hit Return (Enter) to execute it.', +'Type some Python code in here and hit Return (Enter) to execute it.': 'Type some Python code in here and hit Return (Enter) to execute it.', +'Unable to check for upgrades': 'Unable to check for upgrades', +'unable to parse csv file': 'csv soubor nedá sa zpracovat', +'uncheck all': 'vše odznačit', +'Uninstall': 'Odinstalovat', +'update': 'aktualizovat', +'update all languages': 'aktualizovat všechny jazyky', +'Update:': 'Upravit:', +'Upgrade': 'Upgrade', +'upgrade now': 'upgrade now', +'upgrade now to %s': 'upgrade now to %s', +'upload': 'nahrát', +'Upload': 'Upload', +'Upload a package:': 'Nahrát balík:', +'Upload and install packed application': 'Nahrát a instalovat zabalenou aplikaci', +'upload file:': 'nahrát soubor:', +'upload plugin file:': 'nahrát soubor modulu:', +'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Použijte (...)&(...) pro AND, (...)|(...) pro OR a ~(...) pro NOT pro sestavení složitějších dotazů.', +'User %(id)s Logged-in': 'Uživatel %(id)s přihlášen', +'User %(id)s Logged-out': 'Uživatel %(id)s odhlášen', +'User %(id)s Password changed': 'Uživatel %(id)s změnil heslo', +'User %(id)s Profile updated': 'Uživatel %(id)s upravil profil', +'User %(id)s Registered': 'Uživatel %(id)s se zaregistroval', +'User %(id)s Username retrieved': 'Uživatel %(id)s si nachal zaslat přihlašovací jméno', +'User ID': 'ID uživatele', +'Username': 'Přihlašovací jméno', +'variables': 'variables', +'Verify Password': 'Zopakujte heslo', +'Version': 'Verze', +'Version %s.%s.%s (%s) %s': 'Verze %s.%s.%s (%s) %s', +'Versioning': 'Verzování', +'Videos': 'Videa', +'View': 'Pohled (View)', +'Views': 'Pohledy', +'views': 'pohledy', +'Web Framework': 'Web Framework', +'web2py is up to date': 'Máte aktuální verzi web2py.', +'web2py online debugger': 'Ladící online web2py program', +'web2py Recent Tweets': 'Štěbetání na Twitteru o web2py', +'web2py upgrade': 'web2py upgrade', +'web2py upgraded; please restart it': 'web2py upgraded; please restart it', +'Welcome': 'Vítejte', +'Welcome to web2py': 'Vitejte ve web2py', +'Welcome to web2py!': 'Vítejte ve web2py!', +'Which called the function %s located in the file %s': 'která zavolala funkci %s v souboru (kontroléru) %s.', +'You are successfully running web2py': 'Úspěšně jste spustili web2py.', +'You can also set and remove breakpoint in the edit window, using the Toggle Breakpoint button': 'Nastavovat a mazat body přerušení je též možno v rámci editování zdrojového souboru přes tlačítko Vyp./Zap. bod přerušení', +'You can modify this application and adapt it to your needs': 'Tuto aplikaci si můžete upravit a přizpůsobit ji svým potřebám.', +'You need to set up and reach a': 'Je třeba nejprve nastavit a dojít až na', +'You visited the url %s': 'Navštívili jste stránku %s,', +'Your application will be blocked until you click an action button (next, step, continue, etc.)': 'Aplikace bude blokována než se klikne na jedno z tlačítek (další, krok, pokračovat, atd.)', +'You can inspect variables using the console bellow': 'Níže pomocí příkazové řádky si můžete prohlédnout proměnné', +} diff --git a/applications/admin/models/0.py b/applications/admin/models/0.py index 9f0a1d5a..adf95f7f 100644 --- a/applications/admin/models/0.py +++ b/applications/admin/models/0.py @@ -47,5 +47,3 @@ if 'adminLanguage' in request.cookies and not (request.cookies['adminLanguage'] #set static_version from gluon.settings import global_settings response.static_version = global_settings.web2py_version.split('-')[0] - - diff --git a/applications/admin/models/menu.py b/applications/admin/models/menu.py index 5534bcc9..f29f904c 100644 --- a/applications/admin/models/menu.py +++ b/applications/admin/models/menu.py @@ -34,4 +34,3 @@ else: URL(_a, 'default', f='logout'))) response.menu.append((T('Debug'), False, URL(_a, 'debug', 'interact'))) - diff --git a/applications/admin/models/plugin_statebutton.py b/applications/admin/models/plugin_statebutton.py index a857c5b0..21d0377e 100644 --- a/applications/admin/models/plugin_statebutton.py +++ b/applications/admin/models/plugin_statebutton.py @@ -7,11 +7,10 @@ def stateWidget(field, value, data={'on-label':'Enabled', 'off-label':'Disabled' except: fieldName = field - div = DIV(INPUT( _type='checkbox', _name='%s' % fieldName, _checked= 'checked' if value == 'true' else None, _value='true'), - _class='make-bootstrap-switch', + div = DIV(INPUT( _type='checkbox', _name='%s' % fieldName, _checked= 'checked' if value == 'true' else None, _value='true'), + _class='make-bootstrap-switch', data=data) script = SCRIPT(""" jQuery(".make-bootstrap-switch input[name='%s']").parent().bootstrapSwitch(); """ % fieldName) return DIV(div, script) - diff --git a/extras/build_web2py/setup_app.py b/extras/build_web2py/setup_app.py index aa68bbff..92985418 100755 --- a/extras/build_web2py/setup_app.py +++ b/extras/build_web2py/setup_app.py @@ -25,9 +25,9 @@ import sys import re import zipfile -#read web2py version from VERSION file +#read web2py version from VERSION file web2py_version_line = readlines_file('VERSION')[0] -#use regular expression to get just the version number +#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) diff --git a/extras/build_web2py/setup_exe.py b/extras/build_web2py/setup_exe.py index 19b2b2fa..ae0d00ee 100755 --- a/extras/build_web2py/setup_exe.py +++ b/extras/build_web2py/setup_exe.py @@ -1,8 +1,8 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- - + #Adapted from http://bazaar.launchpad.net/~flavour/sahana-eden/trunk/view/head:/static/scripts/tools/standalone_exe.py - + USAGE = """ Usage: Copy this and setup_exe.conf to web2py root folder @@ -13,7 +13,7 @@ Usage: Install bbfreeze: https://pypi.python.org/pypi/bbfreeze/ run python setup_exe.py bbfreeze """ - + from distutils.core import setup from gluon.import_all import base_modules, contributed_modules from gluon.fileutils import readlines_file @@ -24,7 +24,7 @@ import shutil import sys import re import zipfile - + if len(sys.argv) != 2 or not os.path.isfile('web2py.py'): print USAGE sys.exit(1) @@ -32,11 +32,11 @@ BUILD_MODE = sys.argv[1] if not BUILD_MODE in ('py2exe', 'bbfreeze'): print USAGE sys.exit(1) - + def unzip(source_filename, dest_dir): with zipfile.ZipFile(source_filename) as zf: zf.extractall(dest_dir) - + #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): @@ -45,14 +45,14 @@ def recursive_zip(zipf, directory, folder=""): elif os.path.isdir(os.path.join(directory, item)): recursive_zip( zipf, os.path.join(directory, item), folder + os.sep + item) - - + + #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() @@ -68,12 +68,12 @@ include_gevent = Config.getboolean("Setup", "include_gevent") # Python base version python_version = sys.version_info[:3] - - - + + + if BUILD_MODE == 'py2exe': import py2exe - + setup( console=[{'script':'web2py.py', 'icon_resources': [(0, 'extras/icons/web2py.ico')] @@ -88,8 +88,8 @@ if BUILD_MODE == 'py2exe': author="Massimo DiPierro", license="LGPL v3", data_files=[ - 'ABOUT', - 'LICENSE', + 'ABOUT', + 'LICENSE', 'VERSION' ], options={'py2exe': { @@ -108,7 +108,7 @@ if BUILD_MODE == 'py2exe': zipl.close() shutil.rmtree(library_temp_dir) print "web2py binary successfully built" - + elif BUILD_MODE == 'bbfreeze': modules = base_modules + contributed_modules from bbfreeze import Freezer @@ -131,26 +131,26 @@ elif BUILD_MODE == 'bbfreeze': for req in ['ABOUT', 'LICENSE', 'VERSION']: shutil.copy(req, os.path.join('dist', req)) print "web2py binary successfully built" - + try: os.unlink('storage.sqlite') except: pass - -#This need to happen after bbfreeze is run because Freezer() deletes distdir before starting! + +#This need to happen after bbfreeze is run because Freezer() deletes distdir before starting! if python_version > (2,5): # Python26 compatibility: http://www.py2exe.org/index.cgi/Tutorial#Step52 try: shutil.copytree('C:\Bin\Microsoft.VC90.CRT', 'dist/Microsoft.VC90.CRT/') except: print "You MUST copy Microsoft.VC90.CRT folder into the archive" - + 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" @@ -166,7 +166,7 @@ if remove_msft_dlls: os.unlink(os.path.join('dist', f)) except: print "unable to delete dist/" + f - + #Should we include applications? if copy_apps: copy_folders('applications', 'applications') @@ -177,12 +177,12 @@ else: copy_folders('applications/welcome', 'applications/welcome') copy_folders('applications/examples', 'applications/examples') print "Only web2py's admin, examples & welcome applications have been added" - + copy_folders('extras', 'extras') copy_folders('examples', 'examples') copy_folders('handlers', 'handlers') - - + + #should we copy project's site-packages into dist/site-packages if copy_site_packages: #copy site-packages @@ -190,7 +190,7 @@ if copy_site_packages: else: #no worries, web2py will create the (empty) folder first run print "Skipping site-packages" - + #should we copy project's scripts into dist/scripts if copy_scripts: #copy scripts @@ -198,7 +198,7 @@ if copy_scripts: else: #no worries, web2py will create the (empty) folder first run print "Skipping scripts" - + #should we create a zip file of the build? if make_zip: #create a web2py folder & copy dist's files into it @@ -209,13 +209,13 @@ if make_zip: # just temp so the web2py directory is included in our zip file path = 'zip_temp' # leave the first folder as None, as path is root. - recursive_zip(zipf, path) + recursive_zip(zipf, path) 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: if BUILD_MODE == 'py2exe': @@ -223,10 +223,10 @@ if remove_build_files: shutil.rmtree('deposit') shutil.rmtree('dist') print "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 \ No newline at end of file +print "Enjoy web2py " + web2py_version_line diff --git a/gluon/__init__.py b/gluon/__init__.py index 457b061d..d489d923 100644 --- a/gluon/__init__.py +++ b/gluon/__init__.py @@ -11,7 +11,7 @@ Web2Py framework modules """ __all__ = ['A', 'B', 'BEAUTIFY', 'BODY', 'BR', 'CAT', 'CENTER', 'CLEANUP', 'CODE', 'CRYPT', 'DAL', 'DIV', 'EM', 'EMBED', 'FIELDSET', 'FORM', 'Field', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'HEAD', 'HR', 'HTML', 'HTTP', 'I', 'IFRAME', 'IMG', 'INPUT', 'IS_ALPHANUMERIC', 'IS_DATE', 'IS_DATETIME', 'IS_DATETIME_IN_RANGE', 'IS_DATE_IN_RANGE', 'IS_DECIMAL_IN_RANGE', 'IS_EMAIL', 'IS_LIST_OF_EMAILS', 'IS_EMPTY_OR', 'IS_EQUAL_TO', 'IS_EXPR', 'IS_FLOAT_IN_RANGE', 'IS_IMAGE', 'IS_JSON', 'IS_INT_IN_RANGE', 'IS_IN_DB', 'IS_IN_SET', 'IS_IPV4', 'IS_LENGTH', 'IS_LIST_OF', 'IS_LOWER', 'IS_MATCH', 'IS_NOT_EMPTY', 'IS_NOT_IN_DB', 'IS_NULL_OR', 'IS_SLUG', 'IS_STRONG', 'IS_TIME', 'IS_UPLOAD_FILENAME', 'IS_UPPER', 'IS_URL', 'LABEL', 'LEGEND', 'LI', 'LINK', 'LOAD', 'MARKMIN', 'MENU', 'META', 'OBJECT', 'OL', 'ON', 'OPTGROUP', 'OPTION', 'P', 'PRE', 'SCRIPT', 'SELECT', 'SPAN', 'SQLFORM', 'SQLTABLE', 'STRONG', 'STYLE', 'TABLE', 'TAG', 'TBODY', 'TD', 'TEXTAREA', 'TFOOT', 'TH', 'THEAD', 'TITLE', 'TR', 'TT', 'UL', 'URL', 'XHTML', 'XML', 'redirect', 'current', 'embed64'] - + from globals import current from html import * from validators import * diff --git a/gluon/cache.py b/gluon/cache.py index 3a03a19c..671abe7e 100644 --- a/gluon/cache.py +++ b/gluon/cache.py @@ -1,693 +1,693 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -""" -| This file is part of the web2py Web Framework -| Copyrighted by Massimo Di Pierro -| 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 -- CacheOnDisk - 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 thread -import os -import sys -import logging -import re -import hashlib -import datetime -import tempfile -from gluon import recfile -try: - from gluon import settings - have_settings = True -except ImportError: - have_settings = False - -try: - import cPickle as pickle -except: - import pickle - -logger = logging.getLogger("web2py.cache") - -__all__ = ['Cache', 'lazy_cache'] - - -DEFAULT_TIME_EXPIRE = 300 - - - -class CacheAbstract(object): - """ - Abstract class for cache implementations. - Main function just provides referenced api documentation. - - Use CacheInRam or CacheOnDisk instead which are derived from this class. - - Note: - Michele says: there are signatures inside gdbm files that are used - directly by the python gdbm adapter that often are lagging behind in the - detection code in python part. - On every occasion that a gdbm store is probed by the python adapter, - the probe fails, because gdbm file version is newer. - Using gdbm directly from C would work, because there is backward - compatibility, but not from python! - The .shelve file is discarded and a new one created (with new - signature) and it works until it is probed again... - The possible consequences are memory leaks and broken sessions. - """ - - cache_stats_name = 'web2py_cache_statistics' - - def __init__(self, request=None): - """Initializes the object - - Args: - request: the global request object - """ - raise NotImplementedError - - def __call__(self, key, f, - time_expire=DEFAULT_TIME_EXPIRE): - """ - Tries to retrieve the value corresponding to `key` from the cache if the - object exists and if it did not expire, else it calls the function `f` - and stores the output in the cache corresponding to `key`. It always - returns the function that is returned. - - Args: - key(str): the key of the object to be stored or retrieved - f(function): the function whose output is to be cached. - - If `f` is `None` the cache is cleared. - time_expire(int): expiration of the cache in seconds. - - It's 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. - """ - 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. - - Args: - 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 - - Args: - key(str): key for the cached object to be incremeneted - value(int): 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 in storage.keys(): - if r.match(str(key)): - del storage[key] - return - - -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.initialized = False - self.request = request - self.storage = {} - - def initialize(self): - if self.initialized: - return - else: - self.initialized = True - self.locker.acquire() - request = self.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.initialize() - self.locker.acquire() - storage = self.storage - if regex is 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, - destroyer=None): - """ - 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: - - - would break backward compatibility - - would be limiting because people may want to cache live objects - - 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. - """ - self.initialize() - - dt = time_expire - now = time.time() - - self.locker.acquire() - item = self.storage.get(key, None) - if item and f is None: - del self.storage[key] - if destroyer: - destroyer(item[1]) - self.storage[CacheAbstract.cache_stats_name]['hit_total'] += 1 - self.locker.release() - - if f is None: - return None - if item and (dt is None or item[0] > now - dt): - return item[1] - elif item and (item[0] < now - dt) and destroyer: - destroyer(item[1]) - value = f() - - self.locker.acquire() - self.storage[key] = (now, value) - self.storage[CacheAbstract.cache_stats_name]['misses'] += 1 - self.locker.release() - return value - - def increment(self, key, value=1): - self.initialize() - 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 key value store where each key corresponds to a - single file in disk which is replaced when the value changes. - - Disk cache provides persistance when web2py is started/stopped but it is - slower than `CacheInRam` - - Values stored in disk cache must be pickable. - """ - - class PersistentStorage(object): - """ - Implements a key based storage in disk. - """ - - def __init__(self, folder): - self.folder = folder - self.key_filter_in = lambda key: key - self.key_filter_out = lambda key: key - # Check the best way to do atomic file replacement. - if sys.version_info >= (3, 3): - self.replace = os.replace - elif sys.platform == "win32": - import ctypes - from ctypes import wintypes - ReplaceFile = ctypes.windll.kernel32.ReplaceFileW - ReplaceFile.restype = wintypes.BOOL - ReplaceFile.argtypes = [ - wintypes.LPWSTR, - wintypes.LPWSTR, - wintypes.LPWSTR, - wintypes.DWORD, - wintypes.LPVOID, - wintypes.LPVOID, - ] - - def replace_windows(src, dst): - if not ReplaceFile(dst, src, None, 0, 0, 0): - os.rename(src, dst) - - self.replace = replace_windows - else: - # POSIX rename() is always atomic - self.replace = os.rename - - # Make sure we use valid filenames. - if sys.platform == "win32": - import base64 - def key_filter_in_windows(key): - """ - Windows doesn't allow \ / : * ? "< > | in filenames. - To go around this encode the keys with base32. - """ - return base64.b32encode(key) - - def key_filter_out_windows(key): - """ - We need to decode the keys so regex based removal works. - """ - return base64.b32decode(key) - - self.key_filter_in = key_filter_in_windows - self.key_filter_out = key_filter_out_windows - - - def __setitem__(self, key, value): - tmp_name, tmp_path = tempfile.mkstemp(dir=self.folder) - tmp = os.fdopen(tmp_name, 'wb') - try: - pickle.dump((time.time(), value), tmp, pickle.HIGHEST_PROTOCOL) - finally: - tmp.close() - key = self.key_filter_in(key) - fullfilename = os.path.join(self.folder, recfile.generate(key)) - if not os.path.exists(os.path.dirname(fullfilename)): - os.makedirs(os.path.dirname(fullfilename)) - self.replace(tmp_path, fullfilename) - - - def __getitem__(self, key): - key = self.key_filter_in(key) - if recfile.exists(key, path=self.folder): - timestamp, value = pickle.load(recfile.open(key, 'rb', path=self.folder)) - return value - else: - raise KeyError - - - def __contains__(self, key): - key = self.key_filter_in(key) - return recfile.exists(key, path=self.folder) - - - def __delitem__(self, key): - key = self.key_filter_in(key) - recfile.remove(key, path=self.folder) - - - def __iter__(self): - for dirpath, dirnames, filenames in os.walk(self.folder): - for filename in filenames: - yield self.key_filter_out(filename) - - - def keys(self): - return list(self.__iter__()) - - - def get(self, key, default=None): - try: - return self[key] - except KeyError: - return default - - - def clear(self): - for key in self: - del self[key] - - - def __init__(self, request=None, folder=None): - self.initialized = False - self.request = request - self.folder = folder - self.storage = None - - - def initialize(self): - if self.initialized: - return - else: - self.initialized = True - - folder = self.folder - request = self.request - - # Lets test if the cache folder exists, if not - # we are going to create it - folder = os.path.join(folder or request.folder, 'cache') - - if not os.path.exists(folder): - os.mkdir(folder) - - self.storage = CacheOnDisk.PersistentStorage(folder) - - if not CacheAbstract.cache_stats_name in self.storage: - self.storage[CacheAbstract.cache_stats_name] = {'hit_total': 0, 'misses': 0} - - - def __call__(self, key, f, - time_expire=DEFAULT_TIME_EXPIRE): - self.initialize() - - dt = time_expire - item = self.storage.get(key) - self.storage[CacheAbstract.cache_stats_name]['hit_total'] += 1 - - if item and f is None: - del self.storage[key] - - if f is None: - return None - - now = time.time() - - if item and ((dt is None) or (item[0] > now - dt)): - value = item[1] - else: - value = f() - self.storage[key] = (now, value) - self.storage[CacheAbstract.cache_stats_name]['misses'] += 1 - - return value - - - def clear(self, regex=None): - self.initialize() - storage = self.storage - if regex is None: - storage.clear() - else: - self._clear(storage, regex) - - if not CacheAbstract.cache_stats_name in storage: - storage[CacheAbstract.cache_stats_name] = { - 'hit_total': 0, 'misses': 0} - - - def increment(self, key, value=1): - self.initialize() - storage = self.storage - try: - if key in storage: - value = storage[key][1] + value - storage[key] = (time.time(), value) - except: - pass - return value - - - -class CacheAction(object): - def __init__(self, func, key, time_expire, cache, cache_model): - self.__name__ = func.__name__ - self.__doc__ = func.__doc__ - self.func = func - self.key = key - self.time_expire = time_expire - self.cache = cache - self.cache_model = cache_model - - def __call__(self, *a, **b): - if not self.key: - key2 = self.__name__ + ':' + repr(a) + ':' + repr(b) - else: - key2 = self.key.replace('%(name)s', self.__name__)\ - .replace('%(args)s', str(a)).replace('%(vars)s', str(b)) - cache_model = self.cache_model - if not cache_model or isinstance(cache_model, str): - cache_model = getattr(self.cache, cache_model or 'ram') - return cache_model(key2, - lambda a=a, b=b: self.func(*a, **b), - self.time_expire) - - -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 - """ - - autokey = ':%(name)s:%(args)s:%(vars)s' - - def __init__(self, request): - """ - Args: - request: the global request object - """ - # GAE will have a special caching - if have_settings and settings.global_settings.web2py_runtime_gae: - from gluon.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 action(self, time_expire=DEFAULT_TIME_EXPIRE, cache_model=None, - prefix=None, session=False, vars=True, lang=True, - user_agent=False, public=True, valid_statuses=None, - quick=None): - """Better fit for caching an action - - Warning: - Experimental! - - Currently only HTTP 1.1 compliant - reference : http://code.google.com/p/doctype-mirror/wiki/ArticleHttpCaching - - Args: - time_expire(int): same as @cache - cache_model(str): same as @cache - prefix(str): add a prefix to the calculated key - session(bool): adds response.session_id to the key - vars(bool): adds request.env.query_string - lang(bool): adds T.accepted_language - user_agent(bool or dict): if True, adds is_mobile and is_tablet to the key. - Pass a dict to use all the needed values (uses str(.items())) - (e.g. user_agent=request.user_agent()). Used only if session is - not True - public(bool): if False forces the Cache-Control to be 'private' - valid_statuses: by default only status codes starting with 1,2,3 will be cached. - pass an explicit list of statuses on which turn the cache on - quick: Session,Vars,Lang,User-agent,Public: - fast overrides with initials, e.g. 'SVLP' or 'VLP', or 'VLP' - """ - from gluon import current - from gluon.http import HTTP - def wrap(func): - def wrapped_f(): - if current.request.env.request_method != 'GET': - return func() - if time_expire: - cache_control = 'max-age=%(time_expire)s, s-maxage=%(time_expire)s' % dict(time_expire=time_expire) - if quick: - session_ = True if 'S' in quick else False - vars_ = True if 'V' in quick else False - lang_ = True if 'L' in quick else False - user_agent_ = True if 'U' in quick else False - public_ = True if 'P' in quick else False - else: - session_, vars_, lang_, user_agent_, public_ = session, vars, lang, user_agent, public - if not session_ and public_: - cache_control += ', public' - expires = (current.request.utcnow + datetime.timedelta(seconds=time_expire)).strftime('%a, %d %b %Y %H:%M:%S GMT') - else: - cache_control += ', private' - expires = 'Fri, 01 Jan 1990 00:00:00 GMT' - if cache_model: - #figure out the correct cache key - cache_key = [current.request.env.path_info, current.response.view] - if session_: - cache_key.append(current.response.session_id) - elif user_agent_: - if user_agent_ is True: - cache_key.append("%(is_mobile)s_%(is_tablet)s" % current.request.user_agent()) - else: - cache_key.append(str(user_agent_.items())) - if vars_: - cache_key.append(current.request.env.query_string) - if lang_: - cache_key.append(current.T.accepted_language) - cache_key = hashlib.md5('__'.join(cache_key)).hexdigest() - if prefix: - cache_key = prefix + cache_key - try: - #action returns something - rtn = cache_model(cache_key, lambda : func(), time_expire=time_expire) - http, status = None, current.response.status - except HTTP, e: - #action raises HTTP (can still be valid) - rtn = cache_model(cache_key, lambda : e.body, time_expire=time_expire) - http, status = HTTP(e.status, rtn, **e.headers), e.status - else: - #action raised a generic exception - http = None - else: - #no server-cache side involved - try: - #action returns something - rtn = func() - http, status = None, current.response.status - except HTTP, e: - #action raises HTTP (can still be valid) - status = e.status - http = HTTP(e.status, e.body, **e.headers) - else: - #action raised a generic exception - http = None - send_headers = False - if http and isinstance(valid_statuses, list): - if status in valid_statuses: - send_headers = True - elif valid_statuses is None: - if str(status)[0] in '123': - send_headers = True - if send_headers: - headers = { - 'Pragma' : None, - 'Expires' : expires, - 'Cache-Control' : cache_control - } - current.response.headers.update(headers) - if cache_model and not send_headers: - #we cached already the value, but the status is not valid - #so we need to delete the cached value - cache_model(cache_key, None) - if http: - if send_headers: - http.headers.update(current.response.headers) - raise http - return rtn - wrapped_f.__name__ = func.__name__ - wrapped_f.__doc__ = func.__doc__ - return wrapped_f - return wrap - - def __call__(self, - key=None, - time_expire=DEFAULT_TIME_EXPIRE, - cache_model=None): - """ - Decorator function that can be used to cache any function/method. - - Args: - key(str) : the key of the object to be store or retrieved - time_expire(int) : expiration of the cache in seconds - `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. - cache_model(str): can be "ram", "disk" or other (like "memcache"). - Defaults to "ram" - - When the function `f` is called, web2py tries to retrieve - the value corresponding to `key` from the cache if 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. - - Example: :: - - @cache('key', 5000, cache.ram) - def f(): - return time.ctime() - - Note: - If the function `f` is an action, we suggest using - @cache.action instead - """ - - def tmp(func, cache=self, cache_model=cache_model): - return CacheAction(func, key, time_expire, self, cache_model) - return tmp - - @staticmethod - def with_prefix(cache_model, prefix): - """ - allow replacing cache.ram with cache.with_prefix(cache.ram,'prefix') - it will add prefix to all the cache keys used. - """ - return lambda key, f, time_expire=DEFAULT_TIME_EXPIRE, prefix=prefix:\ - cache_model(prefix + key, f, time_expire) - - -def lazy_cache(key=None, time_expire=None, cache_model='ram'): - """ - Can be used to cache any function including ones in modules, - as long as the cached function is only called within a web2py request - - If a key is not provided, one is generated from the function name - `time_expire` defaults to None (no cache expiration) - - If cache_model is "ram" then the model is current.cache.ram, etc. - """ - def decorator(f, key=key, time_expire=time_expire, cache_model=cache_model): - key = key or repr(f) - - def g(*c, **d): - from gluon import current - return current.cache(key, time_expire, cache_model)(f)(*c, **d) - g.__name__ = f.__name__ - return g - return decorator +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""" +| This file is part of the web2py Web Framework +| Copyrighted by Massimo Di Pierro +| 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 +- CacheOnDisk - 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 thread +import os +import sys +import logging +import re +import hashlib +import datetime +import tempfile +from gluon import recfile +try: + from gluon import settings + have_settings = True +except ImportError: + have_settings = False + +try: + import cPickle as pickle +except: + import pickle + +logger = logging.getLogger("web2py.cache") + +__all__ = ['Cache', 'lazy_cache'] + + +DEFAULT_TIME_EXPIRE = 300 + + + +class CacheAbstract(object): + """ + Abstract class for cache implementations. + Main function just provides referenced api documentation. + + Use CacheInRam or CacheOnDisk instead which are derived from this class. + + Note: + Michele says: there are signatures inside gdbm files that are used + directly by the python gdbm adapter that often are lagging behind in the + detection code in python part. + On every occasion that a gdbm store is probed by the python adapter, + the probe fails, because gdbm file version is newer. + Using gdbm directly from C would work, because there is backward + compatibility, but not from python! + The .shelve file is discarded and a new one created (with new + signature) and it works until it is probed again... + The possible consequences are memory leaks and broken sessions. + """ + + cache_stats_name = 'web2py_cache_statistics' + + def __init__(self, request=None): + """Initializes the object + + Args: + request: the global request object + """ + raise NotImplementedError + + def __call__(self, key, f, + time_expire=DEFAULT_TIME_EXPIRE): + """ + Tries to retrieve the value corresponding to `key` from the cache if the + object exists and if it did not expire, else it calls the function `f` + and stores the output in the cache corresponding to `key`. It always + returns the function that is returned. + + Args: + key(str): the key of the object to be stored or retrieved + f(function): the function whose output is to be cached. + + If `f` is `None` the cache is cleared. + time_expire(int): expiration of the cache in seconds. + + It's 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. + """ + 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. + + Args: + 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 + + Args: + key(str): key for the cached object to be incremeneted + value(int): 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 in storage.keys(): + if r.match(str(key)): + del storage[key] + return + + +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.initialized = False + self.request = request + self.storage = {} + + def initialize(self): + if self.initialized: + return + else: + self.initialized = True + self.locker.acquire() + request = self.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.initialize() + self.locker.acquire() + storage = self.storage + if regex is 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, + destroyer=None): + """ + 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: + + - would break backward compatibility + - would be limiting because people may want to cache live objects + - 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. + """ + self.initialize() + + dt = time_expire + now = time.time() + + self.locker.acquire() + item = self.storage.get(key, None) + if item and f is None: + del self.storage[key] + if destroyer: + destroyer(item[1]) + self.storage[CacheAbstract.cache_stats_name]['hit_total'] += 1 + self.locker.release() + + if f is None: + return None + if item and (dt is None or item[0] > now - dt): + return item[1] + elif item and (item[0] < now - dt) and destroyer: + destroyer(item[1]) + value = f() + + self.locker.acquire() + self.storage[key] = (now, value) + self.storage[CacheAbstract.cache_stats_name]['misses'] += 1 + self.locker.release() + return value + + def increment(self, key, value=1): + self.initialize() + 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 key value store where each key corresponds to a + single file in disk which is replaced when the value changes. + + Disk cache provides persistance when web2py is started/stopped but it is + slower than `CacheInRam` + + Values stored in disk cache must be pickable. + """ + + class PersistentStorage(object): + """ + Implements a key based storage in disk. + """ + + def __init__(self, folder): + self.folder = folder + self.key_filter_in = lambda key: key + self.key_filter_out = lambda key: key + # Check the best way to do atomic file replacement. + if sys.version_info >= (3, 3): + self.replace = os.replace + elif sys.platform == "win32": + import ctypes + from ctypes import wintypes + ReplaceFile = ctypes.windll.kernel32.ReplaceFileW + ReplaceFile.restype = wintypes.BOOL + ReplaceFile.argtypes = [ + wintypes.LPWSTR, + wintypes.LPWSTR, + wintypes.LPWSTR, + wintypes.DWORD, + wintypes.LPVOID, + wintypes.LPVOID, + ] + + def replace_windows(src, dst): + if not ReplaceFile(dst, src, None, 0, 0, 0): + os.rename(src, dst) + + self.replace = replace_windows + else: + # POSIX rename() is always atomic + self.replace = os.rename + + # Make sure we use valid filenames. + if sys.platform == "win32": + import base64 + def key_filter_in_windows(key): + """ + Windows doesn't allow \ / : * ? "< > | in filenames. + To go around this encode the keys with base32. + """ + return base64.b32encode(key) + + def key_filter_out_windows(key): + """ + We need to decode the keys so regex based removal works. + """ + return base64.b32decode(key) + + self.key_filter_in = key_filter_in_windows + self.key_filter_out = key_filter_out_windows + + + def __setitem__(self, key, value): + tmp_name, tmp_path = tempfile.mkstemp(dir=self.folder) + tmp = os.fdopen(tmp_name, 'wb') + try: + pickle.dump((time.time(), value), tmp, pickle.HIGHEST_PROTOCOL) + finally: + tmp.close() + key = self.key_filter_in(key) + fullfilename = os.path.join(self.folder, recfile.generate(key)) + if not os.path.exists(os.path.dirname(fullfilename)): + os.makedirs(os.path.dirname(fullfilename)) + self.replace(tmp_path, fullfilename) + + + def __getitem__(self, key): + key = self.key_filter_in(key) + if recfile.exists(key, path=self.folder): + timestamp, value = pickle.load(recfile.open(key, 'rb', path=self.folder)) + return value + else: + raise KeyError + + + def __contains__(self, key): + key = self.key_filter_in(key) + return recfile.exists(key, path=self.folder) + + + def __delitem__(self, key): + key = self.key_filter_in(key) + recfile.remove(key, path=self.folder) + + + def __iter__(self): + for dirpath, dirnames, filenames in os.walk(self.folder): + for filename in filenames: + yield self.key_filter_out(filename) + + + def keys(self): + return list(self.__iter__()) + + + def get(self, key, default=None): + try: + return self[key] + except KeyError: + return default + + + def clear(self): + for key in self: + del self[key] + + + def __init__(self, request=None, folder=None): + self.initialized = False + self.request = request + self.folder = folder + self.storage = None + + + def initialize(self): + if self.initialized: + return + else: + self.initialized = True + + folder = self.folder + request = self.request + + # Lets test if the cache folder exists, if not + # we are going to create it + folder = os.path.join(folder or request.folder, 'cache') + + if not os.path.exists(folder): + os.mkdir(folder) + + self.storage = CacheOnDisk.PersistentStorage(folder) + + if not CacheAbstract.cache_stats_name in self.storage: + self.storage[CacheAbstract.cache_stats_name] = {'hit_total': 0, 'misses': 0} + + + def __call__(self, key, f, + time_expire=DEFAULT_TIME_EXPIRE): + self.initialize() + + dt = time_expire + item = self.storage.get(key) + self.storage[CacheAbstract.cache_stats_name]['hit_total'] += 1 + + if item and f is None: + del self.storage[key] + + if f is None: + return None + + now = time.time() + + if item and ((dt is None) or (item[0] > now - dt)): + value = item[1] + else: + value = f() + self.storage[key] = (now, value) + self.storage[CacheAbstract.cache_stats_name]['misses'] += 1 + + return value + + + def clear(self, regex=None): + self.initialize() + storage = self.storage + if regex is None: + storage.clear() + else: + self._clear(storage, regex) + + if not CacheAbstract.cache_stats_name in storage: + storage[CacheAbstract.cache_stats_name] = { + 'hit_total': 0, 'misses': 0} + + + def increment(self, key, value=1): + self.initialize() + storage = self.storage + try: + if key in storage: + value = storage[key][1] + value + storage[key] = (time.time(), value) + except: + pass + return value + + + +class CacheAction(object): + def __init__(self, func, key, time_expire, cache, cache_model): + self.__name__ = func.__name__ + self.__doc__ = func.__doc__ + self.func = func + self.key = key + self.time_expire = time_expire + self.cache = cache + self.cache_model = cache_model + + def __call__(self, *a, **b): + if not self.key: + key2 = self.__name__ + ':' + repr(a) + ':' + repr(b) + else: + key2 = self.key.replace('%(name)s', self.__name__)\ + .replace('%(args)s', str(a)).replace('%(vars)s', str(b)) + cache_model = self.cache_model + if not cache_model or isinstance(cache_model, str): + cache_model = getattr(self.cache, cache_model or 'ram') + return cache_model(key2, + lambda a=a, b=b: self.func(*a, **b), + self.time_expire) + + +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 + """ + + autokey = ':%(name)s:%(args)s:%(vars)s' + + def __init__(self, request): + """ + Args: + request: the global request object + """ + # GAE will have a special caching + if have_settings and settings.global_settings.web2py_runtime_gae: + from gluon.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 action(self, time_expire=DEFAULT_TIME_EXPIRE, cache_model=None, + prefix=None, session=False, vars=True, lang=True, + user_agent=False, public=True, valid_statuses=None, + quick=None): + """Better fit for caching an action + + Warning: + Experimental! + + Currently only HTTP 1.1 compliant + reference : http://code.google.com/p/doctype-mirror/wiki/ArticleHttpCaching + + Args: + time_expire(int): same as @cache + cache_model(str): same as @cache + prefix(str): add a prefix to the calculated key + session(bool): adds response.session_id to the key + vars(bool): adds request.env.query_string + lang(bool): adds T.accepted_language + user_agent(bool or dict): if True, adds is_mobile and is_tablet to the key. + Pass a dict to use all the needed values (uses str(.items())) + (e.g. user_agent=request.user_agent()). Used only if session is + not True + public(bool): if False forces the Cache-Control to be 'private' + valid_statuses: by default only status codes starting with 1,2,3 will be cached. + pass an explicit list of statuses on which turn the cache on + quick: Session,Vars,Lang,User-agent,Public: + fast overrides with initials, e.g. 'SVLP' or 'VLP', or 'VLP' + """ + from gluon import current + from gluon.http import HTTP + def wrap(func): + def wrapped_f(): + if current.request.env.request_method != 'GET': + return func() + if time_expire: + cache_control = 'max-age=%(time_expire)s, s-maxage=%(time_expire)s' % dict(time_expire=time_expire) + if quick: + session_ = True if 'S' in quick else False + vars_ = True if 'V' in quick else False + lang_ = True if 'L' in quick else False + user_agent_ = True if 'U' in quick else False + public_ = True if 'P' in quick else False + else: + session_, vars_, lang_, user_agent_, public_ = session, vars, lang, user_agent, public + if not session_ and public_: + cache_control += ', public' + expires = (current.request.utcnow + datetime.timedelta(seconds=time_expire)).strftime('%a, %d %b %Y %H:%M:%S GMT') + else: + cache_control += ', private' + expires = 'Fri, 01 Jan 1990 00:00:00 GMT' + if cache_model: + #figure out the correct cache key + cache_key = [current.request.env.path_info, current.response.view] + if session_: + cache_key.append(current.response.session_id) + elif user_agent_: + if user_agent_ is True: + cache_key.append("%(is_mobile)s_%(is_tablet)s" % current.request.user_agent()) + else: + cache_key.append(str(user_agent_.items())) + if vars_: + cache_key.append(current.request.env.query_string) + if lang_: + cache_key.append(current.T.accepted_language) + cache_key = hashlib.md5('__'.join(cache_key)).hexdigest() + if prefix: + cache_key = prefix + cache_key + try: + #action returns something + rtn = cache_model(cache_key, lambda : func(), time_expire=time_expire) + http, status = None, current.response.status + except HTTP, e: + #action raises HTTP (can still be valid) + rtn = cache_model(cache_key, lambda : e.body, time_expire=time_expire) + http, status = HTTP(e.status, rtn, **e.headers), e.status + else: + #action raised a generic exception + http = None + else: + #no server-cache side involved + try: + #action returns something + rtn = func() + http, status = None, current.response.status + except HTTP, e: + #action raises HTTP (can still be valid) + status = e.status + http = HTTP(e.status, e.body, **e.headers) + else: + #action raised a generic exception + http = None + send_headers = False + if http and isinstance(valid_statuses, list): + if status in valid_statuses: + send_headers = True + elif valid_statuses is None: + if str(status)[0] in '123': + send_headers = True + if send_headers: + headers = { + 'Pragma' : None, + 'Expires' : expires, + 'Cache-Control' : cache_control + } + current.response.headers.update(headers) + if cache_model and not send_headers: + #we cached already the value, but the status is not valid + #so we need to delete the cached value + cache_model(cache_key, None) + if http: + if send_headers: + http.headers.update(current.response.headers) + raise http + return rtn + wrapped_f.__name__ = func.__name__ + wrapped_f.__doc__ = func.__doc__ + return wrapped_f + return wrap + + def __call__(self, + key=None, + time_expire=DEFAULT_TIME_EXPIRE, + cache_model=None): + """ + Decorator function that can be used to cache any function/method. + + Args: + key(str) : the key of the object to be store or retrieved + time_expire(int) : expiration of the cache in seconds + `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. + cache_model(str): can be "ram", "disk" or other (like "memcache"). + Defaults to "ram" + + When the function `f` is called, web2py tries to retrieve + the value corresponding to `key` from the cache if 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. + + Example: :: + + @cache('key', 5000, cache.ram) + def f(): + return time.ctime() + + Note: + If the function `f` is an action, we suggest using + @cache.action instead + """ + + def tmp(func, cache=self, cache_model=cache_model): + return CacheAction(func, key, time_expire, self, cache_model) + return tmp + + @staticmethod + def with_prefix(cache_model, prefix): + """ + allow replacing cache.ram with cache.with_prefix(cache.ram,'prefix') + it will add prefix to all the cache keys used. + """ + return lambda key, f, time_expire=DEFAULT_TIME_EXPIRE, prefix=prefix:\ + cache_model(prefix + key, f, time_expire) + + +def lazy_cache(key=None, time_expire=None, cache_model='ram'): + """ + Can be used to cache any function including ones in modules, + as long as the cached function is only called within a web2py request + + If a key is not provided, one is generated from the function name + `time_expire` defaults to None (no cache expiration) + + If cache_model is "ram" then the model is current.cache.ram, etc. + """ + def decorator(f, key=key, time_expire=time_expire, cache_model=cache_model): + key = key or repr(f) + + def g(*c, **d): + from gluon import current + return current.cache(key, time_expire, cache_model)(f)(*c, **d) + g.__name__ = f.__name__ + return g + return decorator diff --git a/gluon/compileapp.py b/gluon/compileapp.py index 9ada3cfb..d04fd0d6 100644 --- a/gluon/compileapp.py +++ b/gluon/compileapp.py @@ -407,7 +407,7 @@ def build_environment(request, response, session, store_current=True): # Enable standard conditional models (i.e., /*.py, /[controller]/*.py, and # /[controller]/[function]/*.py) response.models_to_run = [ - r'^\w+\.py$', + r'^\w+\.py$', r'^%s/\w+\.py$' % request.controller, r'^%s/%s/\w+\.py$' % (request.controller, request.function) ] @@ -514,7 +514,7 @@ def compile_controllers(folder): for function in exposed: command = data + "\nresponse._vars=response._caller(%s)\n" % \ function - filename = pjoin(folder, 'compiled', + filename = pjoin(folder, 'compiled', 'controllers.%s.%s.py' % (fname[:-3],function)) write_file(filename, command) save_pyc(filename) diff --git a/gluon/contrib/hypermedia.py b/gluon/contrib/hypermedia.py index 50494516..86926e6f 100644 --- a/gluon/contrib/hypermedia.py +++ b/gluon/contrib/hypermedia.py @@ -47,7 +47,7 @@ class Collection(object): if self.compact: for fieldname in (self.table_policy.get('fields',table.fields)): field = table[fieldname] - if not ((field.type=='text' and text==False) or + if not ((field.type=='text' and text==False) or field.type=='blob' or field.type.startswith('reference ') or field.type.startswith('list:reference ')) and field.name in row: @@ -56,7 +56,7 @@ class Collection(object): for fieldname in (self.table_policy.get('fields',table.fields)): field = table[fieldname] if not ((field.type=='text' and text==False) or - field.type=='blob' or + field.type=='blob' or field.type.startswith('reference ') or field.type.startswith('list:reference ')) and field.name in row: data.append({'name':field.name,'value':row[field.name], @@ -128,10 +128,10 @@ class Collection(object): for key,value in vars.items(): if key=='_offset': limitby[0] = int(value) # MAY FAIL - elif key == '_limit': + elif key == '_limit': limitby[1] = int(value)+1 # MAY FAIL elif key=='_orderby': - orderby = value + orderby = value elif key in fieldnames: queries.append(table[key] == value) elif key.endswith('.eq') and key[:-3] in fieldnames: # for completeness (useless) @@ -156,14 +156,14 @@ class Collection(object): if filter_query: queries.append(filter_query) query = reduce(lambda a,b:a&b,queries[1:]) if len(queries)>1 else queries[0] - orderby = [table[f] if f[0]!='~' else ~table[f[1:]] for f in orderby.split(',')] + orderby = [table[f] if f[0]!='~' else ~table[f[1:]] for f in orderby.split(',')] return (query, limitby, orderby) def table2queries(self,table, href): """ generates a set of collection.queries examples for the table """ data = [] for fieldname in (self.table_policy.get('fields', table.fields)): - data.append({'name':fieldname,'value':''}) + data.append({'name':fieldname,'value':''}) if self.extensions: data.append({'name':fieldname+'.ne','value':''}) # NEW !!! data.append({'name':fieldname+'.lt','value':''}) @@ -192,7 +192,7 @@ class Collection(object): if not tablename: r['href'] = URL(scheme=True), # https://github.com/collection-json/extensions/blob/master/model.md - r['links'] = [{'rel' : t, 'href' : URL(args=t,scheme=True), 'model':t} + r['links'] = [{'rel' : t, 'href' : URL(args=t,scheme=True), 'model':t} for t in tablenames] response.headers['Content-Type'] = 'application/vnd.collection+json' return response.json({'collection':r}) @@ -207,7 +207,7 @@ class Collection(object): # process GET if request.env.request_method=='GET': table = db[tablename] - r['href'] = URL(args=tablename) + r['href'] = URL(args=tablename) r['items'] = items = [] try: (query, limitby, orderby) = self.request2query(table,request.get_vars) @@ -258,7 +258,7 @@ class Collection(object): return response.json({'collection':r}) # process DELETE elif request.env.request_method=='DELETE': - table = db[tablename] + table = db[tablename] if not request.get_vars: return self.error(400, "BAD REQUEST", "Nothing to delete") else: @@ -312,7 +312,7 @@ class Collection(object): request, response = self.request, self.response r = OrderedDict({ "version" : self.VERSION, - "href" : URL(args=request.args,vars=request.vars), + "href" : URL(args=request.args,vars=request.vars), "error" : { "title" : title, "code" : code, @@ -340,4 +340,3 @@ example_policies = { 'DELETE':{'query':None}, }, } - diff --git a/gluon/contrib/memdb.py b/gluon/contrib/memdb.py index 6ad9b159..e4b56ef7 100644 --- a/gluon/contrib/memdb.py +++ b/gluon/contrib/memdb.py @@ -254,12 +254,12 @@ class Table(DALStorage): self._db(self.id > 0).delete() - def insert(self, **fields): - # Checks 3 times that the id is new. 3 times is enough! - for i in range(3): - id = self._create_id() - if self.get(id) is None and self.update(id, **fields): - return long(id) + def insert(self, **fields): + # Checks 3 times that the id is new. 3 times is enough! + for i in range(3): + id = self._create_id() + if self.get(id) is None and self.update(id, **fields): + return long(id) else: raise RuntimeError("Too many ID conflicts") diff --git a/gluon/contrib/mockimaplib.py b/gluon/contrib/mockimaplib.py index 87f8b479..89975900 100644 --- a/gluon/contrib/mockimaplib.py +++ b/gluon/contrib/mockimaplib.py @@ -141,7 +141,7 @@ class Connection(object): parts = "complete" return ("OK", (("%s " % message_id, message[parts]), message["flags"])) - + def _get_messages(self, query): if query.strip().isdigit(): return [self.spam[self._mailbox][int(query.strip()) - 1],] @@ -151,7 +151,7 @@ class Connection(object): for item in self.spam[self._mailbox]: if item["uid"] == query[1:-1].replace("UID", "").strip(): return [item,] - messages = [] + messages = [] try: for m in self.results[self._mailbox][query]: try: @@ -169,7 +169,7 @@ class Connection(object): return messages except KeyError: raise ValueError("The client issued an unexpected query: %s" % query) - + def setup(self, spam={}, results={}): """adds custom message and query databases or sets the values to the module defaults. @@ -252,4 +252,3 @@ class IMAP4(object): return Connection() IMAP4_SSL = IMAP4 - diff --git a/gluon/contrib/pbkdf2_ctypes.py b/gluon/contrib/pbkdf2_ctypes.py index 685ab5d1..6aa62343 100644 --- a/gluon/contrib/pbkdf2_ctypes.py +++ b/gluon/contrib/pbkdf2_ctypes.py @@ -11,7 +11,7 @@ Note: This module is intended as a plugin replacement of pbkdf2.py by Armin Ronacher. - Git repository: + Git repository: $ git clone https://github.com/michele-comitini/pbkdf2_ctypes.git :copyright: Copyright (c) 2013: Michele Comitini @@ -86,7 +86,7 @@ def _openssl_hashlib_to_crypto_map_get(hashfunc): crypto_hashfunc.restype = ctypes.c_void_p return crypto_hashfunc() - + def _openssl_pbkdf2(data, salt, iterations, digest, keylen): """OpenSSL compatibile wrapper """ @@ -99,7 +99,7 @@ def _openssl_pbkdf2(data, salt, iterations, digest, keylen): c_iter = ctypes.c_int(iterations) c_keylen = ctypes.c_int(keylen) c_buff = ctypes.create_string_buffer(keylen) - + # PKCS5_PBKDF2_HMAC(const char *pass, int passlen, # const unsigned char *salt, int saltlen, int iter, # const EVP_MD *digest, @@ -109,7 +109,7 @@ def _openssl_pbkdf2(data, salt, iterations, digest, keylen): ctypes.c_char_p, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_char_p] - + crypto.PKCS5_PBKDF2_HMAC.restype = ctypes.c_int err = crypto.PKCS5_PBKDF2_HMAC(c_pass, c_passlen, c_salt, c_saltlen, diff --git a/gluon/contrib/pypyodbc.py b/gluon/contrib/pypyodbc.py index 7d359ccb..bb2a9ceb 100644 --- a/gluon/contrib/pypyodbc.py +++ b/gluon/contrib/pypyodbc.py @@ -7,18 +7,18 @@ # Copyright (c) 2014 Henry Zhou and PyPyODBC contributors # Copyright (c) 2004 Michele Petrazzo -# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated +# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated # documentation files (the "Software"), to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, subject to the following conditions: # -# The above copyright notice and this permission notice shall be included in all copies or substantial portions +# The above copyright notice and this permission notice shall be included in all copies or substantial portions # of the Software. # -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO -# THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF -# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO +# THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF +# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. pooling = True @@ -52,7 +52,7 @@ else: use_unicode = False if py_ver < '2.6': bytearray = str - + if not hasattr(ctypes, 'c_ssize_t'): if ctypes.sizeof(ctypes.c_uint) == ctypes.sizeof(ctypes.c_void_p): @@ -69,7 +69,7 @@ SQLWCHAR_SIZE = ctypes.sizeof(ctypes.c_wchar) #determin the size of Py_UNICODE #sys.maxunicode > 65536 and 'UCS4' or 'UCS2' -UNICODE_SIZE = sys.maxunicode > 65536 and 4 or 2 +UNICODE_SIZE = sys.maxunicode > 65536 and 4 or 2 # Define ODBC constants. They are widly used in ODBC documents and programs @@ -402,15 +402,15 @@ class OperationalError(DatabaseError): self.value = (error_code, error_desc) self.args = (error_code, error_desc) - - - -############################################################################ + + + +############################################################################ # # Find the ODBC library on the platform and connect to it using ctypes # ############################################################################ -# Get the References of the platform's ODBC functions via ctypes +# Get the References of the platform's ODBC functions via ctypes odbc_decoding = 'utf_16' odbc_encoding = 'utf_16_le' @@ -421,7 +421,7 @@ if sys.platform in ('win32','cli'): # On Windows, the size of SQLWCHAR is hardcoded to 2-bytes. SQLWCHAR_SIZE = ctypes.sizeof(ctypes.c_ushort) else: - # Set load the library on linux + # Set load the library on linux try: # First try direct loading libodbc.so ODBC_API = ctypes.cdll.LoadLibrary('libodbc.so') @@ -446,7 +446,7 @@ else: except: # If still fail loading, abort. raise OdbcLibraryError('Error while loading ' + library) - + # only iODBC uses utf-32 / UCS4 encoding data, others normally use utf-16 / UCS2 # So we set those for handling. if 'libiodbc.dylib' in library: @@ -506,17 +506,17 @@ if sys.platform not in ('win32','cli'): raise OdbcLibraryError('Using narrow Python build with ODBC library ' 'expecting wide unicode is not supported.') - - - - - - - - - - - + + + + + + + + + + + ############################################################ # Database value to Python data type mappings @@ -551,11 +551,11 @@ SQL_C_DOUBLE = SQL_DOUBLE = 8 SQL_C_TYPE_DATE = SQL_TYPE_DATE = 91 SQL_C_TYPE_TIME = SQL_TYPE_TIME = 92 SQL_C_BINARY = SQL_BINARY = -2 -SQL_C_SBIGINT = SQL_BIGINT + SQL_SIGNED_OFFSET +SQL_C_SBIGINT = SQL_BIGINT + SQL_SIGNED_OFFSET SQL_C_TINYINT = SQL_TINYINT = -6 SQL_C_BIT = SQL_BIT = -7 SQL_C_WCHAR = SQL_WCHAR = -8 -SQL_C_GUID = SQL_GUID = -11 +SQL_C_GUID = SQL_GUID = -11 SQL_C_TYPE_TIMESTAMP = SQL_TYPE_TIMESTAMP = 93 SQL_C_DEFAULT = 99 @@ -581,19 +581,19 @@ def dt_cvt(x): def Decimal_cvt(x): if py_v3: - x = x.decode('ascii') + x = x.decode('ascii') return Decimal(x) - + bytearray_cvt = bytearray if sys.platform == 'cli': bytearray_cvt = lambda x: bytearray(buffer(x)) - + # Below Datatype mappings referenced the document at # http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.help.sdk_12.5.1.aseodbc/html/aseodbc/CACFDIGH.htm SQL_data_type_dict = { \ #SQL Data TYPE 0.Python Data Type 1.Default Output Converter 2.Buffer Type 3.Buffer Allocator 4.Default Size 5.Variable Length -SQL_TYPE_NULL : (None, lambda x: None, SQL_C_CHAR, create_buffer, 2 , False ), +SQL_TYPE_NULL : (None, lambda x: None, SQL_C_CHAR, create_buffer, 2 , False ), SQL_CHAR : (str, lambda x: x, SQL_C_CHAR, create_buffer, 2048 , False ), SQL_NUMERIC : (Decimal, Decimal_cvt, SQL_C_CHAR, create_buffer, 150 , False ), SQL_DECIMAL : (Decimal, Decimal_cvt, SQL_C_CHAR, create_buffer, 150 , False ), @@ -620,8 +620,8 @@ SQL_GUID : (str, str, SQL_C_CH SQL_WLONGVARCHAR : (unicode, lambda x: x, SQL_C_WCHAR, create_buffer_u, 20500 , True ), SQL_TYPE_DATE : (datetime.date, dt_cvt, SQL_C_CHAR, create_buffer, 30 , False ), SQL_TYPE_TIME : (datetime.time, tm_cvt, SQL_C_CHAR, create_buffer, 20 , False ), -SQL_TYPE_TIMESTAMP : (datetime.datetime, dttm_cvt, SQL_C_CHAR, create_buffer, 30 , False ), -SQL_SS_VARIANT : (str, lambda x: x, SQL_C_CHAR, create_buffer, 2048 , True ), +SQL_TYPE_TIMESTAMP : (datetime.datetime, dttm_cvt, SQL_C_CHAR, create_buffer, 30 , False ), +SQL_SS_VARIANT : (str, lambda x: x, SQL_C_CHAR, create_buffer, 2048 , True ), SQL_SS_XML : (unicode, lambda x: x, SQL_C_WCHAR, create_buffer_u, 20500 , True ), SQL_SS_UDT : (bytearray, bytearray_cvt, SQL_C_BINARY, create_buffer, 5120 , True ), } @@ -744,7 +744,7 @@ if sys.platform not in ('cli'): ODBC_API.SQLDrivers.argtypes = [ ctypes.c_void_p, ctypes.c_ushort, - ctypes.c_char_p, ctypes.c_short, ctypes.POINTER(ctypes.c_short), + ctypes.c_char_p, ctypes.c_short, ctypes.POINTER(ctypes.c_short), ctypes.c_char_p, ctypes.c_short, ctypes.POINTER(ctypes.c_short), ] @@ -920,7 +920,7 @@ BLANK_BYTE = str_8b() def ctrl_err(ht, h, val_ret, ansi): """Classify type of ODBC error from (type of handle, handle, return value) , and raise with a list""" - + if ansi: state = create_buffer(22) Message = create_buffer(1024*4) @@ -938,7 +938,7 @@ def ctrl_err(ht, h, val_ret, ansi): Buffer_len = c_short() err_list = [] number_errors = 1 - + while 1: ret = ODBC_func(ht, h, number_errors, state, \ ADDR(NativeError), Message, 1024, ADDR(Buffer_len)) @@ -985,19 +985,19 @@ def check_success(ODBC_obj, ret): ctrl_err(SQL_HANDLE_DBC, ODBC_obj.dbc_h, ret, ODBC_obj.ansi) else: ctrl_err(SQL_HANDLE_ENV, ODBC_obj, ret, False) - - + + def AllocateEnv(): if pooling: ret = ODBC_API.SQLSetEnvAttr(SQL_NULL_HANDLE, SQL_ATTR_CONNECTION_POOLING, SQL_CP_ONE_PER_HENV, SQL_IS_UINTEGER) check_success(SQL_NULL_HANDLE, ret) - ''' + ''' Allocate an ODBC environment by initializing the handle shared_env_h ODBC enviroment needed to be created, so connections can be created under it connections pooling can be shared under one environment ''' - global shared_env_h + global shared_env_h shared_env_h = ctypes.c_void_p() ret = ODBC_API.SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, ADDR(shared_env_h)) check_success(shared_env_h, ret) @@ -1005,7 +1005,7 @@ def AllocateEnv(): # Set the ODBC environment's compatibil leve to ODBC 3.0 ret = ODBC_API.SQLSetEnvAttr(shared_env_h, SQL_ATTR_ODBC_VERSION, SQL_OV_ODBC3, 0) check_success(shared_env_h, ret) - + """ Here, we have a few callables that determine how a result row is returned. @@ -1022,20 +1022,20 @@ def TupleRow(cursor): """ class Row(tuple): cursor_description = cursor.description - + def get(self, field): if not hasattr(self, 'field_dict'): self.field_dict = {} for i,item in enumerate(self): self.field_dict[self.cursor_description[i][0]] = item return self.field_dict.get(field) - + def __getitem__(self, field): if isinstance(field, (unicode,str)): return self.get(field) else: return tuple.__getitem__(self,field) - + return Row @@ -1088,19 +1088,19 @@ def MutableNamedTupleRow(cursor): return Row # When Null is used in a binary parameter, database usually would not -# accept the None for a binary field, so the work around is to use a +# accept the None for a binary field, so the work around is to use a # Specical None that the pypyodbc moudle would know this NULL is for # a binary field. class BinaryNullType(): pass BinaryNull = BinaryNullType() -# The get_type function is used to determine if parameters need to be re-binded +# The get_type function is used to determine if parameters need to be re-binded # against the changed parameter types # 'b' for bool, 'U' for long unicode string, 'u' for short unicode string # 'S' for long 8 bit string, 's' for short 8 bit string, 'l' for big integer, 'i' for normal integer # 'f' for float, 'D' for Decimal, 't' for datetime.time, 'd' for datetime.datetime, 'dt' for datetime.datetime # 'bi' for binary -def get_type(v): +def get_type(v): if isinstance(v, bool): return ('b',) @@ -1130,7 +1130,7 @@ def get_type(v): t = v.as_tuple() #1.23 -> (1,2,3),-2 , 1.23*E7 -> (1,2,3),5 return ('D',(len(t[1]),0 - t[2])) # number of digits, and number of decimal digits - + elif isinstance (v, datetime.datetime): return ('dt',) elif isinstance (v, datetime.date): @@ -1139,7 +1139,7 @@ def get_type(v): return ('t',) elif isinstance (v, (bytearray, buffer)): return ('bi',(len(v)//1000+1)*1000) - + return type(v) @@ -1169,16 +1169,16 @@ class Cursor: ret = ODBC_API.SQLAllocHandle(SQL_HANDLE_STMT, self.connection.dbc_h, ADDR(self.stmt_h)) check_success(self, ret) self._PARAM_SQL_TYPE_LIST = [] - self.closed = False + self.closed = False + - def prepare(self, query_string): """prepare a query""" - + #self._free_results(FREE_STATEMENT) if not self.connection: self.close() - + if type(query_string) == unicode: c_query_string = wchar_pointer(UCS_buf(query_string)) ret = ODBC_API.SQLPrepareW(self.stmt_h, c_query_string, len(query_string)) @@ -1187,10 +1187,10 @@ class Cursor: ret = ODBC_API.SQLPrepare(self.stmt_h, c_query_string, len(query_string)) if ret != SQL_SUCCESS: check_success(self, ret) - - - self._PARAM_SQL_TYPE_LIST = [] - + + + self._PARAM_SQL_TYPE_LIST = [] + if self.connection.support_SQLDescribeParam: # SQLServer's SQLDescribeParam only supports DML SQL, so avoid the SELECT statement if True:# 'SELECT' not in query_string.upper(): @@ -1199,7 +1199,7 @@ class Cursor: ret = ODBC_API.SQLNumParams(self.stmt_h, ADDR(NumParams)) if ret != SQL_SUCCESS: check_success(self, ret) - + for col_num in range(NumParams.value): ParameterNumber = ctypes.c_ushort(col_num + 1) DataType = c_short() @@ -1219,7 +1219,7 @@ class Cursor: check_success(self, ret) except DatabaseError: if sys.exc_info()[1].value[0] == '07009': - self._PARAM_SQL_TYPE_LIST = [] + self._PARAM_SQL_TYPE_LIST = [] break else: raise sys.exc_info()[1] @@ -1227,7 +1227,7 @@ class Cursor: raise sys.exc_info()[1] self._PARAM_SQL_TYPE_LIST.append((DataType.value,DecimalDigits.value)) - + self.statement = query_string @@ -1237,39 +1237,39 @@ class Cursor: if not self.connection: self.close() #self._free_results(NO_FREE_STATEMENT) - + # Get the number of query parameters judged by database. NumParams = c_short() ret = ODBC_API.SQLNumParams(self.stmt_h, ADDR(NumParams)) if ret != SQL_SUCCESS: check_success(self, ret) - + if len(param_types) != NumParams.value: # In case number of parameters provided do not same as number required error_desc = "The SQL contains %d parameter markers, but %d parameters were supplied" \ %(NumParams.value,len(param_types)) raise ProgrammingError('HY000',error_desc) - - + + # Every parameter needs to be binded to a buffer ParamBufferList = [] # Temporary holder since we can only call SQLDescribeParam before # calling SQLBindParam. temp_holder = [] for col_num in range(NumParams.value): - dec_num = 0 + dec_num = 0 buf_size = 512 - + if param_types[col_num][0] == 'u': sql_c_type = SQL_C_WCHAR - sql_type = SQL_WVARCHAR - buf_size = 255 - ParameterBuffer = create_buffer_u(buf_size) - + sql_type = SQL_WVARCHAR + buf_size = 255 + ParameterBuffer = create_buffer_u(buf_size) + elif param_types[col_num][0] == 's': sql_c_type = SQL_C_CHAR sql_type = SQL_VARCHAR - buf_size = 255 + buf_size = 255 ParameterBuffer = create_buffer(buf_size) @@ -1284,26 +1284,26 @@ class Cursor: sql_type = SQL_LONGVARCHAR buf_size = param_types[col_num][1]#len(self._inputsizers)>col_num and self._inputsizers[col_num] or 20500 ParameterBuffer = create_buffer(buf_size) - + # bool subclasses int, thus has to go first elif param_types[col_num][0] == 'b': sql_c_type = SQL_C_CHAR sql_type = SQL_BIT buf_size = SQL_data_type_dict[sql_type][4] ParameterBuffer = create_buffer(buf_size) - + elif param_types[col_num][0] == 'i': - sql_c_type = SQL_C_CHAR - sql_type = SQL_INTEGER - buf_size = SQL_data_type_dict[sql_type][4] - ParameterBuffer = create_buffer(buf_size) - - elif param_types[col_num][0] == 'l': - sql_c_type = SQL_C_CHAR - sql_type = SQL_BIGINT - buf_size = SQL_data_type_dict[sql_type][4] + sql_c_type = SQL_C_CHAR + sql_type = SQL_INTEGER + buf_size = SQL_data_type_dict[sql_type][4] ParameterBuffer = create_buffer(buf_size) - + + elif param_types[col_num][0] == 'l': + sql_c_type = SQL_C_CHAR + sql_type = SQL_BIGINT + buf_size = SQL_data_type_dict[sql_type][4] + ParameterBuffer = create_buffer(buf_size) + elif param_types[col_num][0] == 'D': #Decimal sql_c_type = SQL_C_CHAR @@ -1311,56 +1311,56 @@ class Cursor: digit_num, dec_num = param_types[col_num][1] if dec_num > 0: # has decimal - buf_size = digit_num + buf_size = digit_num dec_num = dec_num else: # no decimal - buf_size = digit_num - dec_num + buf_size = digit_num - dec_num dec_num = 0 ParameterBuffer = create_buffer(buf_size + 4)# add extra length for sign and dot - + elif param_types[col_num][0] == 'f': sql_c_type = SQL_C_CHAR - sql_type = SQL_DOUBLE + sql_type = SQL_DOUBLE buf_size = SQL_data_type_dict[sql_type][4] ParameterBuffer = create_buffer(buf_size) - - + + # datetime subclasses date, thus has to go first elif param_types[col_num][0] == 'dt': sql_c_type = SQL_C_CHAR sql_type = SQL_TYPE_TIMESTAMP - buf_size = self.connection.type_size_dic[SQL_TYPE_TIMESTAMP][0] + buf_size = self.connection.type_size_dic[SQL_TYPE_TIMESTAMP][0] ParameterBuffer = create_buffer(buf_size) dec_num = self.connection.type_size_dic[SQL_TYPE_TIMESTAMP][1] - - + + elif param_types[col_num][0] == 'd': sql_c_type = SQL_C_CHAR if SQL_TYPE_DATE in self.connection.type_size_dic: #if DEBUG:print('conx.type_size_dic.has_key(SQL_TYPE_DATE)') sql_type = SQL_TYPE_DATE buf_size = self.connection.type_size_dic[SQL_TYPE_DATE][0] - + ParameterBuffer = create_buffer(buf_size) dec_num = self.connection.type_size_dic[SQL_TYPE_DATE][1] - + else: # SQL Sever <2008 doesn't have a DATE type. - sql_type = SQL_TYPE_TIMESTAMP - buf_size = 10 + sql_type = SQL_TYPE_TIMESTAMP + buf_size = 10 ParameterBuffer = create_buffer(buf_size) - - + + elif param_types[col_num][0] == 't': sql_c_type = SQL_C_CHAR if SQL_TYPE_TIME in self.connection.type_size_dic: sql_type = SQL_TYPE_TIME - buf_size = self.connection.type_size_dic[SQL_TYPE_TIME][0] + buf_size = self.connection.type_size_dic[SQL_TYPE_TIME][0] ParameterBuffer = create_buffer(buf_size) - dec_num = self.connection.type_size_dic[SQL_TYPE_TIME][1] + dec_num = self.connection.type_size_dic[SQL_TYPE_TIME][1] elif SQL_SS_TIME2 in self.connection.type_size_dic: # TIME type added in SQL Server 2008 sql_type = SQL_SS_TIME2 @@ -1370,16 +1370,16 @@ class Cursor: else: # SQL Sever <2008 doesn't have a TIME type. sql_type = SQL_TYPE_TIMESTAMP - buf_size = self.connection.type_size_dic[SQL_TYPE_TIMESTAMP][0] + buf_size = self.connection.type_size_dic[SQL_TYPE_TIMESTAMP][0] ParameterBuffer = create_buffer(buf_size) dec_num = 3 - + elif param_types[col_num][0] == 'BN': sql_c_type = SQL_C_BINARY - sql_type = SQL_VARBINARY - buf_size = 1 - ParameterBuffer = create_buffer(buf_size) - + sql_type = SQL_VARBINARY + buf_size = 1 + ParameterBuffer = create_buffer(buf_size) + elif param_types[col_num][0] == 'N': if len(self._PARAM_SQL_TYPE_LIST) > 0: sql_c_type = SQL_C_DEFAULT @@ -1389,64 +1389,64 @@ class Cursor: else: sql_c_type = SQL_C_CHAR sql_type = SQL_CHAR - buf_size = 1 - ParameterBuffer = create_buffer(buf_size) + buf_size = 1 + ParameterBuffer = create_buffer(buf_size) elif param_types[col_num][0] == 'bi': sql_c_type = SQL_C_BINARY - sql_type = SQL_LONGVARBINARY - buf_size = param_types[col_num][1]#len(self._inputsizers)>col_num and self._inputsizers[col_num] or 20500 + sql_type = SQL_LONGVARBINARY + buf_size = param_types[col_num][1]#len(self._inputsizers)>col_num and self._inputsizers[col_num] or 20500 ParameterBuffer = create_buffer(buf_size) - - + + else: sql_c_type = SQL_C_CHAR sql_type = SQL_LONGVARCHAR - buf_size = len(self._inputsizers)>col_num and self._inputsizers[col_num] or 20500 + buf_size = len(self._inputsizers)>col_num and self._inputsizers[col_num] or 20500 ParameterBuffer = create_buffer(buf_size) - + temp_holder.append((sql_c_type, sql_type, buf_size, dec_num, ParameterBuffer)) for col_num, (sql_c_type, sql_type, buf_size, dec_num, ParameterBuffer) in enumerate(temp_holder): BufferLen = c_ssize_t(buf_size) LenOrIndBuf = c_ssize_t() - - + + InputOutputType = SQL_PARAM_INPUT if len(pram_io_list) > col_num: InputOutputType = pram_io_list[col_num] ret = SQLBindParameter(self.stmt_h, col_num + 1, InputOutputType, sql_c_type, sql_type, buf_size,\ dec_num, ADDR(ParameterBuffer), BufferLen,ADDR(LenOrIndBuf)) - if ret != SQL_SUCCESS: + if ret != SQL_SUCCESS: check_success(self, ret) # Append the value buffer and the length buffer to the array ParamBufferList.append((ParameterBuffer,LenOrIndBuf,sql_type)) - + self._last_param_types = param_types self._ParamBufferList = ParamBufferList - + def execute(self, query_string, params=None, many_mode=False, call_mode=False): """ Execute the query string, with optional parameters. If parameters are provided, the query would first be prepared, then executed with parameters; - If parameters are not provided, only th query sting, it would be executed directly + If parameters are not provided, only th query sting, it would be executed directly """ if not self.connection: self.close() - + self._free_stmt(SQL_CLOSE) if params: # If parameters exist, first prepare the query then executed with parameters - + if not isinstance(params, (tuple, list)): raise TypeError("Params must be in a list, tuple, or Row") - + if query_string != self.statement: - # if the query is not same as last query, then it is not prepared + # if the query is not same as last query, then it is not prepared self.prepare(query_string) - - + + param_types = list(map(get_type, params)) if call_mode: @@ -1462,8 +1462,8 @@ class Cursor: elif sum([p_type[0] != 'N' and p_type != self._last_param_types[i] for i,p_type in enumerate(param_types)]) > 0: self._free_stmt(SQL_RESET_PARAMS) self._BindParams(param_types) - - + + # With query prepared, now put parameters into buffers col_num = 0 for param_buffer, param_buffer_len, sql_type in self._ParamBufferList: @@ -1479,24 +1479,24 @@ class Cursor: else: c_char_buf = str(param_val) c_buf_len = len(c_char_buf) - + elif param_types[col_num][0] in ('s','S'): c_char_buf = param_val c_buf_len = len(c_char_buf) elif param_types[col_num][0] in ('u','U'): c_char_buf = UCS_buf(param_val) c_buf_len = len(c_char_buf) - + elif param_types[col_num][0] == 'dt': max_len = self.connection.type_size_dic[SQL_TYPE_TIMESTAMP][0] datetime_str = param_val.strftime('%Y-%m-%d %H:%M:%S.%f') c_char_buf = datetime_str[:max_len] if py_v3: c_char_buf = bytes(c_char_buf,'ascii') - + c_buf_len = len(c_char_buf) # print c_buf_len, c_char_buf - + elif param_types[col_num][0] == 'd': if SQL_TYPE_DATE in self.connection.type_size_dic: max_len = self.connection.type_size_dic[SQL_TYPE_DATE][0] @@ -1507,7 +1507,7 @@ class Cursor: c_char_buf = bytes(c_char_buf,'ascii') c_buf_len = len(c_char_buf) #print c_char_buf - + elif param_types[col_num][0] == 't': if SQL_TYPE_TIME in self.connection.type_size_dic: max_len = self.connection.type_size_dic[SQL_TYPE_TIME][0] @@ -1526,7 +1526,7 @@ class Cursor: if py_v3: c_char_buf = bytes(c_char_buf,'ascii') #print c_buf_len, c_char_buf - + elif param_types[col_num][0] == 'b': if param_val == True: c_char_buf = '1' @@ -1535,7 +1535,7 @@ class Cursor: if py_v3: c_char_buf = bytes(c_char_buf,'ascii') c_buf_len = 1 - + elif param_types[col_num][0] == 'D': #Decimal sign = param_val.as_tuple()[0] == 0 and '+' or '-' digit_string = ''.join([str(x) for x in param_val.as_tuple()[1]]) @@ -1555,18 +1555,18 @@ class Cursor: else: c_char_buf = v c_buf_len = len(c_char_buf) - + elif param_types[col_num][0] == 'bi': c_char_buf = str_8b(param_val) c_buf_len = len(c_char_buf) - + else: c_char_buf = param_val - - + + if param_types[col_num][0] == 'bi': param_buffer.raw = str_8b(param_val) - + else: #print (type(param_val),param_buffer, param_buffer.value) param_buffer.value = c_char_buf @@ -1576,37 +1576,37 @@ class Cursor: param_buffer_len.value = SQL_NTS else: param_buffer_len.value = c_buf_len - + col_num += 1 ret = SQLExecute(self.stmt_h) if ret != SQL_SUCCESS: #print param_valparam_buffer, param_buffer.value check_success(self, ret) - + if not many_mode: self._NumOfRows() self._UpdateDesc() #self._BindCols() - + else: self.execdirect(query_string) return self - - + + def _SQLExecute(self): if not self.connection: self.close() ret = SQLExecute(self.stmt_h) if ret != SQL_SUCCESS: - check_success(self, ret) - - + check_success(self, ret) + + def execdirect(self, query_string): """Execute a query directly""" if not self.connection: self.close() - + self._free_stmt() self._last_param_types = None self.statement = None @@ -1621,25 +1621,25 @@ class Cursor: self._UpdateDesc() #self._BindCols() return self - - + + def callproc(self, procname, args): if not self.connection: self.close() raise Warning('', 'Still not fully implemented') self._pram_io_list = [row[4] for row in self.procedurecolumns(procedure = procname).fetchall() if row[4] not in (SQL_RESULT_COL, SQL_RETURN_VALUE)] - + print('pram_io_list: '+str(self._pram_io_list)) - - + + call_escape = '{CALL '+procname if args: call_escape += '(' + ','.join(['?' for params in args]) + ')' call_escape += '}' self.execute(call_escape, args, call_mode = True) - + result = [] for buf, buf_len, sql_type in self._ParamBufferList: @@ -1649,20 +1649,20 @@ class Cursor: result.append(self.connection.output_converter[sql_type](buf.value)) return result - - + + def executemany(self, query_string, params_list = [None]): if not self.connection: self.close() - + for params in params_list: self.execute(query_string, params, many_mode = True) self._NumOfRows() self.rowcount = -1 self._UpdateDesc() #self._BindCols() - - + + def _CreateColBuf(self): if not self.connection: @@ -1672,60 +1672,60 @@ class Cursor: self._ColBufferList = [] bind_data = True for col_num in range(NOC): - col_name = self.description[col_num][0] - col_size = self.description[col_num][2] - col_sql_data_type = self._ColTypeCodeList[col_num] + col_name = self.description[col_num][0] + col_size = self.description[col_num][2] + col_sql_data_type = self._ColTypeCodeList[col_num] target_type = SQL_data_type_dict[col_sql_data_type][2] - dynamic_length = SQL_data_type_dict[col_sql_data_type][5] + dynamic_length = SQL_data_type_dict[col_sql_data_type][5] # set default size base on the column's sql data type - total_buf_len = SQL_data_type_dict[col_sql_data_type][4] - + total_buf_len = SQL_data_type_dict[col_sql_data_type][4] + # over-write if there's pre-set size value for "large columns" - if total_buf_len > 20500: + if total_buf_len > 20500: total_buf_len = self._outputsize.get(None,total_buf_len) - # over-write if there's pre-set size value for the "col_num" column + # over-write if there's pre-set size value for the "col_num" column total_buf_len = self._outputsize.get(col_num, total_buf_len) # if the size of the buffer is very long, do not bind - # because a large buffer decrease performance, and sometimes you only get a NULL value. + # because a large buffer decrease performance, and sometimes you only get a NULL value. # in that case use sqlgetdata instead. if col_size >= 1024: - dynamic_length = True + dynamic_length = True alloc_buffer = SQL_data_type_dict[col_sql_data_type][3](total_buf_len) used_buf_len = c_ssize_t() - + force_unicode = self.connection.unicode_results - + if force_unicode and col_sql_data_type in (SQL_CHAR,SQL_VARCHAR,SQL_LONGVARCHAR): target_type = SQL_C_WCHAR alloc_buffer = create_buffer_u(total_buf_len) - + buf_cvt_func = self.connection.output_converter[self._ColTypeCodeList[col_num]] - + if bind_data: if dynamic_length: bind_data = False - self._ColBufferList.append([col_name, target_type, used_buf_len, ADDR(used_buf_len), alloc_buffer, ADDR(alloc_buffer), total_buf_len, buf_cvt_func, bind_data]) - + self._ColBufferList.append([col_name, target_type, used_buf_len, ADDR(used_buf_len), alloc_buffer, ADDR(alloc_buffer), total_buf_len, buf_cvt_func, bind_data]) + if bind_data: ret = ODBC_API.SQLBindCol(self.stmt_h, col_num + 1, target_type, ADDR(alloc_buffer), total_buf_len, ADDR(used_buf_len)) if ret != SQL_SUCCESS: check_success(self, ret) - + def _UpdateDesc(self): - "Get the information of (name, type_code, display_size, internal_size, col_precision, scale, null_ok)" + "Get the information of (name, type_code, display_size, internal_size, col_precision, scale, null_ok)" if not self.connection: self.close() - + force_unicode = self.connection.unicode_results if force_unicode: Cname = create_buffer_u(1024) else: Cname = create_buffer(1024) - + Cname_ptr = c_short() Ctype_code = c_short() Csize = ctypes.c_size_t() @@ -1736,34 +1736,34 @@ class Cursor: self._ColTypeCodeList = [] NOC = self._NumOfCols() for col in range(1, NOC+1): - - ret = ODBC_API.SQLColAttribute(self.stmt_h, col, SQL_DESC_DISPLAY_SIZE, ADDR(create_buffer(10)), + + ret = ODBC_API.SQLColAttribute(self.stmt_h, col, SQL_DESC_DISPLAY_SIZE, ADDR(create_buffer(10)), 10, ADDR(c_short()),ADDR(Cdisp_size)) if ret != SQL_SUCCESS: check_success(self, ret) - + if force_unicode: - + ret = ODBC_API.SQLDescribeColW(self.stmt_h, col, Cname, len(Cname), ADDR(Cname_ptr),\ ADDR(Ctype_code),ADDR(Csize),ADDR(CDecimalDigits), ADDR(Cnull_ok)) if ret != SQL_SUCCESS: check_success(self, ret) else: - + ret = ODBC_API.SQLDescribeCol(self.stmt_h, col, Cname, len(Cname), ADDR(Cname_ptr),\ ADDR(Ctype_code),ADDR(Csize),ADDR(CDecimalDigits), ADDR(Cnull_ok)) if ret != SQL_SUCCESS: check_success(self, ret) - + col_name = Cname.value if lowercase: col_name = col_name.lower() - #(name, type_code, display_size, + #(name, type_code, display_size, ColDescr.append((col_name, SQL_data_type_dict.get(Ctype_code.value,(Ctype_code.value,))[0],Cdisp_size.value,\ Csize.value, Csize.value,CDecimalDigits.value,Cnull_ok.value == 1 and True or False)) self._ColTypeCodeList.append(Ctype_code.value) - + if len(ColDescr) > 0: self.description = ColDescr # Create the row type before fetching. @@ -1771,26 +1771,26 @@ class Cursor: else: self.description = None self._CreateColBuf() - - + + def _NumOfRows(self): """Get the number of rows""" if not self.connection: self.close() - + NOR = c_ssize_t() ret = SQLRowCount(self.stmt_h, ADDR(NOR)) if ret != SQL_SUCCESS: check_success(self, ret) self.rowcount = NOR.value - return self.rowcount + return self.rowcount + - def _NumOfCols(self): """Get the number of cols""" if not self.connection: self.close() - + NOC = c_short() ret = SQLNumResultCols(self.stmt_h, ADDR(NOC)) if ret != SQL_SUCCESS: @@ -1801,7 +1801,7 @@ class Cursor: def fetchall(self): if not self.connection: self.close() - + rows = [] while True: row = self.fetchone() @@ -1814,11 +1814,11 @@ class Cursor: def fetchmany(self, num = None): if not self.connection: self.close() - + if num is None: num = self.arraysize rows = [] - + while len(rows) < num: row = self.fetchone() if row is None: @@ -1830,12 +1830,12 @@ class Cursor: def fetchone(self): if not self.connection: self.close() - + ret = SQLFetch(self.stmt_h) - - if ret in (SQL_SUCCESS,SQL_SUCCESS_WITH_INFO): + + if ret in (SQL_SUCCESS,SQL_SUCCESS_WITH_INFO): '''Bind buffers for the record set columns''' - + value_list = [] col_num = 1 for col_name, target_type, used_buf_len, ADDR_used_buf_len, alloc_buffer, ADDR_alloc_buffer, total_buf_len, buf_cvt_func, bind_data in self._ColBufferList: @@ -1844,10 +1844,10 @@ class Cursor: if bind_data: ret = SQL_SUCCESS else: - ret = SQLGetData(self.stmt_h, col_num, target_type, ADDR_alloc_buffer, total_buf_len, ADDR_used_buf_len) + ret = SQLGetData(self.stmt_h, col_num, target_type, ADDR_alloc_buffer, total_buf_len, ADDR_used_buf_len) if ret == SQL_SUCCESS: if used_buf_len.value == SQL_NULL_DATA: - value_list.append(None) + value_list.append(None) else: if raw_data_parts == []: # Means no previous data, no need to combine @@ -1865,21 +1865,21 @@ class Cursor: raw_data_parts.append(from_buffer_u(alloc_buffer)) else: raw_data_parts.append(alloc_buffer.value) - break - + break + elif ret == SQL_SUCCESS_WITH_INFO: # Means the data is only partial if target_type == SQL_C_BINARY: raw_data_parts.append(alloc_buffer.raw) else: - raw_data_parts.append(alloc_buffer.value) - + raw_data_parts.append(alloc_buffer.value) + elif ret == SQL_NO_DATA: # Means all data has been transmitted break else: - check_success(self, ret) - + check_success(self, ret) + if raw_data_parts != []: if py_v3: if target_type != SQL_C_BINARY: @@ -1893,47 +1893,47 @@ class Cursor: col_num += 1 return self._row_type(value_list) - + else: if ret == SQL_NO_DATA_FOUND: - + return None else: check_success(self, ret) - + def __next__(self): return self.next() - - def next(self): + + def next(self): row = self.fetchone() if row is None: raise(StopIteration) return row - + def __iter__(self): return self - + def skip(self, count = 0): if not self.connection: self.close() - + for i in range(count): ret = ODBC_API.SQLFetchScroll(self.stmt_h, SQL_FETCH_NEXT, 0) if ret != SQL_SUCCESS: check_success(self, ret) - return None - - - + return None + + + def nextset(self): if not self.connection: self.close() - + ret = ODBC_API.SQLMoreResults(self.stmt_h) if ret not in (SQL_SUCCESS, SQL_NO_DATA): check_success(self, ret) - + if ret == SQL_NO_DATA: self._free_stmt() return False @@ -1942,15 +1942,15 @@ class Cursor: self._UpdateDesc() #self._BindCols() return True - - + + def _free_stmt(self, free_type = None): if not self.connection: self.close() - + if not self.connection.connected: raise ProgrammingError('HY000','Attempt to use a closed connection.') - + #self.description = None #self.rowcount = -1 if free_type in (SQL_CLOSE, None): @@ -1961,17 +1961,17 @@ class Cursor: ret = ODBC_API.SQLFreeStmt(self.stmt_h, SQL_UNBIND) if ret != SQL_SUCCESS: check_success(self, ret) - if free_type in (SQL_RESET_PARAMS, None): + if free_type in (SQL_RESET_PARAMS, None): ret = ODBC_API.SQLFreeStmt(self.stmt_h, SQL_RESET_PARAMS) if ret != SQL_SUCCESS: check_success(self, ret) - - - + + + def getTypeInfo(self, sqlType = None): if not self.connection: self.close() - + if sqlType is None: type = SQL_ALL_TYPES else: @@ -1982,89 +1982,89 @@ class Cursor: self._UpdateDesc() #self._BindCols() return self.fetchone() - - + + def tables(self, table=None, catalog=None, schema=None, tableType=None): - """Return a list with all tables""" + """Return a list with all tables""" if not self.connection: self.close() - + l_catalog = l_schema = l_table = l_tableType = 0 - + if unicode in [type(x) for x in (table, catalog, schema,tableType)]: string_p = lambda x:wchar_pointer(UCS_buf(x)) API_f = ODBC_API.SQLTablesW else: string_p = ctypes.c_char_p API_f = ODBC_API.SQLTables - - - + + + if catalog is not None: l_catalog = len(catalog) - catalog = string_p(catalog) + catalog = string_p(catalog) - if schema is not None: + if schema is not None: l_schema = len(schema) schema = string_p(schema) - + if table is not None: l_table = len(table) table = string_p(table) - - if tableType is not None: + + if tableType is not None: l_tableType = len(tableType) tableType = string_p(tableType) - + self._free_stmt() self._last_param_types = None self.statement = None ret = API_f(self.stmt_h, catalog, l_catalog, - schema, l_schema, + schema, l_schema, table, l_table, tableType, l_tableType) check_success(self, ret) - + self._NumOfRows() self._UpdateDesc() #self._BindCols() return self - - + + def columns(self, table=None, catalog=None, schema=None, column=None): - """Return a list with all columns""" + """Return a list with all columns""" if not self.connection: self.close() - + l_catalog = l_schema = l_table = l_column = 0 - + if unicode in [type(x) for x in (table, catalog, schema,column)]: string_p = lambda x:wchar_pointer(UCS_buf(x)) API_f = ODBC_API.SQLColumnsW else: string_p = ctypes.c_char_p API_f = ODBC_API.SQLColumns - - - - if catalog is not None: + + + + if catalog is not None: l_catalog = len(catalog) catalog = string_p(catalog) if schema is not None: l_schema = len(schema) schema = string_p(schema) - if table is not None: + if table is not None: l_table = len(table) table = string_p(table) - if column is not None: + if column is not None: l_column = len(column) column = string_p(column) - + self._free_stmt() self._last_param_types = None self.statement = None - + ret = API_f(self.stmt_h, catalog, l_catalog, schema, l_schema, @@ -2076,87 +2076,87 @@ class Cursor: self._UpdateDesc() #self._BindCols() return self - - + + def primaryKeys(self, table=None, catalog=None, schema=None): if not self.connection: self.close() - + l_catalog = l_schema = l_table = 0 - + if unicode in [type(x) for x in (table, catalog, schema)]: string_p = lambda x:wchar_pointer(UCS_buf(x)) API_f = ODBC_API.SQLPrimaryKeysW else: string_p = ctypes.c_char_p API_f = ODBC_API.SQLPrimaryKeys - - - - if catalog is not None: + + + + if catalog is not None: l_catalog = len(catalog) catalog = string_p(catalog) - - if schema is not None: + + if schema is not None: l_schema = len(schema) schema = string_p(schema) - - if table is not None: + + if table is not None: l_table = len(table) table = string_p(table) - + self._free_stmt() self._last_param_types = None self.statement = None - + ret = API_f(self.stmt_h, catalog, l_catalog, schema, l_schema, table, l_table) check_success(self, ret) - + self._NumOfRows() self._UpdateDesc() #self._BindCols() return self - - + + def foreignKeys(self, table=None, catalog=None, schema=None, foreignTable=None, foreignCatalog=None, foreignSchema=None): if not self.connection: self.close() - + l_catalog = l_schema = l_table = l_foreignTable = l_foreignCatalog = l_foreignSchema = 0 - + if unicode in [type(x) for x in (table, catalog, schema,foreignTable,foreignCatalog,foreignSchema)]: string_p = lambda x:wchar_pointer(UCS_buf(x)) API_f = ODBC_API.SQLForeignKeysW else: string_p = ctypes.c_char_p API_f = ODBC_API.SQLForeignKeys - - if catalog is not None: + + if catalog is not None: l_catalog = len(catalog) catalog = string_p(catalog) - if schema is not None: + if schema is not None: l_schema = len(schema) schema = string_p(schema) - if table is not None: + if table is not None: l_table = len(table) table = string_p(table) - if foreignTable is not None: + if foreignTable is not None: l_foreignTable = len(foreignTable) foreignTable = string_p(foreignTable) - if foreignCatalog is not None: + if foreignCatalog is not None: l_foreignCatalog = len(foreignCatalog) foreignCatalog = string_p(foreignCatalog) - if foreignSchema is not None: + if foreignSchema is not None: l_foreignSchema = len(foreignSchema) foreignSchema = string_p(foreignSchema) - + self._free_stmt() self._last_param_types = None self.statement = None - + ret = API_f(self.stmt_h, catalog, l_catalog, schema, l_schema, @@ -2165,17 +2165,17 @@ class Cursor: foreignSchema, l_foreignSchema, foreignTable, l_foreignTable) check_success(self, ret) - + self._NumOfRows() self._UpdateDesc() #self._BindCols() return self - - + + def procedurecolumns(self, procedure=None, catalog=None, schema=None, column=None): if not self.connection: self.close() - + l_catalog = l_schema = l_procedure = l_column = 0 if unicode in [type(x) for x in (procedure, catalog, schema,column)]: string_p = lambda x:wchar_pointer(UCS_buf(x)) @@ -2183,74 +2183,74 @@ class Cursor: else: string_p = ctypes.c_char_p API_f = ODBC_API.SQLProcedureColumns - - - if catalog is not None: + + + if catalog is not None: l_catalog = len(catalog) catalog = string_p(catalog) - if schema is not None: + if schema is not None: l_schema = len(schema) schema = string_p(schema) - if procedure is not None: + if procedure is not None: l_procedure = len(procedure) procedure = string_p(procedure) - if column is not None: + if column is not None: l_column = len(column) column = string_p(column) - - + + self._free_stmt() self._last_param_types = None self.statement = None - + ret = API_f(self.stmt_h, catalog, l_catalog, schema, l_schema, procedure, l_procedure, column, l_column) check_success(self, ret) - + self._NumOfRows() self._UpdateDesc() return self - - + + def procedures(self, procedure=None, catalog=None, schema=None): if not self.connection: self.close() - + l_catalog = l_schema = l_procedure = 0 - + if unicode in [type(x) for x in (procedure, catalog, schema)]: string_p = lambda x:wchar_pointer(UCS_buf(x)) API_f = ODBC_API.SQLProceduresW else: string_p = ctypes.c_char_p API_f = ODBC_API.SQLProcedures - - - - if catalog is not None: + + + + if catalog is not None: l_catalog = len(catalog) catalog = string_p(catalog) - if schema is not None: + if schema is not None: l_schema = len(schema) schema = string_p(schema) - if procedure is not None: + if procedure is not None: l_procedure = len(procedure) procedure = string_p(procedure) - - + + self._free_stmt() self._last_param_types = None self.statement = None - + ret = API_f(self.stmt_h, catalog, l_catalog, schema, l_schema, procedure, l_procedure) check_success(self, ret) - + self._NumOfRows() self._UpdateDesc() return self @@ -2259,27 +2259,27 @@ class Cursor: def statistics(self, table, catalog=None, schema=None, unique=False, quick=True): if not self.connection: self.close() - + l_table = l_catalog = l_schema = 0 - + if unicode in [type(x) for x in (table, catalog, schema)]: string_p = lambda x:wchar_pointer(UCS_buf(x)) API_f = ODBC_API.SQLStatisticsW else: string_p = ctypes.c_char_p API_f = ODBC_API.SQLStatistics - - - if catalog is not None: + + + if catalog is not None: l_catalog = len(catalog) catalog = string_p(catalog) - if schema is not None: + if schema is not None: l_schema = len(schema) schema = string_p(schema) - if table is not None: + if table is not None: l_table = len(table) table = string_p(table) - + if unique: Unique = SQL_INDEX_UNIQUE else: @@ -2288,23 +2288,23 @@ class Cursor: Reserved = SQL_QUICK else: Reserved = SQL_ENSURE - + self._free_stmt() self._last_param_types = None self.statement = None - + ret = API_f(self.stmt_h, catalog, l_catalog, - schema, l_schema, + schema, l_schema, table, l_table, Unique, Reserved) check_success(self, ret) - + self._NumOfRows() self._UpdateDesc() #self._BindCols() return self - + def commit(self): if not self.connection: @@ -2315,12 +2315,12 @@ class Cursor: if not self.connection: self.close() self.connection.rollback() - + def setoutputsize(self, size, column = None): if not self.connection: self.close() self._outputsize[column] = size - + def setinputsizes(self, sizes): if not self.connection: self.close() @@ -2331,7 +2331,7 @@ class Cursor: """ Call SQLCloseCursor API to free the statement handle""" # ret = ODBC_API.SQLCloseCursor(self.stmt_h) # check_success(self, ret) -# +# if self.connection.connected: ret = ODBC_API.SQLFreeStmt(self.stmt_h, SQL_CLOSE) check_success(self, ret) @@ -2344,32 +2344,32 @@ class Cursor: ret = ODBC_API.SQLFreeHandle(SQL_HANDLE_STMT, self.stmt_h) check_success(self, ret) - - + + self.closed = True - - - def __del__(self): + + + def __del__(self): if not self.closed: self.close() - + def __exit__(self, type, value, traceback): if not self.connection: self.close() - + if value: self.rollback() else: self.commit() - + self.close() - - + + def __enter__(self): return self - -# This class implement a odbc connection. + +# This class implement a odbc connection. # # @@ -2390,7 +2390,7 @@ class Connection: connectString = connectString + key + '=' + value + ';' self.connectString = connectString - + self.clear_output_converters() try: @@ -2400,23 +2400,23 @@ class Connection: AllocateEnv() finally: lock.release() - + # Allocate an DBC handle self.dbc_h under the environment shared_env_h # This DBC handle is actually the basis of a "connection" - # The handle of self.dbc_h will be used to connect to a certain source + # The handle of self.dbc_h will be used to connect to a certain source # in the self.connect and self.ConnectByDSN method - + ret = ODBC_API.SQLAllocHandle(SQL_HANDLE_DBC, shared_env_h, ADDR(self.dbc_h)) check_success(self, ret) - + self.connect(connectString, autocommit, ansi, timeout, unicode_results, readonly) - - - + + + def connect(self, connectString = '', autocommit = False, ansi = False, timeout = 0, unicode_results = use_unicode, readonly = False): """Connect to odbc, using connect strings and set the connection's attributes like autocommit and timeout by calling SQLSetConnectAttr - """ + """ # Before we establish the connection by the connection string # Set the connection's attribute of "timeout" (Actully LOGIN_TIMEOUT) @@ -2431,9 +2431,9 @@ class Connection: # Convert the connetsytring to encoded string - # so it can be converted to a ctypes c_char array object + # so it can be converted to a ctypes c_char array object + - self.ansi = ansi if not ansi: c_connectString = wchar_pointer(UCS_buf(self.connectString)) @@ -2459,43 +2459,43 @@ class Connection: else: ret = odbc_func(self.dbc_h, 0, c_connectString, len(self.connectString), None, 0, None, SQL_DRIVER_NOPROMPT) check_success(self, ret) - - - # Set the connection's attribute of "autocommit" + + + # Set the connection's attribute of "autocommit" # self.autocommit = autocommit - + if self.autocommit == True: ret = ODBC_API.SQLSetConnectAttr(self.dbc_h, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_ON, SQL_IS_UINTEGER) else: ret = ODBC_API.SQLSetConnectAttr(self.dbc_h, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, SQL_IS_UINTEGER) check_success(self, ret) - - # Set the connection's attribute of "readonly" + + # Set the connection's attribute of "readonly" # self.readonly = readonly - + ret = ODBC_API.SQLSetConnectAttr(self.dbc_h, SQL_ATTR_ACCESS_MODE, self.readonly and SQL_MODE_READ_ONLY or SQL_MODE_READ_WRITE, SQL_IS_UINTEGER) check_success(self, ret) - + self.unicode_results = unicode_results self.connected = 1 self.update_db_special_info() - + def clear_output_converters(self): self.output_converter = {} for sqltype, profile in SQL_data_type_dict.items(): self.output_converter[sqltype] = profile[1] - - + + def add_output_converter(self, sqltype, func): self.output_converter[sqltype] = func - + def settimeout(self, timeout): ret = ODBC_API.SQLSetConnectAttr(self.dbc_h, SQL_ATTR_CONNECTION_TIMEOUT, timeout, SQL_IS_UINTEGER); check_success(self, ret) self.timeout = timeout - + def ConnectByDSN(self, dsn, user, passwd = ''): """Connect to odbc, we need dsn, user and optionally password""" @@ -2504,21 +2504,21 @@ class Connection: self.passwd = passwd sn = create_buffer(dsn) - un = create_buffer(user) + un = create_buffer(user) pw = create_buffer(passwd) - + ret = ODBC_API.SQLConnect(self.dbc_h, sn, len(sn), un, len(un), pw, len(pw)) check_success(self, ret) self.update_db_special_info() self.connected = 1 - - - def cursor(self, row_type_callable=None): + + + def cursor(self, row_type_callable=None): #self.settimeout(self.timeout) if not self.connected: raise ProgrammingError('HY000','Attempt to use a closed connection.') - cur = Cursor(self, row_type_callable=row_type_callable) + cur = Cursor(self, row_type_callable=row_type_callable) # self._cursors.append(cur) return cur @@ -2538,7 +2538,7 @@ class Connection: except: pass cur.close() - + self.support_SQLDescribeParam = False try: driver_name = self.getinfo(SQL_DRIVER_NAME) @@ -2546,11 +2546,11 @@ class Connection: self.support_SQLDescribeParam = True except: pass - + def commit(self): if not self.connected: raise ProgrammingError('HY000','Attempt to use a closed connection.') - + ret = SQLEndTran(SQL_HANDLE_DBC, self.dbc_h, SQL_COMMIT) if ret != SQL_SUCCESS: check_success(self, ret) @@ -2561,14 +2561,14 @@ class Connection: ret = SQLEndTran(SQL_HANDLE_DBC, self.dbc_h, SQL_ROLLBACK) if ret != SQL_SUCCESS: check_success(self, ret) - - - + + + def getinfo(self,infotype): if infotype not in list(aInfoTypes.keys()): - raise ProgrammingError('HY000','Invalid getinfo value: '+str(infotype)) - - + raise ProgrammingError('HY000','Invalid getinfo value: '+str(infotype)) + + if aInfoTypes[infotype] == 'GI_UINTEGER': total_buf_len = 1000 alloc_buffer = ctypes.c_ulong() @@ -2577,7 +2577,7 @@ class Connection: ADDR(used_buf_len)) check_success(self, ret) result = alloc_buffer.value - + elif aInfoTypes[infotype] == 'GI_USMALLINT': total_buf_len = 1000 alloc_buffer = ctypes.c_ushort() @@ -2607,25 +2607,25 @@ class Connection: result = True else: result = False - + return result - + def __exit__(self, type, value, traceback): if value: self.rollback() else: self.commit() - + if self.connected: self.close() - + def __enter__(self): return self def __del__(self): if self.connected: self.close() - + def close(self): if not self.connected: raise ProgrammingError('HY000','Attempt to close a closed connection.') @@ -2633,7 +2633,7 @@ class Connection: # if not cur is None: # if not cur.closed: # cur.close() - + if self.connected: #if DEBUG:print 'disconnect' if not self.autocommit: @@ -2648,7 +2648,7 @@ class Connection: # ret = ODBC_API.SQLFreeHandle(SQL_HANDLE_ENV, shared_env_h) # check_success(shared_env_h, ret) self.connected = 0 - + odbc = Connection connect = odbc ''' @@ -2665,7 +2665,7 @@ def drivers(): AllocateEnv() finally: lock.release() - + DriverDescription = create_buffer_u(1000) BufferLength1 = c_short(1000) DescriptionLength = c_short() @@ -2683,14 +2683,14 @@ def drivers(): if Direction == SQL_FETCH_FIRST: Direction = SQL_FETCH_NEXT return DriverList - + def win_create_mdb(mdb_path, sort_order = "General\0\0"): if sys.platform not in ('win32','cli'): raise Exception('This function is available for use in Windows only.') - + mdb_driver = [d for d in drivers() if 'Microsoft Access Driver (*.mdb' in d] if mdb_driver == []: raise Exception('Access Driver is not found.') @@ -2706,17 +2706,17 @@ def win_create_mdb(mdb_path, sort_order = "General\0\0"): else: c_Path = "CREATE_DB=" + mdb_path + " " + sort_order ODBC_ADD_SYS_DSN = 1 - - + + ret = ctypes.windll.ODBCCP32.SQLConfigDataSource(None,ODBC_ADD_SYS_DSN,driver_name, c_Path) if not ret: raise Exception('Failed to create Access mdb file - "%s". Please check file path, permission and Access driver readiness.' %mdb_path) - - + + def win_connect_mdb(mdb_path): if sys.platform not in ('win32','cli'): raise Exception('This function is available for use in Windows only.') - + mdb_driver = [d for d in drivers() if 'Microsoft Access Driver (*.mdb' in d] if mdb_driver == []: raise Exception('Access Driver is not found.') @@ -2724,20 +2724,20 @@ def win_connect_mdb(mdb_path): driver_name = mdb_driver[0] return connect('Driver={'+driver_name+"};DBQ="+mdb_path, unicode_results = use_unicode, readonly = False) - - - + + + def win_compact_mdb(mdb_path, compacted_mdb_path, sort_order = "General\0\0"): if sys.platform not in ('win32','cli'): raise Exception('This function is available for use in Windows only.') - - + + mdb_driver = [d for d in drivers() if 'Microsoft Access Driver (*.mdb' in d] if mdb_driver == []: raise Exception('Access Driver is not found.') else: driver_name = mdb_driver[0].encode('mbcs') - + #COMPACT_DB= ctypes.windll.ODBCCP32.SQLConfigDataSource.argtypes = [ctypes.c_void_p,ctypes.c_ushort,ctypes.c_char_p,ctypes.c_char_p] #driver_name = "Microsoft Access Driver (*.mdb)" @@ -2751,7 +2751,7 @@ def win_compact_mdb(mdb_path, compacted_mdb_path, sort_order = "General\0\0"): ret = ctypes.windll.ODBCCP32.SQLConfigDataSource(None,ODBC_ADD_SYS_DSN,driver_name, c_Path) if not ret: raise Exception('Failed to compact Access mdb file - "%s". Please check file path, permission and Access driver readiness.' %compacted_mdb_path) - + def dataSources(): """Return a list with [name, descrition]""" diff --git a/gluon/contrib/stripe.py b/gluon/contrib/stripe.py index b9602ace..a0f6ce6d 100644 --- a/gluon/contrib/stripe.py +++ b/gluon/contrib/stripe.py @@ -37,7 +37,7 @@ def pay(): elif form.errors: redirect(URL('pay_error')) return dict(form=form) - + """ URL_CHARGE = 'https://%s:@api.stripe.com/v1/charges' @@ -114,7 +114,7 @@ class StripeForm(object): def process(self): from gluon import current - request = current.request + request = current.request if request.post_vars: if self.signature == request.post_vars.signature: self.response = Stripe(self.sk).charge( @@ -127,7 +127,7 @@ class StripeForm(object): return self self.errors = True return self - + def xml(self): from gluon.template import render if self.accepted: @@ -135,8 +135,8 @@ class StripeForm(object): elif self.errors: return "There was an processing error" else: - context = dict(amount=self.amount, - signature=self.signature, pk=self.pk, + context = dict(amount=self.amount, + signature=self.signature, pk=self.pk, currency_symbol=self.currency_symbol, security_notice=self.security_notice, disclosure_notice=self.disclosure_notice) @@ -145,14 +145,14 @@ class StripeForm(object): TEMPLATE = """ -