我已经离开了我的舒适区,我有点困惑我应该如何登录。
Autobahn 提供了一种使用 RPC 调用 Python 服务器的方法,但是 Twisted 似乎只提供了有关如何将 Twisted 用于客户端的文档。
为了正确解释我的意思,这是代码:
在 Javascript 中,您可以像这样调用 RPC 函数:
sess.call(url, user, pass)
Python客户端代码:
from twisted.spread import pb
from twisted.internet import reactor
from twisted.cred import credentials
class Client(pb.Referenceable):
def remote_print(self, message):
print message
def connect(self):
factory = pb.PBClientFactory()
reactor.connectTCP("localhost", 8800, factory)
def1 = factory.login(credentials.UsernamePassword("Bob", "secret"),
client=self)
def1.addCallback(self.connected)
reactor.run()
def connected(self, perspective):
self.perspective = perspective
d = perspective.callRemote("joinGroup", "#Magic")
d.addCallback(self.gotGroup)
def gotGroup(self, group):
d = group.callRemote("send", "Test message.")
d.addCallback(self.shutdown)
def shutdown(self, result):
reactor.stop()
Client().connect()
Python服务器代码:
from zope.interface import implements
from twisted.cred import portal, checkers
from twisted.spread import pb
from twisted.internet import reactor
class ChatServer:
def __init__(self):
self.groups = {'#Magic':Group('#Magic')} # indexed by name
def joinGroup(self, groupname, user):
if self.groups.has_key(groupname):
self.groups[groupname].addUser(user)
return self.groups[groupname] or None
class ChatRealm:
implements(portal.IRealm)
def requestAvatar(self, avatarID, mind, *interfaces):
assert pb.IPerspective in interfaces
avatar = User(avatarID)
avatar.server = self.server
avatar.attached(mind)
return pb.IPerspective, avatar, lambda a=avatar:a.detached(mind)
class User(pb.Avatar):
def __init__(self, name): self.name = name
def attached(self, mind): self.remote = mind
def detached(self, mind): self.remote = None
def perspective_joinGroup(self, groupname):
return self.server.joinGroup(groupname, self)
def send(self, message):
self.remote.callRemote("print", message)
class Group(pb.Viewable):
def __init__(self, groupname):
self.name = groupname
self.users = []
def addUser(self, user): self.users.append(user)
def view_send(self, from_user, message):
for user in self.users:
user.send("%s: %s" % (from_user.name, message))
realm = ChatRealm()
realm.server = ChatServer()
checker = checkers.InMemoryUsernamePasswordDatabaseDontUse()
checker.addUser("alice", "1234")
checker.addUser("Bob", "secret")
p = portal.Portal(realm, [checker])
reactor.listenTCP(9000, pb.PBServerFactory(p))
reactor.run()
基本上我只需要找出如何通过 RPC 使登录调用在 Javascript 中可访问,但我不知道如何做到这一点,谷歌没有为我提供任何选项。