SlideShare ist ein Scribd-Unternehmen logo
1 von 12
Downloaden Sie, um offline zu lesen
Apache Thrift:
RPC service cross languages
          2012/11/04
           Jimmy Lai
    r97922028 [at] ntu.edu.tw
Thrift Network Stack




     Thrift http://thrift.apache.org/   2
Languages Supported
•   C++                              •     Java
•   C#                               •     OCaml
•   Cocoa                            •     Perl
•   D                                •     PHP
•   Delphi                           •     Python
•   Erlang                           •     Ruby
•   Haskell                          •     Smalltalk



                   Thrift http://thrift.apache.org/    3
Interface Description Language (IDL)
  Data structure
    'bool' | 'byte' | 'i16' | 'i32' | 'i64' | 'double' |
    'string' | 'binary' | 'slist'
    map
    set
    list
• http://thrift.apache.org/docs/idl/


                      Thrift http://thrift.apache.org/     4
Usage
1. Define data structure and service interface
   using IDL(interface description language)
2. Generate language binding library:
      thrift -gen py my.thrift
3. Write Server and Client using the generated
   library. You may refer the template file in
   thrift/tutorial directory.


                  Thrift http://thrift.apache.org/   5
Example
• Scenario:
• We have a prepared machine learning model,
  and we'd like to load the model in advance as
  a server to provide prediction service.




                  Thrift http://thrift.apache.org/   6
Step 1. Define data structure and
        service: classifier.thrift
typedef list<double> Feature

service Classifier{
  i64 predict(1: Feature feature);
}




                   Thrift http://thrift.apache.org/   7
Step 2. Generate binding library
• thrift --gen py classifier.thrift
• Code binding library in gen-py dir




                  Thrift http://thrift.apache.org/   8
Step 3. Write Service and Client
• Server
  class ClassifierHandler(object):
    def __init__(self):
       self.model = pkl.load(open('svm_model.pkl', 'rb'))
       print 'loading model...'

    def predict(self, feature):
      return self.model.predict(feature)[0]




                       Thrift http://thrift.apache.org/     9
Client (1/2)
# Make socket
transport = TSocket.TSocket('localhost', 9090)

# Buffering is critical. Raw sockets are very slow
transport = TTransport.TBufferedTransport(transport)

# Wrap in a protocol
protocol = TBinaryProtocol.TBinaryProtocol(transport)

# Create a client to use the protocol encoder
client = Classifier.Client(protocol)

# Connect!
transport.open()
                     Thrift http://thrift.apache.org/   10
Client (2/2)
digits = datasets.load_digits()
data = zip(digits.data, digits.target)
random.shuffle(data)

for i in range(10):
  result = client.predict(data[i][0])
  answer = data[i][1]
  if result == answer:
      print 'Correct!'
  else:
      print 'Wrong: answer is %d, predicted as %d' % (answer,
result)

# Close!
transport.close()        Thrift http://thrift.apache.org/       11
Live Demo
• See thrift_demo directory in
  https://bitbucket.org/noahsark/slideshare/
 noahsark@localhost:~/workspace/thrift/gen-py$ ./PythonServer.py
 loading model...
 Starting the server...
 noahsark@localhost:~/workspace/thrift/gen-py$ ./PythonClient.py
 Correct!
 Correct!
 Correct!
 Correct!
 Correct!
 Correct!
 Correct!
 Wrong: answer is 8, predicted as 1
 Correct!
 Correct!                   Thrift http://thrift.apache.org/       12

Weitere ähnliche Inhalte

Was ist angesagt?

Apache AVRO (Boston HUG, Jan 19, 2010)
Apache AVRO (Boston HUG, Jan 19, 2010)Apache AVRO (Boston HUG, Jan 19, 2010)
Apache AVRO (Boston HUG, Jan 19, 2010)
Cloudera, Inc.
 

Was ist angesagt? (20)

Facebook thrift
Facebook thriftFacebook thrift
Facebook thrift
 
Php’s guts
Php’s gutsPhp’s guts
Php’s guts
 
Fluentd meetup dive into fluent plugin (outdated)
Fluentd meetup dive into fluent plugin (outdated)Fluentd meetup dive into fluent plugin (outdated)
Fluentd meetup dive into fluent plugin (outdated)
 
Multiplexing in Thrift: Enhancing thrift to meet Enterprise expectations- Imp...
Multiplexing in Thrift: Enhancing thrift to meet Enterprise expectations- Imp...Multiplexing in Thrift: Enhancing thrift to meet Enterprise expectations- Imp...
Multiplexing in Thrift: Enhancing thrift to meet Enterprise expectations- Imp...
 
Hack and HHVM
Hack and HHVMHack and HHVM
Hack and HHVM
 
Hack Programming Language
Hack Programming LanguageHack Programming Language
Hack Programming Language
 
Rest style web services (google protocol buffers) prasad nirantar
Rest style web services (google protocol buffers)   prasad nirantarRest style web services (google protocol buffers)   prasad nirantar
Rest style web services (google protocol buffers) prasad nirantar
 
PHPCR e API Platform: cosa significa davvero sviluppare un CMF con Symfony
PHPCR e API Platform: cosa significa davvero sviluppare un CMF con SymfonyPHPCR e API Platform: cosa significa davvero sviluppare un CMF con Symfony
PHPCR e API Platform: cosa significa davvero sviluppare un CMF con Symfony
 
DEF CON 27 - workshop - HUGO TROVAO and RUSHIKESH NADEDKAR - scapy dojo v1
DEF CON 27 - workshop - HUGO TROVAO and RUSHIKESH NADEDKAR - scapy dojo v1DEF CON 27 - workshop - HUGO TROVAO and RUSHIKESH NADEDKAR - scapy dojo v1
DEF CON 27 - workshop - HUGO TROVAO and RUSHIKESH NADEDKAR - scapy dojo v1
 
Apache AVRO (Boston HUG, Jan 19, 2010)
Apache AVRO (Boston HUG, Jan 19, 2010)Apache AVRO (Boston HUG, Jan 19, 2010)
Apache AVRO (Boston HUG, Jan 19, 2010)
 
Optimizing LAMPhp Applications
Optimizing LAMPhp ApplicationsOptimizing LAMPhp Applications
Optimizing LAMPhp Applications
 
Dive into Fluentd plugin v0.12
Dive into Fluentd plugin v0.12Dive into Fluentd plugin v0.12
Dive into Fluentd plugin v0.12
 
Fluentd meetup in japan
Fluentd meetup in japanFluentd meetup in japan
Fluentd meetup in japan
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
 
JRuby with Java Code in Data Processing World
JRuby with Java Code in Data Processing WorldJRuby with Java Code in Data Processing World
JRuby with Java Code in Data Processing World
 
NativeBoost
NativeBoostNativeBoost
NativeBoost
 
Fluentd introduction at ipros
Fluentd introduction at iprosFluentd introduction at ipros
Fluentd introduction at ipros
 
Fluentd v0.14 Plugin API Details
Fluentd v0.14 Plugin API DetailsFluentd v0.14 Plugin API Details
Fluentd v0.14 Plugin API Details
 
Fluentd and WebHDFS
Fluentd and WebHDFSFluentd and WebHDFS
Fluentd and WebHDFS
 
Php a dynamic web scripting language
Php   a dynamic web scripting languagePhp   a dynamic web scripting language
Php a dynamic web scripting language
 

Andere mochten auch

Data Analyst Nanodegree
Data Analyst NanodegreeData Analyst Nanodegree
Data Analyst Nanodegree
Jimmy Lai
 
NetworkX - python graph analysis and visualization @ PyHug
NetworkX - python graph analysis and visualization @ PyHugNetworkX - python graph analysis and visualization @ PyHug
NetworkX - python graph analysis and visualization @ PyHug
Jimmy Lai
 

Andere mochten auch (20)

Facebook thrift
Facebook thriftFacebook thrift
Facebook thrift
 
Fast data mining flow prototyping using IPython Notebook
Fast data mining flow prototyping using IPython NotebookFast data mining flow prototyping using IPython Notebook
Fast data mining flow prototyping using IPython Notebook
 
[LDSP] Solr Usage
[LDSP] Solr Usage[LDSP] Solr Usage
[LDSP] Solr Usage
 
Data Analyst Nanodegree
Data Analyst NanodegreeData Analyst Nanodegree
Data Analyst Nanodegree
 
[LDSP] Search Engine Back End API Solution for Fast Prototyping
[LDSP] Search Engine Back End API Solution for Fast Prototyping[LDSP] Search Engine Back End API Solution for Fast Prototyping
[LDSP] Search Engine Back End API Solution for Fast Prototyping
 
Illustration of TextSecure's Protocol Buffer usage
Illustration of TextSecure's Protocol Buffer usageIllustration of TextSecure's Protocol Buffer usage
Illustration of TextSecure's Protocol Buffer usage
 
Nltk natural language toolkit overview and application @ PyCon.tw 2012
Nltk  natural language toolkit overview and application @ PyCon.tw 2012Nltk  natural language toolkit overview and application @ PyCon.tw 2012
Nltk natural language toolkit overview and application @ PyCon.tw 2012
 
Documentation with sphinx @ PyHug
Documentation with sphinx @ PyHugDocumentation with sphinx @ PyHug
Documentation with sphinx @ PyHug
 
Software development practices in python
Software development practices in pythonSoftware development practices in python
Software development practices in python
 
When big data meet python @ COSCUP 2012
When big data meet python @ COSCUP 2012When big data meet python @ COSCUP 2012
When big data meet python @ COSCUP 2012
 
HBase Advanced Schema Design - Berlin Buzzwords - June 2012
HBase Advanced Schema Design - Berlin Buzzwords - June 2012HBase Advanced Schema Design - Berlin Buzzwords - June 2012
HBase Advanced Schema Design - Berlin Buzzwords - June 2012
 
Build a Searchable Knowledge Base
Build a Searchable Knowledge BaseBuild a Searchable Knowledge Base
Build a Searchable Knowledge Base
 
Mongo DB로 진행하는 CRUD
Mongo DB로 진행하는 CRUDMongo DB로 진행하는 CRUD
Mongo DB로 진행하는 CRUD
 
Big data analysis in python @ PyCon.tw 2013
Big data analysis in python @ PyCon.tw 2013Big data analysis in python @ PyCon.tw 2013
Big data analysis in python @ PyCon.tw 2013
 
Nltk natural language toolkit overview and application @ PyHug
Nltk  natural language toolkit overview and application @ PyHugNltk  natural language toolkit overview and application @ PyHug
Nltk natural language toolkit overview and application @ PyHug
 
NetworkX - python graph analysis and visualization @ PyHug
NetworkX - python graph analysis and visualization @ PyHugNetworkX - python graph analysis and visualization @ PyHug
NetworkX - python graph analysis and visualization @ PyHug
 
Text classification in scikit-learn
Text classification in scikit-learnText classification in scikit-learn
Text classification in scikit-learn
 
Facebook architecture
Facebook architectureFacebook architecture
Facebook architecture
 
Text Classification in Python – using Pandas, scikit-learn, IPython Notebook ...
Text Classification in Python – using Pandas, scikit-learn, IPython Notebook ...Text Classification in Python – using Pandas, scikit-learn, IPython Notebook ...
Text Classification in Python – using Pandas, scikit-learn, IPython Notebook ...
 
OVERVIEW OF FACEBOOK SCALABLE ARCHITECTURE.
OVERVIEW  OF FACEBOOK SCALABLE ARCHITECTURE.OVERVIEW  OF FACEBOOK SCALABLE ARCHITECTURE.
OVERVIEW OF FACEBOOK SCALABLE ARCHITECTURE.
 

Ähnlich wie Apache thrift-RPC service cross languages

Distributed Ruby and Rails
Distributed Ruby and RailsDistributed Ruby and Rails
Distributed Ruby and Rails
Wen-Tien Chang
 
Data processing at the speed of 100 Gbps@Apache Crail (Incubating)
Data processing at the speed of 100 Gbps@Apache Crail (Incubating)Data processing at the speed of 100 Gbps@Apache Crail (Incubating)
Data processing at the speed of 100 Gbps@Apache Crail (Incubating)
DataWorks Summit
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHP
Zoran Jeremic
 
Apache web server installation/configuration, Virtual Hosting
Apache web server installation/configuration, Virtual HostingApache web server installation/configuration, Virtual Hosting
Apache web server installation/configuration, Virtual Hosting
webhostingguy
 

Ähnlich wie Apache thrift-RPC service cross languages (20)

Distributed Ruby and Rails
Distributed Ruby and RailsDistributed Ruby and Rails
Distributed Ruby and Rails
 
Hands on with CoAP and Californium
Hands on with CoAP and CaliforniumHands on with CoAP and Californium
Hands on with CoAP and Californium
 
Data processing at the speed of 100 Gbps@Apache Crail (Incubating)
Data processing at the speed of 100 Gbps@Apache Crail (Incubating)Data processing at the speed of 100 Gbps@Apache Crail (Incubating)
Data processing at the speed of 100 Gbps@Apache Crail (Incubating)
 
Building scalable and language-independent Java services using Apache Thrift ...
Building scalable and language-independent Java services using Apache Thrift ...Building scalable and language-independent Java services using Apache Thrift ...
Building scalable and language-independent Java services using Apache Thrift ...
 
Building scalable and language independent java services using apache thrift
Building scalable and language independent java services using apache thriftBuilding scalable and language independent java services using apache thrift
Building scalable and language independent java services using apache thrift
 
Rack
RackRack
Rack
 
Intro to-puppet
Intro to-puppetIntro to-puppet
Intro to-puppet
 
Big Data, Data Lake, Fast Data - Dataserialiation-Formats
Big Data, Data Lake, Fast Data - Dataserialiation-FormatsBig Data, Data Lake, Fast Data - Dataserialiation-Formats
Big Data, Data Lake, Fast Data - Dataserialiation-Formats
 
CocoaConf: The Language of Mobile Software is APIs
CocoaConf: The Language of Mobile Software is APIsCocoaConf: The Language of Mobile Software is APIs
CocoaConf: The Language of Mobile Software is APIs
 
Consuming RESTful Web services in PHP
Consuming RESTful Web services in PHPConsuming RESTful Web services in PHP
Consuming RESTful Web services in PHP
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHP
 
(phpconftw2012) PHP as a Middleware in Embedded Systems
(phpconftw2012) PHP as a Middleware in Embedded Systems(phpconftw2012) PHP as a Middleware in Embedded Systems
(phpconftw2012) PHP as a Middleware in Embedded Systems
 
Web services tutorial
Web services tutorialWeb services tutorial
Web services tutorial
 
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon YangPractical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
 
Web Services Tutorial
Web Services TutorialWeb Services Tutorial
Web Services Tutorial
 
Apache web server installation/configuration, Virtual Hosting
Apache web server installation/configuration, Virtual HostingApache web server installation/configuration, Virtual Hosting
Apache web server installation/configuration, Virtual Hosting
 
Introduction into Docker Containers, the Oracle Platform and the Oracle (Nati...
Introduction into Docker Containers, the Oracle Platform and the Oracle (Nati...Introduction into Docker Containers, the Oracle Platform and the Oracle (Nati...
Introduction into Docker Containers, the Oracle Platform and the Oracle (Nati...
 
Rails web api 开发
Rails web api 开发Rails web api 开发
Rails web api 开发
 
Introduction to Laravel Framework (5.2)
Introduction to Laravel Framework (5.2)Introduction to Laravel Framework (5.2)
Introduction to Laravel Framework (5.2)
 
Chicago Hashicorp User Group - Terraform Public Module Registry
Chicago Hashicorp User Group - Terraform Public Module RegistryChicago Hashicorp User Group - Terraform Public Module Registry
Chicago Hashicorp User Group - Terraform Public Module Registry
 

Mehr von Jimmy Lai

Mehr von Jimmy Lai (6)

Python Linters at Scale.pdf
Python Linters at Scale.pdfPython Linters at Scale.pdf
Python Linters at Scale.pdf
 
EuroPython 2022 - Automated Refactoring Large Python Codebases
EuroPython 2022 - Automated Refactoring Large Python CodebasesEuroPython 2022 - Automated Refactoring Large Python Codebases
EuroPython 2022 - Automated Refactoring Large Python Codebases
 
Annotate types in large codebase with automated refactoring
Annotate types in large codebase with automated refactoringAnnotate types in large codebase with automated refactoring
Annotate types in large codebase with automated refactoring
 
The journey of asyncio adoption in instagram
The journey of asyncio adoption in instagramThe journey of asyncio adoption in instagram
The journey of asyncio adoption in instagram
 
Distributed system coordination by zookeeper and introduction to kazoo python...
Distributed system coordination by zookeeper and introduction to kazoo python...Distributed system coordination by zookeeper and introduction to kazoo python...
Distributed system coordination by zookeeper and introduction to kazoo python...
 
Continuous Delivery: automated testing, continuous integration and continuous...
Continuous Delivery: automated testing, continuous integration and continuous...Continuous Delivery: automated testing, continuous integration and continuous...
Continuous Delivery: automated testing, continuous integration and continuous...
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 

Apache thrift-RPC service cross languages

  • 1. Apache Thrift: RPC service cross languages 2012/11/04 Jimmy Lai r97922028 [at] ntu.edu.tw
  • 2. Thrift Network Stack Thrift http://thrift.apache.org/ 2
  • 3. Languages Supported • C++ • Java • C# • OCaml • Cocoa • Perl • D • PHP • Delphi • Python • Erlang • Ruby • Haskell • Smalltalk Thrift http://thrift.apache.org/ 3
  • 4. Interface Description Language (IDL) Data structure 'bool' | 'byte' | 'i16' | 'i32' | 'i64' | 'double' | 'string' | 'binary' | 'slist' map set list • http://thrift.apache.org/docs/idl/ Thrift http://thrift.apache.org/ 4
  • 5. Usage 1. Define data structure and service interface using IDL(interface description language) 2. Generate language binding library: thrift -gen py my.thrift 3. Write Server and Client using the generated library. You may refer the template file in thrift/tutorial directory. Thrift http://thrift.apache.org/ 5
  • 6. Example • Scenario: • We have a prepared machine learning model, and we'd like to load the model in advance as a server to provide prediction service. Thrift http://thrift.apache.org/ 6
  • 7. Step 1. Define data structure and service: classifier.thrift typedef list<double> Feature service Classifier{ i64 predict(1: Feature feature); } Thrift http://thrift.apache.org/ 7
  • 8. Step 2. Generate binding library • thrift --gen py classifier.thrift • Code binding library in gen-py dir Thrift http://thrift.apache.org/ 8
  • 9. Step 3. Write Service and Client • Server class ClassifierHandler(object): def __init__(self): self.model = pkl.load(open('svm_model.pkl', 'rb')) print 'loading model...' def predict(self, feature): return self.model.predict(feature)[0] Thrift http://thrift.apache.org/ 9
  • 10. Client (1/2) # Make socket transport = TSocket.TSocket('localhost', 9090) # Buffering is critical. Raw sockets are very slow transport = TTransport.TBufferedTransport(transport) # Wrap in a protocol protocol = TBinaryProtocol.TBinaryProtocol(transport) # Create a client to use the protocol encoder client = Classifier.Client(protocol) # Connect! transport.open() Thrift http://thrift.apache.org/ 10
  • 11. Client (2/2) digits = datasets.load_digits() data = zip(digits.data, digits.target) random.shuffle(data) for i in range(10): result = client.predict(data[i][0]) answer = data[i][1] if result == answer: print 'Correct!' else: print 'Wrong: answer is %d, predicted as %d' % (answer, result) # Close! transport.close() Thrift http://thrift.apache.org/ 11
  • 12. Live Demo • See thrift_demo directory in https://bitbucket.org/noahsark/slideshare/ noahsark@localhost:~/workspace/thrift/gen-py$ ./PythonServer.py loading model... Starting the server... noahsark@localhost:~/workspace/thrift/gen-py$ ./PythonClient.py Correct! Correct! Correct! Correct! Correct! Correct! Correct! Wrong: answer is 8, predicted as 1 Correct! Correct! Thrift http://thrift.apache.org/ 12