SlideShare a Scribd company logo
1 of 41
Google Custom Search

      Rashi Dhing
Our web application today


• Build  a web application for searching
    SML definitions from the SML Basis
    Standard Library

✓    We will use Google custom search
     for building this app




                                   ... because we know you like SML!
The Google APIs
The Google Custom Search API



➡   Use the Google Custom Search API to search over a website
    or a collection of websites and to embed the results in your
    web application
3 ways to use Google Custom search




•   Google snippet

•   Google Javascript API (client side)

•   Google Python API (server side)
The Google Snippet
Step 1 - go to Google Custom Search
Step 2 - sign in with your Google account
Step 3 - Setup a search engine
Step 3 - Copy the generated code snippet
Step 4 - Paste the code snippet in your page

                                                                     engine/templates/engine/index.html
...
<body>
      <div id="cse-search-form" style="width: 100%;">Loading</div>
      <script src="//www.google.com/jsapi" type="text/javascript"></script>
      <script type="text/javascript">
  
       google.load('search', '1', {language : 'en', style : google.loader.themes.SHINY});
  
       google.setOnLoadCallback(function() {
var customSearchControl = new google.search.CustomSearchControl('004982958264606934300:2o52rkqdfaw');
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
var options = new google.search.DrawOptions();
options.setSearchFormRoot('cse-search-form');
customSearchControl.draw('cse', options);
  
   
    }, true);
   </script>
   <div id="cse" style="width:100%;"></div>
<body></html>
Step 4 - Paste the code snippet in your page

                                                                     engine/templates/engine/index.html
...
                                                                        Your Custom Search Identifier
<body>
                                                                        (aka CX or CSEid)
      <div id="cse-search-form" style="width: 100%;">Loading</div>
      <script src="//www.google.com/jsapi" type="text/javascript"></script>
      <script type="text/javascript">
  
       google.load('search', '1', {language : 'en', style : google.loader.themes.SHINY});
  
       google.setOnLoadCallback(function() {
var customSearchControl = new google.search.CustomSearchControl('004982958264606934300:2o52rkqdfaw');
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
var options = new google.search.DrawOptions();
options.setSearchFormRoot('cse-search-form');
customSearchControl.draw('cse', options);
  
   
    }, true);
   </script>
   <div id="cse" style="width:100%;"></div>
<body></html>
Step 4 - Paste the code snippet in your page

                                                                     engine/templates/engine/index.html
...
                                                                        Your Custom Search Identifier
<body>
                                                                        (aka CX or CSEid)
      <div id="cse-search-form" style="width: 100%;">Loading</div>
      <script src="//www.google.com/jsapi" type="text/javascript"></script>
      <script type="text/javascript">
  
       google.load('search', '1', {language : 'en', style : google.loader.themes.SHINY});
  
       google.setOnLoadCallback(function() {
var customSearchControl = new google.search.CustomSearchControl('004982958264606934300:2o52rkqdfaw');
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
var options = new google.search.DrawOptions();
options.setSearchFormRoot('cse-search-form');
customSearchControl.draw('cse', options);
  
   
    }, true);
   </script>
                                                       The div element where to
   <div id="cse" style="width:100%;"></div>
                                                       show the results
<body></html>
Result
Advantages and Limitations




✓   Very easy to use

๏   The results are shown in a new tab/window

➡   We want the results to be embedded in the same page
Solution



➡   On the client side

    1. query the Google search using the Google Javascript API

    2. process the results using Javascript

    3. show the results in the page
The Google Javascript API
Get your Google API key from the API Console
Search Request

                                                                search/static/js/script.js
function client()
{
 $('#result').html('<script src="https://www.googleapis.com/customsearch/v1?
                           key=AIzaSyDBrtHVzXjrvKus_qGpPbTm9rJppIhjxvM&
                           cx=004982958264606934300:2o52rkqdfaw&
                           q='+$('#inp').val()+'&
                           callback=hndlr"></script>');
}
function hndlr(response)
{
 ....
}
Search Request

                                                                search/static/js/script.js
function client()
{
 $('#result').html('<script src="https://www.googleapis.com/customsearch/v1?
                           key=AIzaSyDBrtHVzXjrvKus_qGpPbTm9rJppIhjxvM&
    Your API key
                           cx=004982958264606934300:2o52rkqdfaw&
                           q='+$('#inp').val()+'&
                           callback=hndlr"></script>');
}
function hndlr(response)
{
 ....
}
Search Request

                                                                search/static/js/script.js
function client()
{
 $('#result').html('<script src="https://www.googleapis.com/customsearch/v1?
                           key=AIzaSyDBrtHVzXjrvKus_qGpPbTm9rJppIhjxvM&
    Your API key
                           cx=004982958264606934300:2o52rkqdfaw&
                           q='+$('#inp').val()+'&
                                                            Your custom search engine id
                           callback=hndlr"></script>');
}
function hndlr(response)
{
 ....
}
Search Request

                                                                search/static/js/script.js
function client()
{
 $('#result').html('<script src="https://www.googleapis.com/customsearch/v1?
                           key=AIzaSyDBrtHVzXjrvKus_qGpPbTm9rJppIhjxvM&
    Your API key
                           cx=004982958264606934300:2o52rkqdfaw&
                           q='+$('#inp').val()+'&
    Your search query                                       Your custom search engine id
                           callback=hndlr"></script>');
}
function hndlr(response)
{
 ....
}
Search Request

                                                                search/static/js/script.js
function client()
{
 $('#result').html('<script src="https://www.googleapis.com/customsearch/v1?
                           key=AIzaSyDBrtHVzXjrvKus_qGpPbTm9rJppIhjxvM&
    Your API key
                           cx=004982958264606934300:2o52rkqdfaw&
                           q='+$('#inp').val()+'&
    Your search query                                       Your custom search engine id
                           callback=hndlr"></script>');
}
function hndlr(response)
{                                  Your callback method
 ....
}
The callback method




➡   The call method (called hndlr in the example) defines
    what to do with the search results
Example
                                                                search/static/js/script.js

function hndlr(response)
{
     page = “”
     for (var i = 0; i < response.items.length; i++) {
          var item = response.items[i];
          var link = item.link;
          page += "<br/><div><a onclick="go('"+link+"');" href='#'>"
                  +item.htmlTitle
                  +"</a><br/>"
                  +item.htmlSnippet+
                  + "<br/><a onclick="go('"+link+"');" href='#'>"
                  +link+"</a></div><br/>";
     }


 
   $('#result').html(page);
 
   $('#result').show();
}
Example
                                                                 search/static/js/script.js

function hndlr(response)
                                    For each search result ...
{
     page = “”
     for (var i = 0; i < response.items.length; i++) {
          var item = response.items[i];
          var link = item.link;
          page += "<br/><div><a onclick="go('"+link+"');" href='#'>"
                  +item.htmlTitle
                  +"</a><br/>"
                  +item.htmlSnippet+
                  + "<br/><a onclick="go('"+link+"');" href='#'>"
                  +link+"</a></div><br/>";
     }


 
   $('#result').html(page);
 
   $('#result').show();
}
Example
                                                                            search/static/js/script.js

function hndlr(response)
                                    For each search result ...
{
     page = “”
     for (var i = 0; i < response.items.length; i++) {
          var item = response.items[i];
          var link = item.link;
          page += "<br/><div><a onclick="go('"+link+"');" href='#'>"
                  +item.htmlTitle
                  +"</a><br/>"
                  +item.htmlSnippet+
                  + "<br/><a onclick="go('"+link+"');" href='#'>"
                  +link+"</a></div><br/>";
     }


 
   $('#result').html(page);                   ... display the search result but change the target url
 
   $('#result').show();                       address so that the link opens in the current page
                                                rather than opening a new one
}
Result
Problem

๏   Nothing happens when you click on the link

➡   No bug shown except ...
Problem

๏   Nothing happens when you click on the link

➡   No bug shown except ...




                                   This is a Cross Domain error
Cross Domain restriction (aka Same Origin Policy)


 ”The policy permits scripts running on pages
 originating from the same site to access each other's
 methods and properties with no specific restrictions,
 but prevents access to most methods and
 properties across pages on different sites.” Wikipedia
Solution - use an iframe
•   An <iframe> can contains another HTML document possibly
    coming from another domain

➡   Like a webpage inside a webpage

✓   An iFrame is acting like a fence between the two documents
     <html>
     ...
         <iframe>
               <html>




               </html>

       </iframe>
     ...
     </html>
Solution - use an iframe
•   An <iframe> can contains another HTML document possibly
    coming from another domain

➡   Like a webpage inside a webpage

✓   An iFrame is acting like a fence between the two documents
     <html>
     ...                      Javascript code from the inner document cannot
         <iframe>             access the resources from the main document
               <html>




               </html>

       </iframe>
     ...
     </html>
Solution - use an iframe
•   An <iframe> can contains another HTML document possibly
    coming from another domain

➡   Like a webpage inside a webpage

✓   An iFrame is acting like a fence between the two documents
     <html>
     ...                      Javascript code from the inner document cannot
         <iframe>             access the resources from the main document
               <html>




               </html>

       </iframe>
     ...                      and vice versa
     </html>
Solution to our problem                                     search/static/js/script.js

function hndlr(response)
{
     page = “”
     for (var i = 0; i < response.items.length; i++) {
          var item = response.items[i];
          var link = item.link;
          page += "<br/><div><a onclick="go('"+link+"');" href='#'>"
                  +item.htmlTitle
                  +"</a><br/>"
                  +item.htmlSnippet+
                  + "<br/><a onclick="go('"+link+"');" href='#'>"
                  +link+"</a></div><br/>";
     }


 
   $('#result').html(page);
 
   $('#result').show();
}
Result
Advantages and Limitations




✓   Using an iframe is secure

๏   We cannot modify the page contained in the iframe

➡   We want the define new CSS and Javascript controls for the
    result document
Solution



➡   On the server side

    1. query the Google search using the Python Google API

    2. process the results using Python

    3. return the results to the client
The Google Python API
The Python Google API


•   Download the last release from

        http://code.google.com/p/google-api-python-client/downloads/list

•   Install

    $ tar xvzf google-api-python-client-1.0beta6.tar.gz

    $ cd google-api-python-client-1.0

    $ python setup.py install
Example
                                                                  search2/views.py

from apiclient.discovery import build
from BeautifulSoup import BeautifulSoup
import urllib2
import re


@csrf_exempt
def find(request):
  try:
    service = build("customsearch","v1",
                     developerKey="AIzaSyDBrtHVzXjrvKus_qGpPbTm9rJppIhjxvM")
    res = service.cse().list(q=request.POST['key'],
                             cx='004982958264606934300:2o52rkqdfaw').execute()
    page = urllib2.urlopen(res['items'][0]['link'])
    soup = BeautifulSoup(page).body
  except:
    return HttpResponse("error")
  else:
    return HttpResponse(soup)

More Related Content

What's hot

Meetup Performance
Meetup PerformanceMeetup Performance
Meetup PerformanceGreg Whalin
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVCAlive Kuo
 
How Not to Build a WordPress Plugin
How Not to Build a WordPress PluginHow Not to Build a WordPress Plugin
How Not to Build a WordPress PluginWill Norris
 
Beeline Firebase talk - Firebase event Jun 2017
Beeline Firebase talk - Firebase event Jun 2017Beeline Firebase talk - Firebase event Jun 2017
Beeline Firebase talk - Firebase event Jun 2017Chetan Padia
 
DOM Scripting Toolkit - jQuery
DOM Scripting Toolkit - jQueryDOM Scripting Toolkit - jQuery
DOM Scripting Toolkit - jQueryRemy Sharp
 
ApacheCon NA11 - Apache Celix, Universal OSGi?
ApacheCon NA11 - Apache Celix, Universal OSGi?ApacheCon NA11 - Apache Celix, Universal OSGi?
ApacheCon NA11 - Apache Celix, Universal OSGi?abroekhuis
 
jQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformancejQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformanceJonas De Smet
 
Odoo - CMS performances optimization
Odoo - CMS performances optimizationOdoo - CMS performances optimization
Odoo - CMS performances optimizationOdoo
 
Ajax Performance Tuning and Best Practices
Ajax Performance Tuning and Best PracticesAjax Performance Tuning and Best Practices
Ajax Performance Tuning and Best PracticesDoris Chen
 
I Don't Care About Security (And Neither Should You)
I Don't Care About Security (And Neither Should You)I Don't Care About Security (And Neither Should You)
I Don't Care About Security (And Neither Should You)Joel Lord
 

What's hot (17)

Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Meetup Performance
Meetup PerformanceMeetup Performance
Meetup Performance
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC
 
Jsp
JspJsp
Jsp
 
Presentation
PresentationPresentation
Presentation
 
Micro app-framework
Micro app-frameworkMicro app-framework
Micro app-framework
 
How Not to Build a WordPress Plugin
How Not to Build a WordPress PluginHow Not to Build a WordPress Plugin
How Not to Build a WordPress Plugin
 
Beeline Firebase talk - Firebase event Jun 2017
Beeline Firebase talk - Firebase event Jun 2017Beeline Firebase talk - Firebase event Jun 2017
Beeline Firebase talk - Firebase event Jun 2017
 
DOM Scripting Toolkit - jQuery
DOM Scripting Toolkit - jQueryDOM Scripting Toolkit - jQuery
DOM Scripting Toolkit - jQuery
 
Mashing up JavaScript
Mashing up JavaScriptMashing up JavaScript
Mashing up JavaScript
 
jQuery Best Practice
jQuery Best Practice jQuery Best Practice
jQuery Best Practice
 
ApacheCon NA11 - Apache Celix, Universal OSGi?
ApacheCon NA11 - Apache Celix, Universal OSGi?ApacheCon NA11 - Apache Celix, Universal OSGi?
ApacheCon NA11 - Apache Celix, Universal OSGi?
 
jQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformancejQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and Performance
 
Odoo - CMS performances optimization
Odoo - CMS performances optimizationOdoo - CMS performances optimization
Odoo - CMS performances optimization
 
Ajax Performance Tuning and Best Practices
Ajax Performance Tuning and Best PracticesAjax Performance Tuning and Best Practices
Ajax Performance Tuning and Best Practices
 
I Don't Care About Security (And Neither Should You)
I Don't Care About Security (And Neither Should You)I Don't Care About Security (And Neither Should You)
I Don't Care About Security (And Neither Should You)
 

Similar to Google

Private slideshow
Private slideshowPrivate slideshow
Private slideshowsblackman
 
Guia de Sobrevivência JS no mundo Open Source
Guia de Sobrevivência JS no mundo Open SourceGuia de Sobrevivência JS no mundo Open Source
Guia de Sobrevivência JS no mundo Open SourceLeonardo Balter
 
Building iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" DominoBuilding iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" DominoRob Bontekoe
 
The Principle of Hybrid App.
The Principle of Hybrid App.The Principle of Hybrid App.
The Principle of Hybrid App.musart Park
 
Gae Meets Django
Gae Meets DjangoGae Meets Django
Gae Meets Djangofool2nd
 
Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...
Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...
Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...Uniface
 
Angular directive filter and routing
Angular directive filter and routingAngular directive filter and routing
Angular directive filter and routingjagriti srivastava
 
The Future of CSS with Web components
The Future of CSS with Web componentsThe Future of CSS with Web components
The Future of CSS with Web componentsdevObjective
 
The Future of CSS with Web Components
The Future of CSS with Web ComponentsThe Future of CSS with Web Components
The Future of CSS with Web ComponentsColdFusionConference
 
Some Advanced Tracking in Google Analytics in 5 mins - PhillyJS meet up
Some Advanced Tracking in Google Analytics in 5 mins - PhillyJS meet up Some Advanced Tracking in Google Analytics in 5 mins - PhillyJS meet up
Some Advanced Tracking in Google Analytics in 5 mins - PhillyJS meet up Nico Miceli
 
Acceptance Testing with Webrat
Acceptance Testing with WebratAcceptance Testing with Webrat
Acceptance Testing with WebratLuismi Cavallé
 
HTML5 New and Improved
HTML5   New and ImprovedHTML5   New and Improved
HTML5 New and ImprovedTimothy Fisher
 
How I Learned to Stop Worrying and Love jQuery (Jan 2013)
How I Learned to Stop Worrying and Love jQuery (Jan 2013)How I Learned to Stop Worrying and Love jQuery (Jan 2013)
How I Learned to Stop Worrying and Love jQuery (Jan 2013)David Giard
 
DrupalCon Dublin 2016 - Automated browser testing with Nightwatch.js
DrupalCon Dublin 2016 - Automated browser testing with Nightwatch.jsDrupalCon Dublin 2016 - Automated browser testing with Nightwatch.js
DrupalCon Dublin 2016 - Automated browser testing with Nightwatch.jsVladimir Roudakov
 
After max+phonegap
After max+phonegapAfter max+phonegap
After max+phonegapyangdj
 
混搭移动开发:PhoneGap+JQurey+Dreamweaver
混搭移动开发:PhoneGap+JQurey+Dreamweaver混搭移动开发:PhoneGap+JQurey+Dreamweaver
混搭移动开发:PhoneGap+JQurey+Dreamweaveryangdj
 
PHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHP
PHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHPPHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHP
PHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHPiMasters
 

Similar to Google (20)

Private slideshow
Private slideshowPrivate slideshow
Private slideshow
 
Guia de Sobrevivência JS no mundo Open Source
Guia de Sobrevivência JS no mundo Open SourceGuia de Sobrevivência JS no mundo Open Source
Guia de Sobrevivência JS no mundo Open Source
 
Building iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" DominoBuilding iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" Domino
 
The Principle of Hybrid App.
The Principle of Hybrid App.The Principle of Hybrid App.
The Principle of Hybrid App.
 
Gae Meets Django
Gae Meets DjangoGae Meets Django
Gae Meets Django
 
Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...
Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...
Uniface Lectures Webinar - Building Responsive Applications with Uniface: Dev...
 
Angular directive filter and routing
Angular directive filter and routingAngular directive filter and routing
Angular directive filter and routing
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
The Future of CSS with Web components
The Future of CSS with Web componentsThe Future of CSS with Web components
The Future of CSS with Web components
 
The Future of CSS with Web Components
The Future of CSS with Web ComponentsThe Future of CSS with Web Components
The Future of CSS with Web Components
 
Some Advanced Tracking in Google Analytics in 5 mins - PhillyJS meet up
Some Advanced Tracking in Google Analytics in 5 mins - PhillyJS meet up Some Advanced Tracking in Google Analytics in 5 mins - PhillyJS meet up
Some Advanced Tracking in Google Analytics in 5 mins - PhillyJS meet up
 
Acceptance Testing with Webrat
Acceptance Testing with WebratAcceptance Testing with Webrat
Acceptance Testing with Webrat
 
Angular js
Angular jsAngular js
Angular js
 
HTML5 New and Improved
HTML5   New and ImprovedHTML5   New and Improved
HTML5 New and Improved
 
How I Learned to Stop Worrying and Love jQuery (Jan 2013)
How I Learned to Stop Worrying and Love jQuery (Jan 2013)How I Learned to Stop Worrying and Love jQuery (Jan 2013)
How I Learned to Stop Worrying and Love jQuery (Jan 2013)
 
DrupalCon Dublin 2016 - Automated browser testing with Nightwatch.js
DrupalCon Dublin 2016 - Automated browser testing with Nightwatch.jsDrupalCon Dublin 2016 - Automated browser testing with Nightwatch.js
DrupalCon Dublin 2016 - Automated browser testing with Nightwatch.js
 
After max+phonegap
After max+phonegapAfter max+phonegap
After max+phonegap
 
混搭移动开发:PhoneGap+JQurey+Dreamweaver
混搭移动开发:PhoneGap+JQurey+Dreamweaver混搭移动开发:PhoneGap+JQurey+Dreamweaver
混搭移动开发:PhoneGap+JQurey+Dreamweaver
 
Basics of AngularJS
Basics of AngularJSBasics of AngularJS
Basics of AngularJS
 
PHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHP
PHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHPPHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHP
PHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHP
 

Recently uploaded

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
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 Processorsdebabhi2
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
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 WorkerThousandEyes
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
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 organizationRadu Cotescu
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
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 DevelopmentsTrustArc
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 

Recently uploaded (20)

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
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 convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
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
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 

Google

  • 1. Google Custom Search Rashi Dhing
  • 2. Our web application today • Build a web application for searching SML definitions from the SML Basis Standard Library ✓ We will use Google custom search for building this app ... because we know you like SML!
  • 4. The Google Custom Search API ➡ Use the Google Custom Search API to search over a website or a collection of websites and to embed the results in your web application
  • 5. 3 ways to use Google Custom search • Google snippet • Google Javascript API (client side) • Google Python API (server side)
  • 7. Step 1 - go to Google Custom Search
  • 8. Step 2 - sign in with your Google account
  • 9. Step 3 - Setup a search engine
  • 10. Step 3 - Copy the generated code snippet
  • 11. Step 4 - Paste the code snippet in your page engine/templates/engine/index.html ... <body> <div id="cse-search-form" style="width: 100%;">Loading</div> <script src="//www.google.com/jsapi" type="text/javascript"></script> <script type="text/javascript"> google.load('search', '1', {language : 'en', style : google.loader.themes.SHINY}); google.setOnLoadCallback(function() { var customSearchControl = new google.search.CustomSearchControl('004982958264606934300:2o52rkqdfaw'); customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET); var options = new google.search.DrawOptions(); options.setSearchFormRoot('cse-search-form'); customSearchControl.draw('cse', options); }, true); </script> <div id="cse" style="width:100%;"></div> <body></html>
  • 12. Step 4 - Paste the code snippet in your page engine/templates/engine/index.html ... Your Custom Search Identifier <body> (aka CX or CSEid) <div id="cse-search-form" style="width: 100%;">Loading</div> <script src="//www.google.com/jsapi" type="text/javascript"></script> <script type="text/javascript"> google.load('search', '1', {language : 'en', style : google.loader.themes.SHINY}); google.setOnLoadCallback(function() { var customSearchControl = new google.search.CustomSearchControl('004982958264606934300:2o52rkqdfaw'); customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET); var options = new google.search.DrawOptions(); options.setSearchFormRoot('cse-search-form'); customSearchControl.draw('cse', options); }, true); </script> <div id="cse" style="width:100%;"></div> <body></html>
  • 13. Step 4 - Paste the code snippet in your page engine/templates/engine/index.html ... Your Custom Search Identifier <body> (aka CX or CSEid) <div id="cse-search-form" style="width: 100%;">Loading</div> <script src="//www.google.com/jsapi" type="text/javascript"></script> <script type="text/javascript"> google.load('search', '1', {language : 'en', style : google.loader.themes.SHINY}); google.setOnLoadCallback(function() { var customSearchControl = new google.search.CustomSearchControl('004982958264606934300:2o52rkqdfaw'); customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET); var options = new google.search.DrawOptions(); options.setSearchFormRoot('cse-search-form'); customSearchControl.draw('cse', options); }, true); </script> The div element where to <div id="cse" style="width:100%;"></div> show the results <body></html>
  • 15. Advantages and Limitations ✓ Very easy to use ๏ The results are shown in a new tab/window ➡ We want the results to be embedded in the same page
  • 16. Solution ➡ On the client side 1. query the Google search using the Google Javascript API 2. process the results using Javascript 3. show the results in the page
  • 18. Get your Google API key from the API Console
  • 19. Search Request search/static/js/script.js function client() { $('#result').html('<script src="https://www.googleapis.com/customsearch/v1? key=AIzaSyDBrtHVzXjrvKus_qGpPbTm9rJppIhjxvM& cx=004982958264606934300:2o52rkqdfaw& q='+$('#inp').val()+'& callback=hndlr"></script>'); } function hndlr(response) { .... }
  • 20. Search Request search/static/js/script.js function client() { $('#result').html('<script src="https://www.googleapis.com/customsearch/v1? key=AIzaSyDBrtHVzXjrvKus_qGpPbTm9rJppIhjxvM& Your API key cx=004982958264606934300:2o52rkqdfaw& q='+$('#inp').val()+'& callback=hndlr"></script>'); } function hndlr(response) { .... }
  • 21. Search Request search/static/js/script.js function client() { $('#result').html('<script src="https://www.googleapis.com/customsearch/v1? key=AIzaSyDBrtHVzXjrvKus_qGpPbTm9rJppIhjxvM& Your API key cx=004982958264606934300:2o52rkqdfaw& q='+$('#inp').val()+'& Your custom search engine id callback=hndlr"></script>'); } function hndlr(response) { .... }
  • 22. Search Request search/static/js/script.js function client() { $('#result').html('<script src="https://www.googleapis.com/customsearch/v1? key=AIzaSyDBrtHVzXjrvKus_qGpPbTm9rJppIhjxvM& Your API key cx=004982958264606934300:2o52rkqdfaw& q='+$('#inp').val()+'& Your search query Your custom search engine id callback=hndlr"></script>'); } function hndlr(response) { .... }
  • 23. Search Request search/static/js/script.js function client() { $('#result').html('<script src="https://www.googleapis.com/customsearch/v1? key=AIzaSyDBrtHVzXjrvKus_qGpPbTm9rJppIhjxvM& Your API key cx=004982958264606934300:2o52rkqdfaw& q='+$('#inp').val()+'& Your search query Your custom search engine id callback=hndlr"></script>'); } function hndlr(response) { Your callback method .... }
  • 24. The callback method ➡ The call method (called hndlr in the example) defines what to do with the search results
  • 25. Example search/static/js/script.js function hndlr(response) { page = “” for (var i = 0; i < response.items.length; i++) { var item = response.items[i]; var link = item.link; page += "<br/><div><a onclick="go('"+link+"');" href='#'>" +item.htmlTitle +"</a><br/>" +item.htmlSnippet+ + "<br/><a onclick="go('"+link+"');" href='#'>" +link+"</a></div><br/>"; } $('#result').html(page); $('#result').show(); }
  • 26. Example search/static/js/script.js function hndlr(response) For each search result ... { page = “” for (var i = 0; i < response.items.length; i++) { var item = response.items[i]; var link = item.link; page += "<br/><div><a onclick="go('"+link+"');" href='#'>" +item.htmlTitle +"</a><br/>" +item.htmlSnippet+ + "<br/><a onclick="go('"+link+"');" href='#'>" +link+"</a></div><br/>"; } $('#result').html(page); $('#result').show(); }
  • 27. Example search/static/js/script.js function hndlr(response) For each search result ... { page = “” for (var i = 0; i < response.items.length; i++) { var item = response.items[i]; var link = item.link; page += "<br/><div><a onclick="go('"+link+"');" href='#'>" +item.htmlTitle +"</a><br/>" +item.htmlSnippet+ + "<br/><a onclick="go('"+link+"');" href='#'>" +link+"</a></div><br/>"; } $('#result').html(page); ... display the search result but change the target url $('#result').show(); address so that the link opens in the current page rather than opening a new one }
  • 29. Problem ๏ Nothing happens when you click on the link ➡ No bug shown except ...
  • 30. Problem ๏ Nothing happens when you click on the link ➡ No bug shown except ... This is a Cross Domain error
  • 31. Cross Domain restriction (aka Same Origin Policy) ”The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites.” Wikipedia
  • 32. Solution - use an iframe • An <iframe> can contains another HTML document possibly coming from another domain ➡ Like a webpage inside a webpage ✓ An iFrame is acting like a fence between the two documents <html> ... <iframe> <html> </html> </iframe> ... </html>
  • 33. Solution - use an iframe • An <iframe> can contains another HTML document possibly coming from another domain ➡ Like a webpage inside a webpage ✓ An iFrame is acting like a fence between the two documents <html> ... Javascript code from the inner document cannot <iframe> access the resources from the main document <html> </html> </iframe> ... </html>
  • 34. Solution - use an iframe • An <iframe> can contains another HTML document possibly coming from another domain ➡ Like a webpage inside a webpage ✓ An iFrame is acting like a fence between the two documents <html> ... Javascript code from the inner document cannot <iframe> access the resources from the main document <html> </html> </iframe> ... and vice versa </html>
  • 35. Solution to our problem search/static/js/script.js function hndlr(response) { page = “” for (var i = 0; i < response.items.length; i++) { var item = response.items[i]; var link = item.link; page += "<br/><div><a onclick="go('"+link+"');" href='#'>" +item.htmlTitle +"</a><br/>" +item.htmlSnippet+ + "<br/><a onclick="go('"+link+"');" href='#'>" +link+"</a></div><br/>"; } $('#result').html(page); $('#result').show(); }
  • 37. Advantages and Limitations ✓ Using an iframe is secure ๏ We cannot modify the page contained in the iframe ➡ We want the define new CSS and Javascript controls for the result document
  • 38. Solution ➡ On the server side 1. query the Google search using the Python Google API 2. process the results using Python 3. return the results to the client
  • 40. The Python Google API • Download the last release from http://code.google.com/p/google-api-python-client/downloads/list • Install $ tar xvzf google-api-python-client-1.0beta6.tar.gz $ cd google-api-python-client-1.0 $ python setup.py install
  • 41. Example search2/views.py from apiclient.discovery import build from BeautifulSoup import BeautifulSoup import urllib2 import re @csrf_exempt def find(request): try: service = build("customsearch","v1", developerKey="AIzaSyDBrtHVzXjrvKus_qGpPbTm9rJppIhjxvM") res = service.cse().list(q=request.POST['key'], cx='004982958264606934300:2o52rkqdfaw').execute() page = urllib2.urlopen(res['items'][0]['link']) soup = BeautifulSoup(page).body except: return HttpResponse("error") else: return HttpResponse(soup)

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n