我需要通过Thrift界面访问来自Django webapp的数据。我想以非阻塞方式执行此操作(例如,使用libevent / gevent ...)但是没有很多示例实现(在python中),所以我想在这里询问任何示例/提示/经验!
请注意,这个问题是关于使用Thrift,而不是任何其他协议,我知道可能有更好的框架用于此目的而不是Django,但使用它也是一个要求!
答案 0 :(得分:0)
这可以通过在Django admin command内实现thrift服务器来完成。请参阅您需要的文件结构的链接。在命令文件中,您可以调用" thrift_server.py",然后按如下方式实现通常的thrift服务器:
import sys
from django.core.management.base import BaseCommand
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
#import thrift files here
#now define the service handler according to your thrift method declaration
class ServiceHandler:
def __init__(self):
pass
#self.log = {}
def thriftMethodName(self, arg):
print "hello world!"
#here you have access to anything in the django framework
return True
class Command(BaseCommand):
def handle(self, *args, **kwargs):
handler = ServiceHandler()
processor = SaleService.Processor(handler)
transport = TSocket.TServerSocket(port=9090)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
# You could do one of these for a multithreaded server
#server = TServer.TThreadedServer(processor, transport, tfactory, pfactory)
#server = TServer.TThreadPoolServer(processor, transport, tfactory, pfactory)
self.stdout.write('Starting thrift server...')
server.serve()
self.stdout.write('done.')
请注意,上面描述了多线程服务器选项,但我还没有对它们进行过测试。
然后您可以按如下方式运行守护程序:
(virtualenv) /django_project/ > python manage.py thrift_server