def __init__(self): realm = config.get("tools.oauth.realm", "http://www.example.com") datastore_class_path = config.get("tools.oauth.datastore", "gearshift.tools.oauth.sodatastore.OAuthDataStore") datastore_class = load_class(datastore_class_path) if datastore_class: log.info("Successfully loaded \"%s\"" % datastore_class_path) else: log.error("Unable to load \"%s\"" % datastore_class_path) return self.datastore = datastore_class() self.request_token_url = config.get('oauth.request_token.url', '/request_token') self.access_token_url = config.get('oauth.access_token.url', '/access_token') self.realm = realm self.oauth_server = oauth.OAuthServer(self.datastore) self.oauth_server.add_signature_method( oauth.OAuthSignatureMethod_PLAINTEXT()) self.oauth_server.add_signature_method( oauth.OAuthSignatureMethod_HMAC_SHA1()) log.info("OAuthTool initialized") return super(OAuthTool, self).__init__(point='before_handler', callable=self.before_handler, priority=10)
def __init__(self): realm = config.get("tools.oauth.realm", "http://www.example.com") datastore_class_path = config.get( "tools.oauth.datastore", "gearshift.tools.oauth.sodatastore.OAuthDataStore") datastore_class = load_class(datastore_class_path) if datastore_class: log.info("Successfully loaded \"%s\"" % datastore_class_path) else: log.error("Unable to load \"%s\"" % datastore_class_path) return self.datastore = datastore_class() self.request_token_url = config.get('oauth.request_token.url', '/request_token') self.access_token_url = config.get('oauth.access_token.url', '/access_token') self.realm = realm self.oauth_server = oauth.OAuthServer(self.datastore) self.oauth_server.add_signature_method( oauth.OAuthSignatureMethod_PLAINTEXT()) self.oauth_server.add_signature_method( oauth.OAuthSignatureMethod_HMAC_SHA1()) log.info("OAuthTool initialized") return super(OAuthTool, self).__init__(point='before_handler', callable=self.before_handler, priority=10)
def load_project_config(self): """Choose the config file. Try to guess whether this is a development or installed project. """ # check whether user specified custom settings if self.load_config: load_project_config(self.config) if config.get("i18n.locale_dir"): self.locale_dir = config.get("i18n.locale_dir") print 'Use %s as a locale directory' % self.locale_dir if config.get('i18n.domain'): self.domain = config.get("i18n.domain") print 'Use %s as a message domain' % self.domain if os.path.exists(self.locale_dir) and \ not os.path.isdir(self.locale_dir): raise ProgramError, ( '%s is not a directory' % self.locale_dir) if not os.path.exists(self.locale_dir): os.makedirs(self.locale_dir)
def start_server(): """Start the server if it's not already.""" if not config.get("cp_started"): cherrypy.engine.start() config.update({"cp_started" : True}) if not config.get("server_started"): startup.startTurboGears() config.update({"server_started" : True})
def setUp(self): testutil.stop_server(tg_only = True) self._visit_on = config.get('tools.visit.on', False) self._visit_source = config.get('tools.visit.source', 'cookie') config.update({'tools.visit.on': True}) self._visit_timeout = config.get('tools.visit.timeout', 20) config.update({'tools.visit.timeout': 50}) self.cookie_name = config.get("tools.visit.cookie.name", 'tg-visit') self._visit_key_param = config.get("tools.visit.form.name", 'tg_visit') self.app = testutil.make_app(VisitRoot) testutil.start_server()
def setUp(self): testutil.stop_server(tg_only=True) self._visit_on = config.get('tools.visit.on', False) self._visit_source = config.get('tools.visit.source', 'cookie') config.update({'tools.visit.on': True}) self._visit_timeout = config.get('tools.visit.timeout', 20) config.update({'tools.visit.timeout': 50}) self.cookie_name = config.get("tools.visit.cookie.name", 'tg-visit') self._visit_key_param = config.get("tools.visit.form.name", 'tg_visit') self.app = testutil.make_app(VisitRoot) testutil.start_server()
def db(self): if hasattr(request, "_couchdb_db"): db = request._couchdb_db else: dburi = config.get("couchdb.dburi") server = Server(dburi) username = config.get("couchdb.username") password = config.get("couchdb.password") if username: server.resource.http.add_credentials(username, password) db = server[config.get("couchdb.database")] request._couchdb_db = db return db
def start_extension(self): # Bail out if the application hasn't enabled this extension if not config.get("tools.visit.on", False): return # Bail out if this extension is already running global _manager if _manager: return log.info("Visit Tracking starting") # How long may the visit be idle before a new visit ID is assigned? # The default is 20 minutes. timeout = timedelta(minutes=config.get("tools.visit.timeout", 20)) # Create the thread that manages updating the visits _manager = _create_visit_manager(timeout)
def start_extension(self): # Bail out if the application hasn't enabled this extension if not config.get('tools.identity.on', False): return # Identity requires that Visit tracking be enabled if not config.get('tools.visit.on', False): raise identity.IdentityConfigurationException( "Visit tracking must be enabled (tools.visit.on)") log.info("Identity starting") # Temporary until tg-admin can call create_extension_model visitor.create_extension_model() # Register the plugin for the Visit Tracking framework visit.enable_visit_plugin(visitor.IdentityVisitPlugin())
def i18n_filter(stream, template, locale=None): """Kid template filter which calls translates all elements matching language attribute(set in configuration as i18n.templateLocaleAttribute, default 'lang') """ lang_attr = config.get("i18n.templateLocaleAttribute", "lang") locales=[locale] for ev, item in stream: if ev==START: l = item.get(lang_attr) if l: locale = l locales.append(l) elif ev==TEXT: prefix = '' postfix = '' if len(item) > 0 and item[0] == ' ': prefix =' ' if len(item) > 1 and item[-1] == ' ': postfix =' ' text = item.strip() if text: item = gettext(text, locale) item = prefix + item + postfix elif ev==END: if item.get(lang_attr): locales.pop() locale = locales[-1] yield (ev, item)
def __init__(self, uri=None, supports_transactions=True): if not uri: uri = config.get("sqlobject.dburi") self.uri = uri self.supports_transactions = supports_transactions hub_registry.add(self) ConnectionHub.__init__(self)
def _get_locale(): """Default function for returning locale. First looks in session for locale key, then checks the HTTP Accept-Language header, and finally checks the config default locale setting. This can be replaced by your own function by setting cherrypy config setting i18n.get_locale to your function name. """ if not request_available(): return config.get("i18n.default_locale", "en") if config.get("tools.sessions.on", False): locale_key = config.get("i18n.session_key", "locale") locale = cherrypy.session.get(locale_key) if locale: return locale browser_accept_lang = _get_locale_from_accept_header() return browser_accept_lang or config.get("i18n.default_locale", "en")
def handler(self, oldhandler, *args, **kwargs): output = oldhandler(*args, **kwargs) # If not a dict then output has been rendered and there's nothing left # for us to do, so bail out if not isinstance(output, dict): return output get = request.config.get exposes = get('tools.expose.exposes', dict(default={})) accept = request.headers.get('Accept', "").lower() accept = tg_util.simplify_http_accept_header(accept) tg_format = request.tg_format # Select the correct expose to use. First we trust tg_format, then # accept headers, then fallback to default for key in [tg_format, accept, 'default']: if exposes.has_key(key): expose = exposes[key] break # Unpack parameters that were supplied to @expose format = expose.get('format', get('tools.expose.format', None)) template = expose.get('template', get('tools.expose.template', None)) allow_json = expose.get('allow_json', get('tools.expose.allow_json', False)) mapping = expose.get('mapping') fragment = expose.get('fragment') if format == "json" or (format is None and template is None): template = "json" if allow_json and (tg_format == "json" or accept in ("application/json", "text/javascript")): template = "json" if not template: template = format content_type = expose.get('content_type', config.get("tg.content_type", None)) if template and template.startswith("."): template = func.__module__[:func.__module__.rfind('.')]+template output["tg_css"] = tg_util.setlike() headers = {'Content-Type': content_type} output = render(output, template=template, format=format, mapping=mapping, headers=headers, fragment=fragment) content_type = headers['Content-Type'] if content_type: response.headers["Content-Type"] = content_type return output cherrypy.request.handler = handler
def __init__(self): super(OAuthDataStore, self).__init__() global token_class token_class_path = config.get("tools.oauth.sodatastore.model.token", "gearshift.tools.oauth.sodatastore.TG_Token") token_class = load_class(token_class_path) if token_class: log.info("Successfully loaded \"%s\"" % token_class_path) global nonce_class nonce_class_path = config.get("tools.oauth.sodatastore.model.nonce", "gearshift.tools.oauth.sodatastore.TG_Nonce") nonce_class = load_class(nonce_class_path) if nonce_class: log.info("Successfully loaded \"%s\"" % nonce_class_path)
def set_hub(self): dburi = config.get("%s.dburi" % self.packagename, None) if not dburi: dburi = config.get("sqlobject.dburi", None) if not dburi: raise KeyError, "No database configuration found!" if dburi.startswith("notrans_"): dburi = dburi[8:] trans = False else: trans = True hub = _hubs.get(dburi, None) if not hub: hub = AutoConnectHub(dburi, supports_transactions=trans) _hubs[dburi] = hub self.hub = hub
def translate(item, attr=None): """Translates the text of element plus the text of all child elements. If attr is present this is used to provide the locale name; if not then value provided by get_locale is used. For example: <div lang=""> this is a test <a href="de">testing</a> </div> The string 'this is a test' is rendered by the locale provided by get_locale, the string 'testing' by the German locale. Possible use in Kid template: <?python from turbogears.i18n import translate ?> <translate xmlns:py="http://purl.org/kid/ns#" py:match="item.attrib.has_key('lang')" py:replace="translate(item)"/> <h1 lang="">Welcome!</h1> @param item: element to be translated @type item: ElementTree element @param attr: attribute name used to store locale, if any """ if attr is None: attr = config.get("i18n.templateLocaleAttribute", "lang") translate_all(item, item.get(attr), attr) return item
def i18n_filter(stream, template, locale=None): """Kid template filter which calls translates all elements matching language attribute(set in configuration as i18n.templateLocaleAttribute, default 'lang') """ lang_attr = config.get("i18n.templateLocaleAttribute", "lang") locales = [locale] for ev, item in stream: if ev == START: l = item.get(lang_attr) if l: locale = l locales.append(l) elif ev == TEXT: prefix = "" postfix = "" if len(item) > 0 and item[0] == " ": prefix = " " if len(item) > 1 and item[-1] == " ": postfix = " " text = item.strip() if text: item = gettext(text, locale) item = prefix + item + postfix elif ev == END: if item.get(lang_attr): locales.pop() locale = locales[-1] yield (ev, item)
def find_config(self): """Chooses the config file, trying to guess whether this is a development or installed project.""" load_project_config(self.config) self.dburi = config.get("sqlobject.dburi", None) if self.dburi and self.dburi.startswith("notrans_"): self.dburi = self.dburi[8:]
def index(self): new = visit_key = None cur_visit = visit.current() if cur_visit: new = cur_visit.is_new key = cur_visit.key visit_on = config.get('tools.visit.on') return dict(new=new, key=key, visit_on=visit_on)
def __init__(self): log.debug("GFCTool initialized") self.site_id = config.get("gfc_consumer_key", ":").split(":")[1] return super(GFCTool, self).__init__(point='before_handler', callable=self.before_handler, priority=10)
def stop_server(tg_only = False): """Stop the server and unmount the application. \ Use tg_only = True to leave CherryPy running (for faster tests). """ unmount() if not tg_only: if not cherrypy.engine.state in [states.STOPPED]: cherrypy.engine.exit() config.update({"cp_started" : False}) if config.get("cp_started") and not tg_only: cherrypy.server.stop() config.update({"cp_started" : False}) if config.get("server_started"): startup.stopTurboGears() config.update({"server_started" : False})
def is_locale_supported(locale, domain=None): """Check if [domain].mo file exists for this language.""" if not domain: domain = config.get("i18n.domain", "messages") localedir = get_locale_dir() return localedir and os.path.exists(os.path.join( localedir, locale, "LC_MESSAGES", "%s.mo" % domain))
def get_locale(locale=None): """ Returns user locale, using _get_locale or app-specific locale lookup function. """ if not locale: get_locale_f = config.get("i18n.get_locale", _get_locale) locale = get_locale_f() return locale
def set_session_locale(locale): """ Sets the i18n session locale. Raises an error if session support is not enabled. """ sess_key = config.get("i18n.session_key", "locale") setattr(cherrypy.session, 'sess_key', locale)
def test_old_visit(self): """Test if we can track a visitor over time.""" response = self.app.get("/") # first visit's cookie print "Headers", response.headers print "Visit on", config.get('tools.visit.on') morsel = response.cookies_set[self.cookie_name] response = self.app.get("/", headers=cookie_header(response)) assert not response.raw['new']
def connect_db(thread_index): global storm_stores dburi = config.get('storm.dburi') database = create_database(dburi) try: local_store = Store(database) except Exception: log.error("Unable to connect to database: %s" % dburi) cherrypy.engine.exit() return timezone = config.get("storm.timezone") if timezone: local_store.execute(SQL("SET time_zone=?", (timezone, ))); storm_stores[thread_index] = local_store cherrypy.thread_data.store = local_store
def _choose_engine(template): if isinstance(template, basestring): colon = template.find(":") if colon > -1: enginename = template[:colon] template = template[colon + 1:] else: engine = engines.get(template, None) if engine: return engine, None, template enginename = config.get("tg.defaultview", "genshi") else: enginename = config.get("tg.defaultview", "genshi") engine = engines.get(enginename, None) if not engine: raise KeyError, \ "Template engine %s is not installed" % enginename return engine, template, enginename
def _choose_engine(template): if isinstance(template, basestring): colon = template.find(":") if colon > -1: enginename = template[:colon].lower() template = template[colon+1:] else: engine = engines.get(template, None) if engine: return engine, None, template enginename = config.get("tg.defaultmarkup", "markdown") else: enginename = config.get("tg.defaultmarkup", "markdown") engine = engines.get(enginename, None) if not engine: raise KeyError, \ "Template engine %s is not installed" % enginename return engine, template, enginename
def __init__(self, timeout): global visit_class visit_class_path = config.get("tools.visit.aeprovider.model", "gearshift.visit.aevisit.TG_Visit") visit_class = load_class(visit_class_path) if not visit_class: log.error("Error loading \"%s\"" % visit_class_path) self.create_model() self.timeout = timeout
def __init__(self, timeout): global visit_class visit_class_path = config.get("tools.visit.stprovider.model", "gearshift.visit.stvisit.TG_Visit") visit_class = load_class(visit_class_path) if visit_class: log.info("Successfully loaded \"%s\"" % visit_class_path) # base-class' __init__ triggers self.create_model, so mappers need to # be initialized before. super(StormVisitManager, self).__init__(timeout)
def _create_visit_manager(timeout): """Create a VisitManager based on the plugin specified in the config file.""" plugin_name = config.get("tools.visit.manager", "gearshift.visit.sovisit.SqlObjectVisitManager") try: plugin = load_class(plugin_name) except Exception, e: log.error("Error loading visit plugin '%s': %s", plugin_name, e) raise RuntimeError("VisitManager plugin missing: %s" % plugin_name)
def start_server(root): app = cherrypy.tree.mount(root, config=config.app) if config.get("tg.fancy_exception", False): from paste import evalexception app.wsgiapp.pipeline.append(("paste_exc", evalexception.middleware.EvalException)) cherrypy.engine.start() cherrypy.engine.block()
def plain_gettext(key, locale=None, domain=None): """Get the gettext value for key. Added to builtins as '_'. Returns Unicode string. @param key: text to be translated @param locale: locale code to be used. If locale is None, gets the value provided by get_locale. """ gettext_func = config.get("i18n.gettext", tg_gettext) return gettext_func(key, locale, domain)
def run(self): """Run the sqlobject-admin tool or functions from the sacommand module.""" if not "--egg" in sys.argv and not gearshift.util.get_project_name(): print "This doesn't look like a GearShift project." return else: command = sys.argv[1] if config.get("sqlalchemy.dburi"): try: sacommand(command, sys.argv) except Exception: # NoApplicableMethods: # Anonymous except to avoid making entire # gearshift dependent on peak.rules just to get # this ONE case of NoApplicableMethods... sacommand("help", []) return try: from sqlobject.manager import command except ImportError: from gearshift.util import missing_dependency_error print missing_dependency_error('SQLObject') return sqlobjcommand = command if sqlobjcommand not in no_connection_param: if self.dburi: print "Using database URI %s" % self.dburi sys.argv.insert(2, self.dburi) sys.argv.insert(2, "-c") else: print( "Database URI not specified in the config file" " (%s).\nPlease be sure it's on the command line." % (self.config or get_project_config())) if sqlobjcommand not in no_model_param: if not "--egg" in sys.argv: eggname = glob.glob("*.egg-info") if not eggname or not os.path.exists( os.path.join(eggname[0], "sqlobject.txt")): eggname = self.fix_egginfo(eggname) eggname = eggname[0].replace(".egg-info", "") if not "." in sys.path: sys.path.append(".") pkg_resources.working_set.add_entry(".") sys.argv.insert(2, eggname) sys.argv.insert(2, "--egg") command.the_runner.run(sys.argv)
def plain_ngettext(key1, key2, num, locale=None, domain=None): """Translate two possible texts based on whether num is greater than 1. @param key1: text if num==1 @param key2: text if num!=1 @param num: a number @type num: integer @locale: locale code to be used. If locale is None, gets the value provided by get_locale. """ ngettext_func = config.get("i18n.ngettext", tg_ngettext) return ngettext_func(key1, key2, num, locale, domain)
def load_project_config(self): """Choose the config file. Try to guess whether this is a development or installed project. """ # check whether user specified custom settings if self.load_config: load_project_config(self.config) if config.get("i18n.locale_dir"): self.locale_dir = config.get("i18n.locale_dir") print 'Use %s as a locale directory' % self.locale_dir if config.get('i18n.domain'): self.domain = config.get("i18n.domain") print 'Use %s as a message domain' % self.domain if os.path.exists(self.locale_dir) and \ not os.path.isdir(self.locale_dir): raise ProgramError, ('%s is not a directory' % self.locale_dir) if not os.path.exists(self.locale_dir): os.makedirs(self.locale_dir)
def __init__(self, timeout): global visit_class visit_class_path = config.get("tools.visit.saprovider.model", "gearshift.visit.savisit.TG_Visit") visit_class = load_class(visit_class_path) if visit_class is None: msg = 'No visit class found for %s' % visit_class_path msg += ', did you run setup.py develop?' log.error(msg) bind_metadata() if visit_class is TG_Visit: mapper(visit_class, visits_table) # base-class' __init__ triggers self.create_model, so mappers need to # be initialized before. super(SqlAlchemyVisitManager, self).__init__(timeout)
def get_catalog(locale, domain = None): """Return translations for given locale.""" if not domain: domain = config.get("i18n.domain", "messages") catalog = _catalogs.get(domain) if not catalog: catalog = _catalogs[domain] = {} messages = catalog.get(locale) if not messages: localedir = get_locale_dir() messages = catalog[locale] = translation(domain=domain, localedir=localedir, languages=[locale]) return messages
def connect(self): global storm_stores if hasattr(cherrypy.thread_data, "store"): return dburi = config.get('storm.dburi') database = create_database(dburi) try: local_store = Store(database) except Exception: log.error("Unable to connect to database: %s" % dburi) cherrypy.engine.exit() return storm_stores.append(local_store) cherrypy.thread_data.store = local_store