本文整理汇总了Python中paste.registry.Registry.prepare方法的典型用法代码示例。如果您正苦于以下问题:Python Registry.prepare方法的具体用法?Python Registry.prepare怎么用?Python Registry.prepare使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类paste.registry.Registry
的用法示例。
在下文中一共展示了Registry.prepare方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setUp
# 需要导入模块: from paste.registry import Registry [as 别名]
# 或者: from paste.registry.Registry import prepare [as 别名]
def setUp(self):
super(AutoCompleterTest, self).setUp()
# Création d'un environnement WSGI pour les tests.
# Par défaut, l'utilisateur n'est pas identifé
# et n'appartient donc à aucun groupe.
environ = {'repoze.what.credentials': {
'groups': [],
}
}
request = Request(environ)
config = VigiloAppConfig('TurboGears')
config.init_managers_predicate()
registry = Registry()
registry.prepare()
registry.register(tg.request, request)
registry.register(tg.config, config)
self.ctrl = AutoCompleteController()
# Par défaut, l'utilisateur n'est pas identifé.
tg.request.identity = {'repoze.who.userid': None}
self.accounts = (
(u'manager', u'managers'), # Accès à tout (manager)
(u'nobody', u'nobody'), # Accès à rien.
(u'direct', u'direct'), # Permissions directe sur l'objet.
(u'indirect', u'indirect'), # Permissions indirectes sur l'objet.
)
# Création des comptes utilisateurs.
for username, group in self.accounts:
functions.add_user(username, u'%[email protected]' % username,
u'', u'', group)
# Création de l'arborescence des objets.
self.create_deps()
示例2: HelloworldCommand
# 需要导入模块: from paste.registry import Registry [as 别名]
# 或者: from paste.registry.Registry import prepare [as 别名]
class HelloworldCommand(Command):
'''
A base class to use when the full Pylons environment should be loaded
'''
summary = __doc__.split("\n") [0]
usage = __doc__
group_name = "helloworld"
def __init__(self, name):
Command.__init__(self, name)
self.parser = Command.standard_parser(verbose=False)
self.parser.add_option('-c', '--config', dest='config', default='development.ini', help='Config file to use.')
return
def command(self):
pass
def _load_config(self):
from paste.deploy import appconfig
if not self.options.config:
msg = 'No config file supplied'
raise self.BadCommand(msg)
self.filename = os.path.abspath(self.options.config)
if not os.path.exists(self.filename):
raise AssertionError('Config filename %r does not exist.' % self.filename)
fileConfig (self.filename)
conf = appconfig('config:' + self.filename)
# We have now loaded the config. Now we can import helloworld for the first time.
from helloworld.config.environment import load_environment
load_environment (conf.global_conf, conf.local_conf)
self.registry = Registry()
self.registry.prepare()
return
示例3: main
# 需要导入模块: from paste.registry import Registry [as 别名]
# 或者: from paste.registry.Registry import prepare [as 别名]
def main():
parser = argparse.ArgumentParser(description = __doc__)
parser.add_argument('config', help = 'path of configuration file')
parser.add_argument('-v', '--verbose', action = 'store_true', help = 'increase output verbosity')
args = parser.parse_args()
# logging.basicConfig(level = logging.DEBUG if args.verbose else logging.WARNING, stream = sys.stdout)
logging.basicConfig(level = logging.INFO if args.verbose else logging.WARNING, stream = sys.stdout)
site_conf = appconfig('config:{}'.format(os.path.abspath(args.config)))
load_environment(site_conf.global_conf, site_conf.local_conf)
registry = Registry()
registry.prepare()
registry.register(pylons.translator, MockTranslator())
plugins.load('synchronous_search')
model.repo.new_revision()
for package_extra in model.Session.query(model.PackageExtra).filter(
model.PackageExtra.key == 'supplier_id',
model.PackageExtra.package_id.in_(
model.Session.query(model.Package.id).filter(model.Package.name.like('%-fork-%'))),
):
model.Session.delete(package_extra)
model.repo.commit_and_remove()
return 0
示例4: main
# 需要导入模块: from paste.registry import Registry [as 别名]
# 或者: from paste.registry.Registry import prepare [as 别名]
def main():
parser = argparse.ArgumentParser(description = __doc__)
parser.add_argument('config', help = 'path of configuration file')
parser.add_argument('-v', '--verbose', action = 'store_true', help = 'increase output verbosity')
args = parser.parse_args()
# logging.basicConfig(level = logging.DEBUG if args.verbose else logging.WARNING, stream = sys.stdout)
logging.basicConfig(level = logging.INFO if args.verbose else logging.WARNING, stream = sys.stdout)
site_conf = appconfig('config:{}'.format(os.path.abspath(args.config)))
load_environment(site_conf.global_conf, site_conf.local_conf)
registry = Registry()
registry.prepare()
registry.register(pylons.translator, MockTranslator())
plugins.load('synchronous_search')
model.repo.new_revision()
for package_extra in model.Session.query(model.PackageExtra).filter(
model.PackageExtra.key == 'territorial_coverage_granularity',
model.PackageExtra.value == 'france',
):
package = package_extra.package
if package.private or package.state != 'active':
log.warning(u'Territorial coverage granularity of package {} must be manually corrected'.format(
package.name))
continue
package_extra.value = 'pays'
model.repo.commit_and_remove()
return 0
示例5: CkanCommand
# 需要导入模块: from paste.registry import Registry [as 别名]
# 或者: from paste.registry.Registry import prepare [as 别名]
class CkanCommand(paste.script.command.Command):
parser = paste.script.command.Command.standard_parser(verbose=True)
parser.add_option('-c', '--config', dest='config',
default='development.ini', help='Config file to use.')
parser.add_option('-f', '--file',
action='store',
dest='file_path',
help="File to dump results to (if needed)")
default_verbosity = 1
group_name = 'ckan'
def _load_config(self):
from paste.deploy import appconfig
from ckan.config.environment import load_environment
if not self.options.config:
msg = 'No config file supplied'
raise self.BadCommand(msg)
self.filename = os.path.abspath(self.options.config)
if not os.path.exists(self.filename):
raise AssertionError('Config filename %r does not exist.' % self.filename)
fileConfig(self.filename)
conf = appconfig('config:' + self.filename)
load_environment(conf.global_conf, conf.local_conf)
self.registry=Registry()
self.registry.prepare()
import pylons
self.translator_obj = MockTranslator()
self.registry.register(pylons.translator, self.translator_obj)
def _setup_app(self):
cmd = paste.script.appinstall.SetupCommand('setup-app')
cmd.run([self.filename])
示例6: setup_environment_and_database
# 需要导入模块: from paste.registry import Registry [as 别名]
# 或者: from paste.registry.Registry import prepare [as 别名]
def setup_environment_and_database(env_dir=None, enabled_plugins=''):
global_config = {}
env_dir = env_dir or '/invalid'
app_instance_secret = secret.secret_string()
app_config = {
'plugins': enabled_plugins,
'sqlalchemy.url': 'sqlite://',
'layout_template': 'layout',
'external_template': 'false',
'image_dir': os.path.join(env_dir, 'images'),
'media_dir': os.path.join(env_dir, 'media'),
'beaker.session.secret': app_instance_secret,
'sa_auth.cookie_secret': app_instance_secret,
}
pylons_config = load_environment(global_config, app_config)
paste_registry = Registry()
paste_registry.prepare()
app_globals = pylons_config['pylons.app_globals']
register_instance(paste_registry, 'app_globals', app_globals)
pylons_config.update({
'paste.registry': paste_registry,
'pylons.pylons': pylons,
})
metadata.create_all(bind=DBSession.bind, checkfirst=True)
return pylons_config
示例7: register_translator
# 需要导入模块: from paste.registry import Registry [as 别名]
# 或者: from paste.registry.Registry import prepare [as 别名]
def register_translator():
from paste.registry import Registry
import pylons
registry = Registry()
registry.prepare()
translator_obj = MockTranslator()
registry.register(pylons.translator, translator_obj)
log.info('Translator object was registered for the background job')
示例8: main
# 需要导入模块: from paste.registry import Registry [as 别名]
# 或者: from paste.registry.Registry import prepare [as 别名]
def main():
parser = argparse.ArgumentParser(description = __doc__)
parser.add_argument('config', help = 'path of configuration file')
parser.add_argument('-v', '--verbose', action = 'store_true', help = 'increase output verbosity')
args = parser.parse_args()
# logging.basicConfig(level = logging.DEBUG if args.verbose else logging.WARNING, stream = sys.stdout)
logging.basicConfig(level = logging.INFO if args.verbose else logging.WARNING, stream = sys.stdout)
site_conf = appconfig('config:{}'.format(os.path.abspath(args.config)))
load_environment(site_conf.global_conf, site_conf.local_conf)
registry = Registry()
registry.prepare()
registry.register(pylons.translator, MockTranslator())
plugins.load('synchronous_search')
# model.repo.new_revision()
# for resource in model.Session.query(model.Resource).filter(
# model.Resource.url.like('%etalab2.fr%'),
# ):
# url = resource.url
# if url.startswith('http://ckan.etalab2.fr/'):
# resource.url = resource.url.replace('http://ckan.etalab2.fr/', 'http://www.data.gouv.fr/fr/')
# elif url.startswith('http://ckan-hetic.etalab2.fr/'):
# resource.url = resource.url.replace('http://ckan-hetic.etalab2.fr/', 'http://www.data.gouv.fr/fr/')
# elif url.startswith('http://www.etalab2.fr/'):
# resource.url = resource.url.replace('http://www.etalab2.fr/', 'http://www.data.gouv.fr/')
# else:
# print resource.url
# model.repo.commit_and_remove()
# model.repo.new_revision()
# for resource in model.Session.query(model.Resource).filter(
# model.Resource.url.like('%www.data.gouv.fr%'),
# ):
# if resource.url.startswith('http://www.data.gouv.fr/') and not resource.url.startswith('http://www.data.gouv.fr/var'):
# resource.url = resource.url.replace('http://www.data.gouv.fr/', 'http://new.data.gouv.fr/')
# model.repo.commit_and_remove()
model.repo.new_revision()
for resource in model.Session.query(model.Resource).filter(
model.Resource.url.like('http://new.data.gouv.fr/%'),
):
resource.url = resource.url.replace('http://new.data.gouv.fr/', 'https://www.data.gouv.fr/')
model.repo.commit_and_remove()
model.repo.new_revision()
for resource in model.Session.query(model.Resource).filter(
model.Resource.url.like('https://new.data.gouv.fr/%'),
):
resource.url = resource.url.replace('https://new.data.gouv.fr/', 'https://www.data.gouv.fr/')
model.repo.commit_and_remove()
return 0
示例9: _test_restorer
# 需要导入模块: from paste.registry import Registry [as 别名]
# 或者: from paste.registry.Registry import prepare [as 别名]
def _test_restorer(stack, data):
# We need to test the request's specific Registry. Initialize it here so we
# can use it later (RegistryManager will re-use one preexisting in the
# environ)
registry = Registry()
extra_environ={'paste.throw_errors': False,
'paste.registry': registry}
request_id = restorer.get_request_id(extra_environ)
app = TestApp(stack)
res = app.get('/', extra_environ=extra_environ, expect_errors=True)
# Ensure all the StackedObjectProxies are empty after the RegistryUsingApp
# raises an Exception
for stacked, proxied_obj, test_cleanup in data:
only_key = list(proxied_obj.keys())[0]
try:
assert only_key not in stacked
assert False
except TypeError:
# Definitely empty
pass
# Ensure the StackedObjectProxies & Registry 'work' in the simulated
# EvalException context
replace = {'replace': 'dict'}
new = {'new': 'object'}
restorer.restoration_begin(request_id)
try:
for stacked, proxied_obj, test_cleanup in data:
# Ensure our original data magically re-appears in this context
only_key, only_val = list(proxied_obj.items())[0]
assert only_key in stacked and stacked[only_key] == only_val
# Ensure the Registry still works
registry.prepare()
registry.register(stacked, new)
assert 'new' in stacked and stacked['new'] == 'object'
registry.cleanup()
# Back to the original (pre-prepare())
assert only_key in stacked and stacked[only_key] == only_val
registry.replace(stacked, replace)
assert 'replace' in stacked and stacked['replace'] == 'dict'
if test_cleanup:
registry.cleanup()
try:
stacked._current_obj()
assert False
except TypeError:
# Definitely empty
pass
finally:
restorer.restoration_end()
示例10: _paste_registry
# 需要导入模块: from paste.registry import Registry [as 别名]
# 或者: from paste.registry.Registry import prepare [as 别名]
def _paste_registry(pylons_request):
"Internal helper method to get a new registry."
paste_registry = None
is_request_registered = is_object_registered(pylons_request)
if is_request_registered:
paste_registry = pylons_request.environ.get('paste.registry')
if paste_registry is None:
paste_registry = Registry()
paste_registry.prepare()
if is_request_registered:
pylons_request.environ['paste.registry'] = paste_registry
return paste_registry
示例11: register_translator
# 需要导入模块: from paste.registry import Registry [as 别名]
# 或者: from paste.registry.Registry import prepare [as 别名]
def register_translator():
# Register a translator in this thread so that
# the _() functions in logic layer can work
from paste.registry import Registry
from pylons import translator
from ckan.lib.cli import MockTranslator
global registry
registry = Registry()
registry.prepare()
global translator_obj
translator_obj = MockTranslator()
registry.register(translator, translator_obj)
示例12: main
# 需要导入模块: from paste.registry import Registry [as 别名]
# 或者: from paste.registry.Registry import prepare [as 别名]
def main():
parser = argparse.ArgumentParser(description = __doc__)
parser.add_argument('config', help = 'path of configuration file')
parser.add_argument('-t', '--territoria-url', help = 'Territoria URL', required = True)
parser.add_argument('-v', '--verbose', action = 'store_true', help = 'increase output verbosity')
args = parser.parse_args()
# logging.basicConfig(level = logging.DEBUG if args.verbose else logging.WARNING, stream = sys.stdout)
logging.basicConfig(level = logging.INFO if args.verbose else logging.WARNING, stream = sys.stdout)
site_conf = appconfig('config:{}'.format(os.path.abspath(args.config)))
load_environment(site_conf.global_conf, site_conf.local_conf)
registry = Registry()
registry.prepare()
registry.register(pylons.translator, MockTranslator())
plugins.load('synchronous_search')
model.repo.new_revision()
kind_code_name_by_kind_code = {}
for package_extra in model.Session.query(model.PackageExtra).filter(
model.PackageExtra.key == 'territorial_coverage',
):
if package_extra.value == 'Coutry/FR':
kind_code_name = 'Country/FR/FRANCE'
elif package_extra.value == 'InternationalOrganization/EU':
kind_code_name = 'InternationalOrganization/UE/UNION EUROPEENNE'
elif package_extra.value.count('/') == 1:
kind_code_name = kind_code_name_by_kind_code.get(package_extra.value)
if kind_code_name is None:
kind, code = package_extra.value.split('/')
try:
response = urllib2.urlopen(urlparse.urljoin(args.territoria_url,
'/api/v1/territory?{}'.format(urllib.urlencode(dict(
code = code,
kind = kind,
), doseq = True))))
except urllib2.HTTPError, response:
print package_extra.value
raise
response_dict = json.loads(response.read())
main_postal_distribution = response_dict['data']['main_postal_distribution']
kind_code_name_by_kind_code[package_extra.value] = kind_code_name = u'/'.join([kind, code,
main_postal_distribution])
print kind_code_name
else:
continue
package = package_extra.package
if package.private or package.state != 'active':
log.warning(u'Territorial coverage of package {} must be manually corrected'.format(package.name))
continue
package_extra.value = kind_code_name
开发者ID:etalab,项目名称:etalab-ckan-scripts,代码行数:55,代码来源:add_main_postal_distribution_to_territorial_coverage.py
示例13: load_config
# 需要导入模块: from paste.registry import Registry [as 别名]
# 或者: from paste.registry.Registry import prepare [as 别名]
def load_config(path):
import paste.deploy
conf = paste.deploy.appconfig('config:' + path)
import ckan, pylons
ckan.config.environment.load_environment(conf.global_conf,
conf.local_conf)
from ckan.lib.cli import MockTranslator
from paste.registry import Registry
registry=Registry()
registry.prepare()
translator_obj=MockTranslator()
registry.register(pylons.translator, translator_obj)
示例14: command
# 需要导入模块: from paste.registry import Registry [as 别名]
# 或者: from paste.registry.Registry import prepare [as 别名]
def command(dry_run=False):
from ckan import model
from ckanext.dgu.lib.resource_formats import match
from running_stats import StatsList
# Register a translator in this thread so that
# the _() functions in logic layer can work
from ckan.lib.cli import MockTranslator
registry=Registry()
registry.prepare()
translator_obj=MockTranslator()
registry.register(translator, translator_obj)
if not dry_run:
model.repo.new_revision()
# Add canonised formats to map
for format_ in res_type_map.keys():
res_type_map[canonise(format_)] = res_type_map[format_]
log.info('Tidying resource types')
stats = StatsList()
res_query = model.Session.query(model.Resource)
log.info('Tidying formats. Resources=%i Canonised formats=%i',
res_query.count(), len(set(res_type_map.values())))
for res in res_query:
canonised_fmt = canonise(res.format or '')
if canonised_fmt in res_type_map:
improved_fmt = res_type_map[canonised_fmt]
else:
improved_fmt = tidy(res.format)
match_ = match(improved_fmt)
if match_:
improved_fmt = match_
if (improved_fmt or '') != (res.format or ''):
if not dry_run:
res.format = improved_fmt
stats.add(improved_fmt, res.format)
else:
stats.add('No change', res.format)
if not dry_run:
model.repo.commit_and_remove()
log.info('Stats report: %r', stats.report())
print stats.report()
log.info('Warnings (%i): %r', len(warnings), warnings)
示例15: fake_request
# 需要导入模块: from paste.registry import Registry [as 别名]
# 或者: from paste.registry.Registry import prepare [as 别名]
def fake_request(pylons_config, server_name='mediadrop.example', language='en',
method='GET', request_uri='/', post_vars=None):
app_globals = pylons_config['pylons.app_globals']
pylons.app_globals._push_object(app_globals)
if post_vars and method.upper() != 'POST':
raise ValueError('You must not specify post_vars for request method %r' % method)
wsgi_environ = create_wsgi_environ('http://%s%s' % (server_name, request_uri),
method.upper(), request_body=post_vars)
request = Request(wsgi_environ, charset='utf-8')
request.language = language
request.settings = app_globals.settings
pylons.request._push_object(request)
response = Response(content_type='application/xml', charset='utf-8')
pylons.response._push_object(response)
session = SessionObject(wsgi_environ)
pylons.session._push_object(session)
routes_url = URLGenerator(pylons_config['routes.map'], wsgi_environ)
pylons.url._push_object(routes_url)
# TODO: Use ContextObj() for Pylons 0.10
tmpl_context = AttribSafeContextObj()
tmpl_context.paginators = Bunch()
pylons.tmpl_context._push_object(tmpl_context)
# some parts of Pylons (e.g. Pylons.controllers.core.WSGIController)
# use the '.c' alias instead.
pylons.c = pylons.tmpl_context
paste_registry = Registry()
paste_registry.prepare()
engines = create_tw_engine_manager(app_globals)
host_framework = PylonsHostFramework(engines=engines)
paste_registry.register(tw.framework, host_framework)
mediacore_i18n_path = os.path.join(os.path.dirname(mediacore.__file__), 'i18n')
translator = Translator(language, dict(mediacore=mediacore_i18n_path))
# not sure why but sometimes pylons.translator is not a StackedObjectProxy
# but just a regular Translator.
if not hasattr(pylons.translator, '_push_object'):
pylons.translator = StackedObjectProxy()
paste_registry.replace(pylons.translator, translator)
wsgi_environ.update({
'pylons.pylons': pylons,
'paste.registry': paste_registry,
})
return request