17h00 - Démo « Service WEB REST »

Navigation rapide : Lundi / Mardi / Mercredi / Jeudi / Vendredi Mémos : Perl / Python / Ruby
  • écrire un client REST

client.rb

 1: %w(rubygems patron pp).each do |lib| require lib end
 2:
 3: session = Patron::Session.new
 4: session.base_url = 'http://localhost:4567'
 5:
 6: response = session.get('/',{"Accept" => "text/html"})
 7: pp response.headers
 8: puts response.body
 9:
10: response = session.get('/',{"Accept" => "application/json"})
11: pp response.headers
12: puts response.body


  • écrire un modèle de données
    • utilisant la base de données sqlite qui vous est fournie
    • mappant la table « users »

models/users.rb

 1: %w(rubygems sequel).each do |lib| require lib end
 2:
 3: DB = Sequel.sqlite('anf2012.sqlite3')
 4:
 5: class User < Sequel::Model
 6:   set_primary_key :email     # Par défaut, utilise :id
 7:   plugin :validation_helpers # Permet de valider le format des emails
 8:   #                          # Par défaut Sequel::Model map la classe
 9:   # set_dataset DB[:users]   # sur la table portant le même nom
10:   #                          # Permet de choisir le nom de la table
11:   def validate
12:     super
13:     validate_unique :email
14:     validate_format /^[^@]+@[^\.]+\..+$/, :email
15:   end
16: end


controlers/users/get.rb

 1: module ANF; class Application < Sinatra::Base
 2:   get '/users' do
 3:     @users = User.all
 4:     case request.accept?
 5:       when 'text/html':
 6:         status          OK
 7:         content_type    'text/html'
 8:         body            erb :'users/html'
 9:       when 'application/json':
10:         status          OK
11:         content_type    'application/json'
12:         body            erb :'users/json', :layout => false
13:     end
14:   end
15: end; end


  • écrire une vue HTML
    • affichant un tableau contenant les données de votre modèle

views/users/html.erb

 1: <!DOCTYPE html>
 2:   <head>
 3:     <meta charset="UTF-8">
 4:   </head>
 5:   <body>
 6:     <table>
 7:       <% @users.each do |user| %><tr>
 8:         <% user.values.each do |k,v| %> <td><%= v %></td>
 9:       <% end %></tr>
10:     <% end %></table>
11:   </body>
12: </html>


  • écrire une vue JSON
    • représentant un tableau contenant les données de votre modèle, au format JSON

views/users/json.erb

 1: <%=
 2: require 'rubygems'
 3: require 'json'
 4:
 5: data = []
 6: @users.each do |user|
 7:   u = {}
 8:   values = user.values.collect do |k,v| u[k]=v end
 9:   data << u
10: end
11: data.to_json
12: %>


controlers/users/get.rb

 1: module ANF; class Application < Sinatra::Base
 2:   get '/users/:email' do
 3:     @user  = User[params['email']] unless params['email'].nil?
 4:     if @user.nil? then
 5:       @users = User.all
 6:       case request.accept?
 7:         when 'text/html':
 8:           status          OK
 9:           content_type    'text/html'
10:           body            erb :'users/html'
11:         when 'application/json':
12:           status          OK
13:           content_type    'application/json'
14:           body            erb :'users/json', :layout => false
15:       end
16:     else
17:       case request.accept?
18:         when 'text/html':
19:           status          OK
20:           content_type    'text/html'
21:           body            erb :'user/html'
22:         when 'application/json':
23:           status          OK
24:           content_type    'application/json'
25:           body            erb :'user/json', :layout => false
26:       end
27:     end
28:   end
29: end; end


  • écrire un contrôleur utilisant le verbe HTTP POST
    • pour ajouter un utilisateur
    • répondant à une URI de type « http://ip:port/users »
    • en passant l'object JSON suivant { 'email': 'leonardo@vinci-closluce.com', 'name': 'leonardo' }

controlers/users/post.rb

1: require 'json'
2:
3: module ANF; class Application < Sinatra::Base
4:   post '/users/:email' do
5:
6:   end
7: end; end


controlers/users/put.rb

 1: require 'json'
 2:
 3: module ANF; class Application < Sinatra::Base
 4:   put '/users/:email' do
 5:     user = User[params[:email]] unless params['email'].nil?
 6:     content_type 'application/json'
 7:     if user.nil? then
 8:       if request.content_type == 'application/json' then
 9:         data = JSON.parse request.body.read
10:         if user.count > 0 then
11:           user.update( :name => data['name']) unless data['name'].nil?
12:           status OK
13:           body   '{ "message": "Ressource found" }'
14:         else
15:           status NOT_FOUND
16:           body   '{ "message": "Ressource not found" }'
17:         end
18:       else
19:         status ERROR
20:         body   '{ "message": "Data must be in JSON" }'
21:       end
22:     else
23:       status ERROR
24:       body   '{ "message": "User email missing" }'
25:     end
26:   end
27: end; end


controlers/users/delete.rb

 1: module ANF; class Application < Sinatra::Base
 2:   delete '/users/:email' do
 3:     user = User[params[:email]] unless params['email'].nil?
 4:     content_type 'application/json'
 5:     if user.count > 0 then
 6:       user.delete
 7:       if user.count == 0 then
 8:         status OK
 9:         body   '{ "message": "User deleted" }'
10:       else
11:         status ERROR
12:         body   %q{{ "message": "Can't process your request" }}
13:       end
14:     else
15:       status   NOT_FOUND
16:       body     '{ "message": "Ressource not found" }'
17:     end
18:   end
19: end; end

Version

$Id: jeudi_corrige_ruby_4.txt 567 2012-05-21 07:29:58Z aicardi $

jeudi_corrige_ruby_4.txt · Last modified: 2012/05/21 09:30 (external edit)
 
Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki