本文整理汇总了Python中springpython.context.ApplicationContext.get_object方法的典型用法代码示例。如果您正苦于以下问题:Python ApplicationContext.get_object方法的具体用法?Python ApplicationContext.get_object怎么用?Python ApplicationContext.get_object使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类springpython.context.ApplicationContext
的用法示例。
在下文中一共展示了ApplicationContext.get_object方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: DaoAuthenticationProviderNotHidingUserNotFoundExceptionsTestCase
# 需要导入模块: from springpython.context import ApplicationContext [as 别名]
# 或者: from springpython.context.ApplicationContext import get_object [as 别名]
class DaoAuthenticationProviderNotHidingUserNotFoundExceptionsTestCase(MockTestCase):
def __init__(self, methodName='runTest'):
MockTestCase.__init__(self, methodName)
self.logger = logging.getLogger("springpythontest.providerTestCases.DaoAuthenticationProviderNotHidingUserNotFoundExceptionsTestCase")
def setUp(self):
SecurityContextHolder.setContext(SecurityContext())
self.appContext = ApplicationContext(XMLConfig("support/providerApplicationContext.xml"))
self.auth_manager = self.appContext.get_object("dao_mgr_not_hiding_exceptions")
self.mock = self.mock()
self.appContext.get_object("dataSource").stubConnection.mockCursor = self.mock
def testIocDaoAuthenticationBadUsersDontHideBadCredentialsDisabledUser(self):
self.mock.expects(once()).method("execute").id("#1")
self.mock.expects(once()).method("fetchall").will(return_value([('disableduser', 'password4', False)])).id("#2").after("#1")
self.mock.expects(once()).method("execute").id("#3").after("#2")
self.mock.expects(once()).method("fetchall").will(return_value([('disableduser', 'role1'), ('disableduser', 'blue')])).id("#4").after("#3")
authentication = UsernamePasswordAuthenticationToken(username="disableduser", password="password4")
self.assertRaises(DisabledException, self.auth_manager.authenticate, authentication)
def testIocDaoAuthenticationBadUsersDontHideBadCredentialsEmptyUser(self):
self.mock.expects(once()).method("execute").id("#1")
self.mock.expects(once()).method("fetchall").will(return_value([('emptyuser', '', True)])).id("#2").after("#1")
self.mock.expects(once()).method("execute").id("#3").after("#2")
self.mock.expects(once()).method("fetchall").will(return_value([])).id("#4").after("#3")
authentication = UsernamePasswordAuthenticationToken(username="emptyuser", password="")
self.assertRaises(UsernameNotFoundException, self.auth_manager.authenticate, authentication)
示例2: ttestExportingAServiceThroughIoCWithoutPullingTheIntermediateComponent
# 需要导入模块: from springpython.context import ApplicationContext [as 别名]
# 或者: from springpython.context.ApplicationContext import get_object [as 别名]
def ttestExportingAServiceThroughIoCWithoutPullingTheIntermediateComponent(self):
appContext = ApplicationContext(XMLConfig("support/remotingPyro4TestApplicationContext.xml"))
remoteService1 = appContext.get_object("remoteServiceServer1")
clientSideProxy1 = appContext.get_object("accountServiceClient1")
remoteService2 = appContext.get_object("remoteServiceServer2")
clientSideProxy2 = appContext.get_object("accountServiceClient2")
time.sleep(0.01)
argument1 = ['a', 1, 'b']
self.assertEquals(remoteService1.getData(argument1), "You got remote data => %s" % argument1)
self.assertEquals(remoteService1.getMoreData(argument1), "You got more remote data => %s" % argument1)
self.assertEquals(clientSideProxy1.getData(argument1), "You got remote data => %s" % argument1)
self.assertEquals(clientSideProxy1.getMoreData(argument1), "You got more remote data => %s" % argument1)
routineToRun = "testit"
self.assertEquals(remoteService2.executeOperation(routineToRun), "Operation %s has been carried out" % routineToRun)
self.assertEquals(remoteService2.executeOtherOperation(routineToRun), "Other operation %s has been carried out" % routineToRun)
self.assertEquals(clientSideProxy2.executeOperation(routineToRun), "Operation %s has been carried out" % routineToRun)
self.assertEquals(clientSideProxy2.executeOtherOperation(routineToRun), "Other operation %s has been carried out" % routineToRun)
del(appContext)
示例3: test_multiple_connections
# 需要导入模块: from springpython.context import ApplicationContext [as 别名]
# 或者: from springpython.context.ApplicationContext import get_object [as 别名]
def test_multiple_connections(self):
# 2 clients to the same host/port/db/pool should use the same
# connection
appctx = ApplicationContext(RedisAppConfig())
pool = redis.ConnectionPool()
# NOTE: it is fragile to reference connection_pool property directly
r1 = appctx.get_object('redis_service')
r1.connection_pool=pool
r2 = appctx.get_object('redis_service')
r2.connection_pool=pool
self.assertEquals(r1.connection, r2.connection)
# if one of them switches, they should have
# separate conncetion objects
r2.select(db=10, host='localhost', port=6379)
self.assertNotEqual(r1.connection, r2.connection)
conns = [r1.connection, r2.connection]
conns.sort()
# but returning to the original state shares the object again
r2.select(db=9, host='localhost', port=6379)
self.assertEquals(r1.connection, r2.connection)
# the connection manager should still have just 2 connections
mgr_conns = pool.get_all_connections()
mgr_conns.sort()
self.assertEquals(conns, mgr_conns)
示例4: setupContext
# 需要导入模块: from springpython.context import ApplicationContext [as 别名]
# 或者: from springpython.context.ApplicationContext import get_object [as 别名]
def setupContext(self, username, password):
applicationContext = ApplicationContext(XMLConfig("support/unanimousBasedApplicationContext.xml"))
token = UsernamePasswordAuthenticationToken(username, password)
auth_manager = applicationContext.get_object("auth_manager")
SecurityContextHolder.setContext(SecurityContext())
SecurityContextHolder.getContext().authentication = auth_manager.authenticate(token)
self.sampleService = applicationContext.get_object("sampleService")
self.block1 = SampleBlockOfData("block1")
self.block2 = SampleBlockOfData("block2")
示例5: ReflectionSaltSourceErrorTestCase
# 需要导入模块: from springpython.context import ApplicationContext [as 别名]
# 或者: from springpython.context.ApplicationContext import get_object [as 别名]
class ReflectionSaltSourceErrorTestCase(unittest.TestCase):
def setUp(self):
self.appContext = ApplicationContext(XMLConfig("support/encodingApplicationContext.xml"))
self.user = SaltedUser("user1", "testPassword", True)
def testEncodingWithReflectionSaltSourceNoSuchMethod(self):
saltSource = self.appContext.get_object("reflectionSaltSource2")
self.assertRaises(AuthenticationServiceException, saltSource.get_salt, self.user)
def testEncodingWithReflectionSaltSourceLeftEmpty(self):
saltSource = self.appContext.get_object("reflectionSaltSource3")
self.assertRaises(AuthenticationServiceException, saltSource.get_salt, self.user)
示例6: configure
# 需要导入模块: from springpython.context import ApplicationContext [as 别名]
# 或者: from springpython.context.ApplicationContext import get_object [as 别名]
def configure():
#----- WIRING
GlobalConfiguration.simpyEnv = simpy.Environment()
context = ApplicationContext(GlobalConfiguration.config_xml)
topology = context.get_object("topology")
GlobalConfiguration.topology = topology #reqd for statistic generations
sdn_nfv = context.get_object("nfv_sdn")
sdn_nfv.distribute_information()
topology.wireComponents()
示例7: LdapAuthenticationProviderTestCase
# 需要导入模块: from springpython.context import ApplicationContext [as 别名]
# 或者: from springpython.context.ApplicationContext import get_object [as 别名]
class LdapAuthenticationProviderTestCase(unittest.TestCase):
def __init__(self, methodName='runTest'):
unittest.TestCase.__init__(self, methodName)
self.logger = logging.getLogger("springpythontest.securityLdapTestCases.LdapAuthenticationProviderTestCase")
def setUp(self):
SecurityContextHolder.setContext(SecurityContext())
self.appContext = ApplicationContext(XMLConfig("support/ldapApplicationContext.xml"))
def testGoodUsersBindAuthentication(self):
self.auth_manager = self.appContext.get_object("ldapAuthenticationProvider")
authentication = UsernamePasswordAuthenticationToken(username="bob", password="bobspassword")
SecurityContextHolder.getContext().authentication = self.auth_manager.authenticate(authentication)
self.assertTrue("ROLE_DEVELOPERS" in SecurityContextHolder.getContext().authentication.granted_auths)
def testGoodUsersPasswordAuthentication(self):
self.auth_manager = self.appContext.get_object("ldapAuthenticationProvider2")
authentication = UsernamePasswordAuthenticationToken(username="bob", password="bobspassword")
SecurityContextHolder.getContext().authentication = self.auth_manager.authenticate(authentication)
self.assertTrue("ROLE_DEVELOPERS" in SecurityContextHolder.getContext().authentication.granted_auths)
def testGoodUserWithShaEncoding(self):
self.auth_manager = self.appContext.get_object("ldapAuthenticationProvider2")
authentication = UsernamePasswordAuthenticationToken(username="ben", password="benspassword")
SecurityContextHolder.getContext().authentication = self.auth_manager.authenticate(authentication)
self.assertTrue("ROLE_DEVELOPERS" in SecurityContextHolder.getContext().authentication.granted_auths)
def testWrongPasswordBindAuthentication(self):
self.auth_manager = self.appContext.get_object("ldapAuthenticationProvider")
authentication = UsernamePasswordAuthenticationToken(username="bob", password="wrongpassword")
self.assertRaises(BadCredentialsException, self.auth_manager.authenticate, authentication)
def testWrongPasswordAuthentication(self):
self.auth_manager = self.appContext.get_object("ldapAuthenticationProvider2")
authentication = UsernamePasswordAuthenticationToken(username="bob", password="wrongpassword")
self.assertRaises(BadCredentialsException, self.auth_manager.authenticate, authentication)
def testNonexistentUserBindAuthentication(self):
self.auth_manager = self.appContext.get_object("ldapAuthenticationProvider")
authentication = UsernamePasswordAuthenticationToken(username="nonexistentuser", password="password")
self.assertRaises(BadCredentialsException, self.auth_manager.authenticate, authentication)
def testNonexistentUserPasswordAuthentication(self):
self.auth_manager = self.appContext.get_object("ldapAuthenticationProvider2")
authentication = UsernamePasswordAuthenticationToken(username="nonexistentuser", password="password")
self.assertRaises(BadCredentialsException, self.auth_manager.authenticate, authentication)
def testEmptyPassword(self):
self.auth_manager = self.appContext.get_object("ldapAuthenticationProvider")
authentication = UsernamePasswordAuthenticationToken(username="nonexistentuser", password="")
self.assertRaises(BadCredentialsException, self.auth_manager.authenticate, authentication)
示例8: testWikiServiceWithCaching
# 需要导入模块: from springpython.context import ApplicationContext [as 别名]
# 或者: from springpython.context.ApplicationContext import get_object [as 别名]
def testWikiServiceWithCaching(self):
context = ApplicationContext(WikiProductionAppConfig())
caching_service = context.get_object("caching_service")
wiki_service = context.get_object("wiki_service")
self.assertEquals(len(caching_service.keys()), 0)
wiki_service.statistics(None)
self.assertEquals(len(caching_service.keys()), 0)
wiki_service.get_article("jeff article")
self.assertEquals(len(caching_service.keys()), 1)
wiki_service.store_article("jeff article")
self.assertEquals(len(caching_service.keys()), 0)
示例9: clean_url
# 需要导入模块: from springpython.context import ApplicationContext [as 别名]
# 或者: from springpython.context.ApplicationContext import get_object [as 别名]
def clean_url(self):
url = self.cleaned_data['url']
ctx = ApplicationContext(DAOContext())
org_dao = ctx.get_object('OrganizationDAO')
url_metadata_dao = ctx.get_object('URLMetadataDAO')
try:
domain = UrlUtility().get_domain(url)
except:
raise ValidationError("Oops! We couldn't find information on that domain.")
if org_dao.find(organization_url=domain) or url_metadata_dao.find(domain=domain):
raise ValidationError("Oops! Looks like we already have information on that organization.")
return url
示例10: heatmap_coordinates
# 需要导入模块: from springpython.context import ApplicationContext [as 别名]
# 或者: from springpython.context.ApplicationContext import get_object [as 别名]
def heatmap_coordinates(request):
"""
Gets all the lat/long values for all organizations.
Returns:
List of lat/long coordinates encoded in JSON.
"""
if request.method != 'GET':
return HttpResponseNotAllowed(request)
coords = cache.get('organization_coords_list')
last_update = cache.get('organization_coords_list_last_update')
if not coords or not last_update or (datetime.utcnow() - last_update > REFRESH_COORDS_LIST):
new_coords = []
cache.set('organization_address_list_last_update', datetime.utcnow())
ctx = ApplicationContext(DAOContext())
org_dao = ctx.get_object('OrganizationDAO')
try:
organizations = org_dao.findmany(latlng__exists=True, latlng__ne=[])
except:
logger.error('Error occurred on organization lookup')
return HttpResponseServerError(request)
for org in organizations:
new_coords.append(org.latlng)
coords = MongoJSONEncoder().encode(new_coords)
if len(coords) > 0:
cache.set('organization_coords_list', coords)
return HttpResponse(coords, content_type="application/json")
示例11: process_exception
# 需要导入模块: from springpython.context import ApplicationContext [as 别名]
# 或者: from springpython.context.ApplicationContext import get_object [as 别名]
def process_exception(self, request, exception, spider):
"""
An exception occurred while trying to get a response from the requested URL,
so we need to do cleanup. This means updating the URLMetadata to reflect that
this URL has been checked and queuing a new URL request from the URLFrontier.
"""
# log error
_middleware_logger.error(exception.message)
# update last_visited for failed request
try:
url_dao = URLMetadataDAO()
url_dto = url_dao.find(url=request.url)
if url_dto is not None:
url_dto.last_visited = datetime.utcnow()
url_dao.create_update(url_dto)
except Exception as e:
_middleware_logger.error(e.message)
# queue next url
ctx = ApplicationContext(URLFrontierContext())
url_frontier = ctx.get_object("URLFrontier")
try:
url_frontier_rules = spider.url_frontier_rules
except Exception as e:
_middleware_logger.error('ERROR: Spider without url_frontier_rules defined')
return None
next_url = url_frontier.next_url(url_frontier_rules)
if next_url is not None:
return Request(next_url.url, dont_filter=True)
return None
示例12: test_contact_scraper
# 需要导入模块: from springpython.context import ApplicationContext [as 别名]
# 或者: from springpython.context.ApplicationContext import get_object [as 别名]
def test_contact_scraper(self):
ctx = ApplicationContext(TestableDocumentScraperContext())
test_files = [
"httpwwwprajwalaindiacomcontactushtml",
]
contact_scraper = ctx.get_object('ContactScraper')
contacts = []
for input_file in test_files:
response = file_to_response(input_file)
if response is not None:
ret = contact_scraper.parse(response)
if isinstance(ret, type([])):
contacts = contacts + ret
else:
contacts.append(ret)
assert_list = [{
'email': 'test',
'first_name': 'test',
'last_name': 'test',
'organization': {'name': 'test'},
'position': 'test',
'phones': ['test'],
}]
for test in assert_list:
self.assertIn(test, contacts, 'Contact \'' + str(test) + '\' not found')
示例13: InMemoryDaoAuthenticationProviderTestCase
# 需要导入模块: from springpython.context import ApplicationContext [as 别名]
# 或者: from springpython.context.ApplicationContext import get_object [as 别名]
class InMemoryDaoAuthenticationProviderTestCase(unittest.TestCase):
def setUp(self):
SecurityContextHolder.setContext(SecurityContext())
self.appContext = ApplicationContext(XMLConfig("support/providerApplicationContext.xml"))
self.auth_manager = self.appContext.get_object("inMemoryDaoAuthenticationManager")
def __init__(self, methodName='runTest'):
unittest.TestCase.__init__(self, methodName)
self.logger = logging.getLogger("springpythontest.providerTestCases.InMemoryDaoAuthenticationProviderTestCase")
def testIoCDaoAuthenticationGoodUsers(self):
authentication = UsernamePasswordAuthenticationToken(username="user1", password="password1")
SecurityContextHolder.getContext().authentication = self.auth_manager.authenticate(authentication)
self.assertTrue("role1" in SecurityContextHolder.getContext().authentication.granted_auths)
self.assertTrue("blue" in SecurityContextHolder.getContext().authentication.granted_auths)
authentication = UsernamePasswordAuthenticationToken(username="user2", password="password2")
SecurityContextHolder.getContext().authentication = self.auth_manager.authenticate(authentication)
self.assertTrue("role1" in SecurityContextHolder.getContext().authentication.granted_auths)
self.assertTrue("orange" in SecurityContextHolder.getContext().authentication.granted_auths)
authentication = UsernamePasswordAuthenticationToken(username="adminuser", password="password3")
SecurityContextHolder.getContext().authentication = self.auth_manager.authenticate(authentication)
self.assertTrue("role1" in SecurityContextHolder.getContext().authentication.granted_auths)
self.assertTrue("admin" in SecurityContextHolder.getContext().authentication.granted_auths)
def testIocDaoAuthenticationBadUsersWithHiddenExceptions(self):
authentication = UsernamePasswordAuthenticationToken(username="nonexistent", password="password999")
self.assertRaises(BadCredentialsException, self.auth_manager.authenticate, authentication)
authentication = UsernamePasswordAuthenticationToken(username="disableduser", password="password4")
self.assertRaises(DisabledException, self.auth_manager.authenticate, authentication)
authentication = UsernamePasswordAuthenticationToken(username="emptyuser", password="")
self.assertRaises(BadCredentialsException, self.auth_manager.authenticate, authentication)
示例14: testIoCGeneralQueryWithDictionaryRowMapper
# 需要导入模块: from springpython.context import ApplicationContext [as 别名]
# 或者: from springpython.context.ApplicationContext import get_object [as 别名]
def testIoCGeneralQueryWithDictionaryRowMapper(self):
appContext = ApplicationContext(XMLConfig("support/databaseTestSqliteApplicationContext.xml"))
factory = appContext.get_object("connection_factory")
databaseTemplate = DatabaseTemplate(factory)
databaseTemplate.execute("DROP TABLE IF EXISTS animal")
databaseTemplate.execute("""
CREATE TABLE animal (
id serial PRIMARY KEY,
name VARCHAR(11),
category VARCHAR(20),
population integer
)
""")
factory.commit()
databaseTemplate.execute("DELETE FROM animal")
factory.commit()
self.assertEquals(len(databaseTemplate.query_for_list("SELECT * FROM animal")), 0)
databaseTemplate.execute("INSERT INTO animal (name, category, population) VALUES ('snake', 'reptile', 1)")
databaseTemplate.execute("INSERT INTO animal (name, category, population) VALUES ('racoon', 'mammal', 0)")
databaseTemplate.execute ("INSERT INTO animal (name, category, population) VALUES ('black mamba', 'kill_bill_viper', 1)")
databaseTemplate.execute ("INSERT INTO animal (name, category, population) VALUES ('cottonmouth', 'kill_bill_viper', 1)")
factory.commit()
self.assertEquals(len(databaseTemplate.query_for_list("SELECT * FROM animal")), 4)
results = databaseTemplate.query("select * from animal", rowhandler=DictionaryRowMapper())
示例15: testExportingAServiceUsingNonStandardPortsWithConstructorArgsByAttribute
# 需要导入模块: from springpython.context import ApplicationContext [as 别名]
# 或者: from springpython.context.ApplicationContext import get_object [as 别名]
def testExportingAServiceUsingNonStandardPortsWithConstructorArgsByAttribute(self):
appContext = ApplicationContext(XMLConfig("support/remotingPyroTestApplicationContext.xml"))
time.sleep(0.01)
remoteService1 = appContext.get_object("remoteServiceServer1")
serviceExporter5 = appContext.get_object("serviceExporter5")
clientSideProxy5 = appContext.get_object("accountServiceClient5")
time.sleep(0.01)
argument = ['a', 1, 'b']
self.assertEquals(remoteService1.getData(argument), "You got remote data => %s" % argument)
self.assertEquals(remoteService1.getMoreData(argument), "You got more remote data => %s" % argument)
self.assertEquals(clientSideProxy5.getData(argument), "You got remote data => %s" % argument)
self.assertEquals(clientSideProxy5.getMoreData(argument), "You got more remote data => %s" % argument)