SlideShare una empresa de Scribd logo
1 de 21
Descargar para leer sin conexión
Fake my Party
      Tanja Otto

     24.11.2009
  Düsseldorf on Rails
SalesLentz::DevTeam
Über mich
• internes Entwicklerteam von Sales-Lentz
• IBEs für Reisen, Bustickets, Eventtickets
• seit 2006 entwickeln wir mit Ruby on Rails
• Mit Hussein Morsy Buch Ruby on Rails 2
  Galileo Press
  http://www.railsbuch.de
  http://twitter.com/ajnato
  http://devteam.sales-lentz.lu
HTTParty

• einfaches senden von HTTP-Anfragen
• JSON und XML werden automatisch in
  Ruby-Hashes umgewandelt
• http://github.com/jnunemaker/httparty
HTTParty

XML

         HTTParty   HASH

JSON
Installation


sudo gem install httparty
Ein erstes Beispiel
require "rubygems"
require "httparty"

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')

#   puts   response.body
#   puts   response.code # => 200
#   puts   response.message # => OK
#   puts   response.headers.inspect

response.each do |item|
  puts item['user']['screen_name']
end

#   =>   alexmedeiros59
#   =>   EmySayers
#   =>   ciquuuee
#   =>   bray1972
#   =>   shasoGORGEOUS
#   =>   kimix
Beispiel Twitter-API
class Twitter
  include HTTParty
  base_uri 'twitter.com'

  def initialize(u, p)
    @auth = {:username => u, :password => p}
  end

  def timeline(which=:friends, options={})
    options.merge!({:basic_auth => @auth})
    self.class.get("/statuses/#{which}_timeline.json", options)
  end

  def post(text)
    options = { :query => {:status => text}, :basic_auth => @auth }
    self.class.post('/statuses/update.json', options)
  end
end

twitter = Twitter.new(USERNAME, PASSWORD)
pp twitter.timeline.map{|t| t['user']['name']}
weitere Beispiele

• http://github.com/jnunemaker/httparty/tree/
  master/examples
FakeWeb
• Helper, um HTTP-Anfragen zu stubben
• Testumgebungen von live-Anfragen
  entkoppeln
• Tests sind auch lauffähig, wenn keine
  Netzwerkverbindung besteht
• arbeitet mit allen Libraries die auf
  Net::HTTP basieren
• http://github.com/chrisk/fakeweb/
Installation


sudo gem install fakeweb
Mit einfacher
     Zeichenkette antworten
require "rubygems"
require "fakeweb"
require "httparty"

FakeWeb.register_uri(:get, "http://twitter.com/statuses/
public_timeline.json", :body => "Hello World!")

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body
# => Hello World!

response = HTTParty.get('http://search.twitter.com/trends.json')
puts response.body
# es wird die Antwort der echten Anfrage zurückgeliefert
Einer Antwort einen
             Status hinzufügen
require "rubygems"
require "fakeweb"
require "httparty"

FakeWeb.register_uri(:get, "http://twitter.com/statuses/
public_timeline.json",
                     :body => "Nothing found",
                     :status => ["404", "Not Found"])

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.code # => "404"
puts response.message # => "Not Found"
puts response.body # => "Nothing found"
Auf jede HTTP
            Methode antworten
require "rubygems"
require "fakeweb"
require "httparty"

FakeWeb.register_uri(:any, "http://twitter.com/statuses/
public_timeline.json", :body => "response for any HTTP method")

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body
# => response for any HTTP method

response = HTTParty.post('http://twitter.com/statuses/public_timeline.json')
puts response.body
# response for any HTTP method
Wiederholende Anfragen
require "rubygems"
require "fakeweb"
require "httparty"

FakeWeb.register_uri(:get, "http://twitter.com/statuses/public_timeline.json",
                     [{:body => "Public Timeline", :status => ["200", "OK"]},
                      {:body => "Timeline not found", :status => ["404", "Not
Found"]}])

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body # => Public Timeline
puts response.code # => 200
puts response.message # => OK

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body # => Timeline not found
puts response.code # => 404
puts response.message # => Not Found

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body # => Timeline not found
puts response.code # => 404
puts response.message # => Not Found
Wiederholende Anfragen
require "rubygems"
require "fakeweb"
require "httparty"

FakeWeb.register_uri(:get, "http://twitter.com/statuses/
public_timeline.json",
                     [{:body => "Public Timeline", :status => ["200",
"OK"], :times => 2},
                       {:body => "Timeline not found", :status => ["404",
"Not Found"]}])

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body # => Public Timeline

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body # => Public Timeline

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body # => Timeline not found
HTTP Authentifizierung
require "rubygems"
require "fakeweb"
require "httparty"

FakeWeb.register_uri(:get, "http://example.com/secret", :body =>
"Unauthorized", :status => ["401", "Unauthorized"])
FakeWeb.register_uri(:get, "http://user:pwd@example.com/secret", :body =>
"Authorized")

response = HTTParty.get('http://example.com/secret')
puts response.body # => Unauthorized

response = HTTParty.get('http://example.com/secret', :basic_auth => {:username
=> "user", :password => "pwd"})
puts response.body # => Authorized
Alle registrierten URIs
               löschen
require "rubygems"
require "fakeweb"
require "httparty"

FakeWeb.register_uri(:get, "http://twitter.com/statuses/
public_timeline.json", :body => "Hello World!")

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body
# => Hello World!

FakeWeb.clean_registry

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body
# es wird die Antwort der echten Anfrage zurückgeliefert
Alle live Anfragen
                   blockieren
require "rubygems"
require "fakeweb"
require "httparty"

FakeWeb.allow_net_connect = false

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
# => raises FakeWeb::NetConnectNotAllowedError


require "rubygems"
require "fakeweb"
require "httparty"

# default
FakeWeb.allow_net_connect = true

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
# live Anfrage wird gesendet
automatisches einlesen
            einer Datei
<?xml version="1.0" encoding="UTF-8"?>
<countries>
  <country>Belgien</country>
  <country>Deutschland</country>
  <country>Luxembourg</country>
</countries>


require "rubygems"
require "httparty"
require "fakeweb"

FakeWeb.register_uri(:get, "http://example.com/countries.xml", :body =>
'fixtures/countries.xml', :content_type => "text/xml")

response = HTTParty.get('http://example.com/countries.xml')
puts response.inspect
# => {"countries"=>{"country"=>["Belgien", "Deutschland", "Luxembourg"]}}
HTTP response
             headers definieren
require "rubygems"
require "fakeweb"
require "httparty"

FakeWeb.register_uri(:get, "http://twitter.com/statuses/
public_timeline.json",
                     :body => "Hello World!",
                     :content_type => "text/plain")

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
puts response.body # => Hello World!
puts response.headers.inspect # => {"content-type"=>["text/plain"]}

Más contenido relacionado

La actualidad más candente

REST with Eve and Python
REST with Eve and PythonREST with Eve and Python
REST with Eve and PythonPiXeL16
 
The report of JavaOne2011 about groovy
The report of JavaOne2011 about groovyThe report of JavaOne2011 about groovy
The report of JavaOne2011 about groovyYasuharu Nakano
 
Cross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App EngineCross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App EngineAndy McKay
 
async/await in Swift
async/await in Swiftasync/await in Swift
async/await in SwiftPeter Friese
 
RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK - Nicola Iarocci - Co...
RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK -  Nicola Iarocci - Co...RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK -  Nicola Iarocci - Co...
RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK - Nicola Iarocci - Co...Codemotion
 
Apache CouchDB talk at Ontario GNU Linux Fest
Apache CouchDB talk at Ontario GNU Linux FestApache CouchDB talk at Ontario GNU Linux Fest
Apache CouchDB talk at Ontario GNU Linux FestMyles Braithwaite
 
Asynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time MessagingAsynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time MessagingSteve Rhoades
 
KCDC 2018 - Rapid API Development with Sails
KCDC 2018 - Rapid API Development with SailsKCDC 2018 - Rapid API Development with Sails
KCDC 2018 - Rapid API Development with SailsJustin James
 
Keep it simple web development stack
Keep it simple web development stackKeep it simple web development stack
Keep it simple web development stackEric Ahn
 
Web Scraping with Python
Web Scraping with PythonWeb Scraping with Python
Web Scraping with PythonPaul Schreiber
 
JavaScript APIs - The Web is the Platform
JavaScript APIs - The Web is the PlatformJavaScript APIs - The Web is the Platform
JavaScript APIs - The Web is the PlatformRobert Nyman
 
Python, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBPython, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBemptysquare
 
Desafios do Profissionalismo Ágil
Desafios do Profissionalismo ÁgilDesafios do Profissionalismo Ágil
Desafios do Profissionalismo ÁgilVictor Hugo Germano
 
Web Crawling Modeling with Scrapy Models #TDC2014
Web Crawling Modeling with Scrapy Models #TDC2014Web Crawling Modeling with Scrapy Models #TDC2014
Web Crawling Modeling with Scrapy Models #TDC2014Bruno Rocha
 
Logstash for SEO: come monitorare i Log del Web Server in realtime
Logstash for SEO: come monitorare i Log del Web Server in realtimeLogstash for SEO: come monitorare i Log del Web Server in realtime
Logstash for SEO: come monitorare i Log del Web Server in realtimeAndrea Cardinale
 
How to Scrap Any Website's content using ScrapyTutorial of How to scrape (cra...
How to Scrap Any Website's content using ScrapyTutorial of How to scrape (cra...How to Scrap Any Website's content using ScrapyTutorial of How to scrape (cra...
How to Scrap Any Website's content using ScrapyTutorial of How to scrape (cra...Anton
 

La actualidad más candente (20)

A Gentle Introduction to Event Loops
A Gentle Introduction to Event LoopsA Gentle Introduction to Event Loops
A Gentle Introduction to Event Loops
 
REST with Eve and Python
REST with Eve and PythonREST with Eve and Python
REST with Eve and Python
 
The report of JavaOne2011 about groovy
The report of JavaOne2011 about groovyThe report of JavaOne2011 about groovy
The report of JavaOne2011 about groovy
 
Cross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App EngineCross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App Engine
 
async/await in Swift
async/await in Swiftasync/await in Swift
async/await in Swift
 
Fun with Python
Fun with PythonFun with Python
Fun with Python
 
Pydata-Python tools for webscraping
Pydata-Python tools for webscrapingPydata-Python tools for webscraping
Pydata-Python tools for webscraping
 
RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK - Nicola Iarocci - Co...
RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK -  Nicola Iarocci - Co...RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK -  Nicola Iarocci - Co...
RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK - Nicola Iarocci - Co...
 
Apache CouchDB talk at Ontario GNU Linux Fest
Apache CouchDB talk at Ontario GNU Linux FestApache CouchDB talk at Ontario GNU Linux Fest
Apache CouchDB talk at Ontario GNU Linux Fest
 
Asynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time MessagingAsynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time Messaging
 
KCDC 2018 - Rapid API Development with Sails
KCDC 2018 - Rapid API Development with SailsKCDC 2018 - Rapid API Development with Sails
KCDC 2018 - Rapid API Development with Sails
 
Getting testy with Perl
Getting testy with PerlGetting testy with Perl
Getting testy with Perl
 
Keep it simple web development stack
Keep it simple web development stackKeep it simple web development stack
Keep it simple web development stack
 
Web Scraping with Python
Web Scraping with PythonWeb Scraping with Python
Web Scraping with Python
 
JavaScript APIs - The Web is the Platform
JavaScript APIs - The Web is the PlatformJavaScript APIs - The Web is the Platform
JavaScript APIs - The Web is the Platform
 
Python, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBPython, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDB
 
Desafios do Profissionalismo Ágil
Desafios do Profissionalismo ÁgilDesafios do Profissionalismo Ágil
Desafios do Profissionalismo Ágil
 
Web Crawling Modeling with Scrapy Models #TDC2014
Web Crawling Modeling with Scrapy Models #TDC2014Web Crawling Modeling with Scrapy Models #TDC2014
Web Crawling Modeling with Scrapy Models #TDC2014
 
Logstash for SEO: come monitorare i Log del Web Server in realtime
Logstash for SEO: come monitorare i Log del Web Server in realtimeLogstash for SEO: come monitorare i Log del Web Server in realtime
Logstash for SEO: come monitorare i Log del Web Server in realtime
 
How to Scrap Any Website's content using ScrapyTutorial of How to scrape (cra...
How to Scrap Any Website's content using ScrapyTutorial of How to scrape (cra...How to Scrap Any Website's content using ScrapyTutorial of How to scrape (cra...
How to Scrap Any Website's content using ScrapyTutorial of How to scrape (cra...
 

Similar a Fake My Party

Let's read code: python-requests library
Let's read code: python-requests libraryLet's read code: python-requests library
Let's read code: python-requests librarySusan Tan
 
Let's read code: the python-requests library
Let's read code: the python-requests libraryLet's read code: the python-requests library
Let's read code: the python-requests librarySusan Tan
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Michelangelo van Dam
 
Get Real: Adventures in realtime web apps
Get Real: Adventures in realtime web appsGet Real: Adventures in realtime web apps
Get Real: Adventures in realtime web appsdaviddemello
 
REST meets Semantic Web
REST meets Semantic WebREST meets Semantic Web
REST meets Semantic WebSteve Speicher
 
Using and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareAlona Mekhovova
 
API Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API DocumentationAPI Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API DocumentationRouven Weßling
 
YDN KR Tech Talk : Pipes 와 YQL 활용하기
YDN KR Tech Talk : Pipes 와 YQL 활용하기YDN KR Tech Talk : Pipes 와 YQL 활용하기
YDN KR Tech Talk : Pipes 와 YQL 활용하기Jinho Jung
 
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHPKing Foo
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Michelangelo van Dam
 
Tips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applicationsTips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applicationsTim Cull
 
Velocity EU 2014 — Offline-first web apps
Velocity EU 2014 — Offline-first web appsVelocity EU 2014 — Offline-first web apps
Velocity EU 2014 — Offline-first web appsandrewsmatt
 
Spiffy Applications With JavaScript
Spiffy Applications With JavaScriptSpiffy Applications With JavaScript
Spiffy Applications With JavaScriptMark Casias
 

Similar a Fake My Party (20)

Let's read code: python-requests library
Let's read code: python-requests libraryLet's read code: python-requests library
Let's read code: python-requests library
 
Palestra VCR
Palestra VCRPalestra VCR
Palestra VCR
 
Let's read code: the python-requests library
Let's read code: the python-requests libraryLet's read code: the python-requests library
Let's read code: the python-requests library
 
Api
ApiApi
Api
 
Web Server.pdf
Web Server.pdfWeb Server.pdf
Web Server.pdf
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
 
JSON and the APInauts
JSON and the APInautsJSON and the APInauts
JSON and the APInauts
 
Get Real: Adventures in realtime web apps
Get Real: Adventures in realtime web appsGet Real: Adventures in realtime web apps
Get Real: Adventures in realtime web apps
 
REST meets Semantic Web
REST meets Semantic WebREST meets Semantic Web
REST meets Semantic Web
 
Using and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middleware
 
API Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API DocumentationAPI Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API Documentation
 
YDN KR Tech Talk : Pipes 와 YQL 활용하기
YDN KR Tech Talk : Pipes 와 YQL 활용하기YDN KR Tech Talk : Pipes 와 YQL 활용하기
YDN KR Tech Talk : Pipes 와 YQL 활용하기
 
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
Servlets intro
Servlets introServlets intro
Servlets intro
 
Tips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applicationsTips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applications
 
Velocity EU 2014 — Offline-first web apps
Velocity EU 2014 — Offline-first web appsVelocity EU 2014 — Offline-first web apps
Velocity EU 2014 — Offline-first web apps
 
Blog Hacks 2011
Blog Hacks 2011Blog Hacks 2011
Blog Hacks 2011
 
Server Side Swift: Vapor
Server Side Swift: VaporServer Side Swift: Vapor
Server Side Swift: Vapor
 
Spiffy Applications With JavaScript
Spiffy Applications With JavaScriptSpiffy Applications With JavaScript
Spiffy Applications With JavaScript
 

Último

Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 

Último (20)

Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 

Fake My Party

  • 1. Fake my Party Tanja Otto 24.11.2009 Düsseldorf on Rails
  • 3. Über mich • internes Entwicklerteam von Sales-Lentz • IBEs für Reisen, Bustickets, Eventtickets • seit 2006 entwickeln wir mit Ruby on Rails • Mit Hussein Morsy Buch Ruby on Rails 2 Galileo Press http://www.railsbuch.de http://twitter.com/ajnato http://devteam.sales-lentz.lu
  • 4. HTTParty • einfaches senden von HTTP-Anfragen • JSON und XML werden automatisch in Ruby-Hashes umgewandelt • http://github.com/jnunemaker/httparty
  • 5. HTTParty XML HTTParty HASH JSON
  • 7. Ein erstes Beispiel require "rubygems" require "httparty" response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') # puts response.body # puts response.code # => 200 # puts response.message # => OK # puts response.headers.inspect response.each do |item| puts item['user']['screen_name'] end # => alexmedeiros59 # => EmySayers # => ciquuuee # => bray1972 # => shasoGORGEOUS # => kimix
  • 8. Beispiel Twitter-API class Twitter include HTTParty base_uri 'twitter.com' def initialize(u, p) @auth = {:username => u, :password => p} end def timeline(which=:friends, options={}) options.merge!({:basic_auth => @auth}) self.class.get("/statuses/#{which}_timeline.json", options) end def post(text) options = { :query => {:status => text}, :basic_auth => @auth } self.class.post('/statuses/update.json', options) end end twitter = Twitter.new(USERNAME, PASSWORD) pp twitter.timeline.map{|t| t['user']['name']}
  • 10. FakeWeb • Helper, um HTTP-Anfragen zu stubben • Testumgebungen von live-Anfragen entkoppeln • Tests sind auch lauffähig, wenn keine Netzwerkverbindung besteht • arbeitet mit allen Libraries die auf Net::HTTP basieren • http://github.com/chrisk/fakeweb/
  • 12. Mit einfacher Zeichenkette antworten require "rubygems" require "fakeweb" require "httparty" FakeWeb.register_uri(:get, "http://twitter.com/statuses/ public_timeline.json", :body => "Hello World!") response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => Hello World! response = HTTParty.get('http://search.twitter.com/trends.json') puts response.body # es wird die Antwort der echten Anfrage zurückgeliefert
  • 13. Einer Antwort einen Status hinzufügen require "rubygems" require "fakeweb" require "httparty" FakeWeb.register_uri(:get, "http://twitter.com/statuses/ public_timeline.json", :body => "Nothing found", :status => ["404", "Not Found"]) response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.code # => "404" puts response.message # => "Not Found" puts response.body # => "Nothing found"
  • 14. Auf jede HTTP Methode antworten require "rubygems" require "fakeweb" require "httparty" FakeWeb.register_uri(:any, "http://twitter.com/statuses/ public_timeline.json", :body => "response for any HTTP method") response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => response for any HTTP method response = HTTParty.post('http://twitter.com/statuses/public_timeline.json') puts response.body # response for any HTTP method
  • 15. Wiederholende Anfragen require "rubygems" require "fakeweb" require "httparty" FakeWeb.register_uri(:get, "http://twitter.com/statuses/public_timeline.json", [{:body => "Public Timeline", :status => ["200", "OK"]}, {:body => "Timeline not found", :status => ["404", "Not Found"]}]) response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => Public Timeline puts response.code # => 200 puts response.message # => OK response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => Timeline not found puts response.code # => 404 puts response.message # => Not Found response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => Timeline not found puts response.code # => 404 puts response.message # => Not Found
  • 16. Wiederholende Anfragen require "rubygems" require "fakeweb" require "httparty" FakeWeb.register_uri(:get, "http://twitter.com/statuses/ public_timeline.json", [{:body => "Public Timeline", :status => ["200", "OK"], :times => 2}, {:body => "Timeline not found", :status => ["404", "Not Found"]}]) response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => Public Timeline response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => Public Timeline response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => Timeline not found
  • 17. HTTP Authentifizierung require "rubygems" require "fakeweb" require "httparty" FakeWeb.register_uri(:get, "http://example.com/secret", :body => "Unauthorized", :status => ["401", "Unauthorized"]) FakeWeb.register_uri(:get, "http://user:pwd@example.com/secret", :body => "Authorized") response = HTTParty.get('http://example.com/secret') puts response.body # => Unauthorized response = HTTParty.get('http://example.com/secret', :basic_auth => {:username => "user", :password => "pwd"}) puts response.body # => Authorized
  • 18. Alle registrierten URIs löschen require "rubygems" require "fakeweb" require "httparty" FakeWeb.register_uri(:get, "http://twitter.com/statuses/ public_timeline.json", :body => "Hello World!") response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => Hello World! FakeWeb.clean_registry response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # es wird die Antwort der echten Anfrage zurückgeliefert
  • 19. Alle live Anfragen blockieren require "rubygems" require "fakeweb" require "httparty" FakeWeb.allow_net_connect = false response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') # => raises FakeWeb::NetConnectNotAllowedError require "rubygems" require "fakeweb" require "httparty" # default FakeWeb.allow_net_connect = true response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') # live Anfrage wird gesendet
  • 20. automatisches einlesen einer Datei <?xml version="1.0" encoding="UTF-8"?> <countries> <country>Belgien</country> <country>Deutschland</country> <country>Luxembourg</country> </countries> require "rubygems" require "httparty" require "fakeweb" FakeWeb.register_uri(:get, "http://example.com/countries.xml", :body => 'fixtures/countries.xml', :content_type => "text/xml") response = HTTParty.get('http://example.com/countries.xml') puts response.inspect # => {"countries"=>{"country"=>["Belgien", "Deutschland", "Luxembourg"]}}
  • 21. HTTP response headers definieren require "rubygems" require "fakeweb" require "httparty" FakeWeb.register_uri(:get, "http://twitter.com/statuses/ public_timeline.json", :body => "Hello World!", :content_type => "text/plain") response = HTTParty.get('http://twitter.com/statuses/public_timeline.json') puts response.body # => Hello World! puts response.headers.inspect # => {"content-type"=>["text/plain"]}