Last active
March 4, 2016 00:25
-
-
Save athoune/8ab85700ae69da025895 to your computer and use it in GitHub Desktop.
Hacking thrift with gunicorn
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import sys | |
sys.path.append('gen-py') | |
from gunicorn.app.base import Application | |
from gunicorn.workers.sync import SyncWorker | |
from gunicorn.arbiter import Arbiter | |
from thrift.transport.TSocket import TSocket | |
import thrift.protocol.TBinaryProtocol | |
class ThriftApplication(Application): | |
def init(self, parser, opts, args): | |
pass | |
def wsgi(self): | |
return None | |
class Worker(SyncWorker): | |
def handle(self, listener, client, addr): | |
itransport = TSocket() | |
itransport.setHandle(client) | |
iprotocol = TBinaryProtocol.TBinaryProtocol(itransport) | |
otransport = TSocket() | |
otransport.setHandle(client) | |
oprotocol = TBinaryProtocol.TBinaryProtocol(otransport) | |
self.cfg.processor.process(iprotocol, oprotocol) | |
if __name__ == '__main__': | |
from tutorial.Calculator import Processor | |
from tutorial.ttypes import * | |
from shared.ttypes import SharedStruct | |
class CalculatorHandler: | |
def __init__(self): | |
self.log = {} | |
def ping(self): | |
print('ping()') | |
def add(self, n1, n2): | |
print('add(%d,%d)' % (n1, n2)) | |
return n1+n2 | |
def calculate(self, logid, work): | |
print('calculate(%d, %r)' % (logid, work)) | |
if work.op == Operation.ADD: | |
val = work.num1 + work.num2 | |
elif work.op == Operation.SUBTRACT: | |
val = work.num1 - work.num2 | |
elif work.op == Operation.MULTIPLY: | |
val = work.num1 * work.num2 | |
elif work.op == Operation.DIVIDE: | |
if work.num2 == 0: | |
x = InvalidOperation() | |
x.whatOp = work.op | |
x.why = 'Cannot divide by 0' | |
raise x | |
val = work.num1 / work.num2 | |
else: | |
x = InvalidOperation() | |
x.whatOp = work.op | |
x.why = 'Invalid operation' | |
raise x | |
log = SharedStruct() | |
log.key = logid | |
log.value = '%d' % (val) | |
self.log[logid] = log | |
return val | |
def getStruct(self, key): | |
print('getStruct(%d)' % (key)) | |
return self.log[key] | |
def zip(self): | |
print('zip()') | |
handler = CalculatorHandler() | |
app = ThriftApplication() | |
app.cfg.processor = Processor(handler) | |
arbiter = Arbiter(app) | |
arbiter.worker_class = Worker | |
arbiter.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment