Skip to main content
 首页 » 编程设计

python之使用 Django 的非阻塞 Thrift-Server

2025年05月04日45lvdongjie

我需要通过 Thrift 访问来自 Django webapp 的数据界面。我想以非阻塞方式执行此操作(例如使用 libevent/gevent ...),但周围没有很多示例实现(在 python 中),所以我想在这里询问任何示例/提示/经验!

请注意,这个问题是关于使用 Thrift,而不是任何其他协议(protocol),我知道可能有比 Django 更好的框架用于此目的,但使用它也是一个要求!

请您参考如下方法:

这可以通过在 Django admin command 中实现节俭服务器来完成.请参阅您需要的文件结构的链接。在您可以称为“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