本文整理汇总了Python中twisted.python.components.registerAdapter函数的典型用法代码示例。如果您正苦于以下问题:Python registerAdapter函数的具体用法?Python registerAdapter怎么用?Python registerAdapter使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了registerAdapter函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _duplicateAdapterForClassOrInterfaceAllowed
def _duplicateAdapterForClassOrInterfaceAllowed(self, original):
"""
Verify that when C{components.ALLOW_DUPLICATES} is set to C{True}, new
adapter registrations for a particular from-type/interface and
to-interface pair replace older registrations.
"""
firstAdapter = lambda o: False
secondAdapter = lambda o: True
class TheInterface(Interface):
pass
components.registerAdapter(firstAdapter, original, TheInterface)
components.ALLOW_DUPLICATES = True
try:
components.registerAdapter(secondAdapter, original, TheInterface)
self.assertIs(
components.getAdapterFactory(original, TheInterface, None),
secondAdapter)
finally:
components.ALLOW_DUPLICATES = False
# It should be rejected again at this point
self.assertRaises(
ValueError,
components.registerAdapter,
firstAdapter, original, TheInterface)
self.assertIs(
components.getAdapterFactory(original, TheInterface, None),
secondAdapter)
示例2: run
def run():
args = PARSER.parse_args()
# Unpack values. Each should be a list of one item (hence the
# comma. Yay list unpacking)
private_key, = args.private_key
public_key, = args.public_key
webserver_address, = args.webserver_address
webserver_user, = args.webserver_user
webserver_password, = args.webserver_password
port = int(args.port)
log.startLogging(sys.stderr)
log.startLogging(open('gitssh.log', 'w'))
components.registerAdapter(GitSession, GitConchUser, ISession)
# Set up authorization
GitServer.meta = GitMeta(webserver_address,
webserver_user, webserver_password)
GitServer.portal = Portal(GitRealm(GitServer.meta))
GitServer.portal.registerChecker(TeamPasswordChecker(GitServer.meta))
# Instantiate a server
server = GitServer(os.path.abspath(private_key),
os.path.abspath(public_key))
# Start listening
reactor.listenTCP(port, server)
reactor.run()
示例3: makeService
def makeService(config):
components.registerAdapter(
GitSession,
GitAvatar,
session.ISession)
with open(config['conf']) as f:
conf = yaml.load(f.read())
port = int(conf.get('port', 22))
host_key = conf.get('host_key')
driver_key = conf.get('driver', 'example')
log.msg('Using driver: \'%s\'' % driver_key)
mgr = driver.DriverManager(
namespace='gitserver.driver',
name=driver_key,
invoke_on_load=False
)
portal = Portal(GitRealm(mgr))
portal.registerChecker(GitPublicKeyChecker(mgr))
# factory.SSHFactory takes no arguments, so unlike the
# websocket server, we will assign portal on the class
# rather than through the constructor.
# TypeError: this constructor takes no arguments
# is raised if we pass portal GitFactory(portal)
GitFactory.portal = portal
GitSession.driver_key = driver_key
return internet.TCPServer(port, GitFactory(host_key=host_key))
示例4: start
def start():
from checker import PublicKeyCredentialsChecker
from factory import ForwardFactory
from realm import ForwardRealm
from session import ForwardSession
from twisted.conch.ssh import session
from twisted.cred import portal
from twisted.internet import reactor
from twisted.python import components, log
from twisted.web import server
import sys
from user import ForwardUser
from conf import config
import web
log.startLogging(sys.stderr)
components.registerAdapter(ForwardSession, ForwardUser, session.ISession)
portal = portal.Portal(ForwardRealm())
portal.registerChecker(PublicKeyCredentialsChecker())
ForwardFactory.portal = portal
print "running server on %s:%s" % (config['SSH_INTERFACE'],config['SSH_PORT'])
reactor.listenTCP(
port=config['SSH_PORT'],
interface=config['SSH_INTERFACE'],
factory=ForwardFactory()
)
reactor.listenTCP(port=config['WEB_PORT'],
interface=config['WEB_INTERFACE'],
factory=server.Site(web.MainSite()))
reactor.run()
示例5: setUp
def setUp(self):
db = inmemory.ReadOnlyInMemoryLDAPEntry("", {})
com = db.addChild("dc=com", {"objectClass": ["dcObject"], "dc": ["com"]})
com.addChild("dc=example", {"objectClass": ["dcObject"], "dc": ["example"], "subschemaSubentry": ["cn=schema"]})
db.addChild(
"cn=schema",
{
"objectClass": ["TODO"],
"cn": ["schema"],
"attributeTypes": [test_schema.AttributeType_KnownValues.knownValues[0][0]],
"objectClasses": [
test_schema.OBJECTCLASSES["organization"],
test_schema.OBJECTCLASSES["organizationalUnit"],
],
},
)
class LDAPServerFactory(protocol.ServerFactory):
protocol = ldapserver.LDAPServer
def __init__(self, root):
self.root = root
components.registerAdapter(lambda x: x.root, LDAPServerFactory, interfaces.IConnectedLDAPEntry)
serverFactory = LDAPServerFactory(db)
self.client = ldapclient.LDAPClient()
server = serverFactory.buildProtocol(address.IPv4Address("TCP", "localhost", "1024"))
util.returnConnected(server, self.client)
示例6: check_config_base
def check_config_base():
from mypkg import config, interfaces, usesconfig
components.registerAdapter(
AdaptRunningConfigToMyConfig, config.MyConfig, IMyConfig)
print usesconfig.do_a_config_thing()
示例7: setUp
def setUp(self):
db = inmemory.ReadOnlyInMemoryLDAPEntry('', {})
com = db.addChild('dc=com',
{'objectClass': ['dcObject'],
'dc': ['com'],
})
com.addChild('dc=example',
{'objectClass': ['dcObject'],
'dc': ['example'],
'subschemaSubentry': ['cn=schema'],
})
db.addChild('cn=schema',
{'objectClass': ['TODO'],
'cn': ['schema'],
'attributeTypes': [test_schema.AttributeType_KnownValues.knownValues[0][0]],
'objectClasses': [test_schema.OBJECTCLASSES['organization'],
test_schema.OBJECTCLASSES['organizationalUnit'],
],
})
class LDAPServerFactory(protocol.ServerFactory):
protocol = ldapserver.LDAPServer
def __init__(self, root):
self.root = root
components.registerAdapter(lambda x: x.root,
LDAPServerFactory,
interfaces.IConnectedLDAPEntry)
serverFactory = LDAPServerFactory(db)
self.client = ldapclient.LDAPClient()
server = serverFactory.buildProtocol(address.IPv4Address('TCP', 'localhost', '1024'))
util.returnConnected(server, self.client)
示例8: test_basic
def test_basic(self):
"""
Registered adapters can be used to adapt classes to an interface.
"""
components.registerAdapter(MetaAdder, MetaNumber, IMeta)
n = MetaNumber(1)
self.assertEqual(IMeta(n).add(1), 2)
示例9: main
def main(argv=sys.argv[1:]):
parser = argparse.ArgumentParser()
parser.add_argument(
'-c',
'--config',
help=(
'Path to the configuration file. If not specified then the '
'lookup order will check for a HADOUKN_GIT_CONFIG environ '
'variable, then fallback to .hadoukngitrc in the CWD.'
),
default='hadoukngit.ini'
)
args = parser.parse_args(args=argv)
cfg_path = args.config
if cfg_path is not None and not os.path.exists(cfg_path):
print('Invalid path "{}" specified for the config file.'
.format(cfg_path), file=sys.stderr)
return 1
config = get_config(cfg_path)
settings = config.get_dict()
factory = SSHFactory(settings)
# adapting User to GitSession which implements ISession
components.registerAdapter(GitSession, User, ISession)
port = int(settings['hadoukngit']['port'])
# Run the server
logger.info('Serving on localhost:%s...' % port)
reactor.listenTCP(port, factory)
reactor.run()
示例10: registerCustomFieldSerializer
def registerCustomFieldSerializer(serializerClass, typeClass):
"""Register a custom field serializer for a specific type.
"""
registerAdapter(
serializerClass, typeClass, igwt.ICustomFieldSerializer
)
registerTypeClass(typeClass)
示例11: _registerAdapterForClassOrInterface
def _registerAdapterForClassOrInterface(self, original):
adapter = lambda o: None
class TheInterface(Interface):
pass
components.registerAdapter(adapter, original, TheInterface)
self.assertIdentical(
components.getAdapterFactory(original, TheInterface, None),
adapter)
示例12: load
def load(S):
for line in S.split('\n'):
line = line.strip()
if line and not line.startswith('#'):
(a, o, i) = line.split()
registerAdapter(_namedAnyWithBuiltinTranslation(a),
_namedAnyWithBuiltinTranslation(clean(o)),
_namedAnyWithBuiltinTranslation(i))
示例13: testComponentized
def testComponentized(self):
components.registerAdapter(Adept, Compo, IAdept)
components.registerAdapter(Elapsed, Compo, IElapsed)
c = Compo()
assert c.getComponent(IAdept).adaptorFunc() == (1, 1)
assert c.getComponent(IAdept).adaptorFunc() == (2, 2)
assert IElapsed(IAdept(c)).elapsedFunc() == 1
示例14: check_app_inherited
def check_app_inherited():
from otherpkg import config
class OtherApp(object):
def get_config(self):
return "config.name = 'other app'"
components.registerAdapter(
AdaptRunningAppToMyApp, OtherApp, IMyApp)
示例15: register
def register():
"""Register this component
"""
try:
components.registerAdapter(MambaSQLAdapter, MySQL, IMambaSQL)
except ValueError:
# component already registered
pass