SlideShare a Scribd company logo
1 of 13
TwD Chapter 12
Adding External
Search Functionality
asika Kuo
For Django Summer
Django Summer 2
12. Adding External Search
Functionality
●
本章要利用 Bing API 替 APP 增加搜尋功能
Django Summer 3
12.1. The Bing Search API
●
把用 Bing 搜尋到的資料顯示在自己的 APP 裡
●
Bing 伺服器回傳的 result 可以是 XML 或 JSON (可以自己
指定)
Django Summer 4
12.1.1. Registering for a Bing API Key
●
註冊 MS 的帳號(可以直接用 hotmail 的)
– https://account.windowsazure.com
●
到 Windows Azure Marketplace Bing Search API page 訂
閱免費版搜尋 API 服務
– 5,000 Transactions/month
Django Summer 5
12.2. Adding Search Functionality
●
建立 rango/bing_search.py
Django Summer 6
12.2. Adding Search Functionality
●
根據 API 的規定準備
好我們要送出的
request 字串
def run_query(search_terms):
root_url =
'https://api.datamarket.azure.com/Bing/Search/'
source = 'Web'
results_per_page = 10
offset = 0
query = "'{0}'".format(search_terms)
query = urllib.quote(query)
search_url = "{0}{1}?
$format=json&$top={2}&$skip={3}&Query={4}".format(
root_url,
source,
results_per_page,
offset,
query)
Django Summer 7
12.2. Adding Search Functionality
●
利用 urllib2 的
password manager
在送出的 HTTP
request header 中加
入我們剛申請好的
API Key 資訊
●
# Setup authentication with the Bing servers.
# The username MUST be a blank string, and put in
your API key!
username = ''
bing_api_key = '<api_key>'
# Create a 'password manager' which handles
authentication for us.
password_mgr =
urllib2.HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(None, search_url,
username, bing_api_key)
Django Summer 8
● HTTP Basic Authentication
– 在用戶端發送 request 時一併於 HTTP header 提供用戶名和密碼的一
種簡易認證方式
– 預設會將 <username>:<password> 用 Base64 編碼後送出
●
不是為了安全性而是為了轉換掉與 HTTP 不相容的字元
●
Bing 規定的 API Key 認證方式
– Username: 空字串
– Password: 申請到的 API Key
Django Summer 9
12.2. Adding Search Functionality
●
用 urllib2.openurl()
連同 query string 和
認證資訊一起送出
●
接到的 response 會
是字串格式的 JSON
●
用 json.loads() 轉成
python dictionary
# Prepare for connecting to Bing's servers.
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)
# Connect to the server and read the response generated.
response = urllib2.urlopen(search_url).read()
# Convert the string response to a Python dictionary object.
json_response = json.loads(response)
# Loop through each page returned, populating out results list.
for result in json_response['d']['results']:
results.append({
'title': result['Title'],
'link': result['Url'],
'summary': result['Description']})
Django Summer 10
12.3. Putting Search into Rango
●
建立
templates/rango/se
arch.html
– 如果有傳入
result_list 就把內
容 render 到頁面
上
{% if result_list %}
<!-- Display search results in an ordered list -->
<div style="clear: both;">
<ol>
{% for result in result_list %}
<li>
<strong><a
href="{{ result.link }}">{{ result.title }}</a></strong>
<br />
<em>{{ result.summary }}</em>
</li>
{% endfor %}
</ol>
</div>
{% endif %}
Django Summer 11
12.3.2. Adding the View
def search(request):
context = RequestContext(request)
result_list = []
if request.method == 'POST':
query = request.POST['query'].strip()
if query:
# Run our Bing function to get the
results list!
result_list = run_query(query)
return
render_to_response('rango/search.html',
{'result_list': result_list}, context)
Django Summer 12
處理 Unicode
● run_query() 預設處理的格式是 str
– query = "'{0}'".format(search_terms)
● 從前端傳回來的 query string 是 unicode
– 包含英文以外的字元, format() 就會發生
UnicodeEncodeError
● 解法
– 呼叫 unicode 的 format()
● query = u"'{0}'".format(search_terms)
●
Django Summer 13
處理 Unicode
● urllib.quote() 傳入 unicode 字串發生 KeyError
● 解法
– 把 query 字串編碼為 UTF-8
– query = urllib.quote(query.encode('utf-8'))

More Related Content

What's hot

What's hot (13)

Node.js and Parse
Node.js and ParseNode.js and Parse
Node.js and Parse
 
Altitude NY 2018: 132 websites, 1 service: Your local news runs on Fastly
Altitude NY 2018: 132 websites, 1 service: Your local news runs on FastlyAltitude NY 2018: 132 websites, 1 service: Your local news runs on Fastly
Altitude NY 2018: 132 websites, 1 service: Your local news runs on Fastly
 
Building Android apps with Parse
Building Android apps with ParseBuilding Android apps with Parse
Building Android apps with Parse
 
Contract-driven development with OpenAPI 3 and Vert.x | DevNation Tech Talk
Contract-driven development with OpenAPI 3 and Vert.x | DevNation Tech TalkContract-driven development with OpenAPI 3 and Vert.x | DevNation Tech Talk
Contract-driven development with OpenAPI 3 and Vert.x | DevNation Tech Talk
 
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech TalkHacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
 
robrighter's Node.js presentation for DevChatt
robrighter's Node.js presentation for DevChattrobrighter's Node.js presentation for DevChatt
robrighter's Node.js presentation for DevChatt
 
Intro to Google Apps Script
Intro to Google Apps ScriptIntro to Google Apps Script
Intro to Google Apps Script
 
gunicorn introduction
gunicorn introductiongunicorn introduction
gunicorn introduction
 
VBA API for scriptDB primer
VBA API for scriptDB primerVBA API for scriptDB primer
VBA API for scriptDB primer
 
App script
App scriptApp script
App script
 
Pythonの勉強がてら死活監視ツールを作った話
Pythonの勉強がてら死活監視ツールを作った話Pythonの勉強がてら死活監視ツールを作った話
Pythonの勉強がてら死活監視ツールを作った話
 
Server Logs: After Excel Fails
Server Logs: After Excel FailsServer Logs: After Excel Fails
Server Logs: After Excel Fails
 
Do something in 5 with gas 9-copy between databases with oauth2
Do something in 5 with gas 9-copy between databases with oauth2Do something in 5 with gas 9-copy between databases with oauth2
Do something in 5 with gas 9-copy between databases with oauth2
 

Viewers also liked (7)

Bahasa Inggris IX
Bahasa Inggris IXBahasa Inggris IX
Bahasa Inggris IX
 
Social media sentinel
Social media sentinelSocial media sentinel
Social media sentinel
 
TangoWithDjango - ch8
TangoWithDjango - ch8TangoWithDjango - ch8
TangoWithDjango - ch8
 
Inggris1
Inggris1Inggris1
Inggris1
 
нептун
нептуннептун
нептун
 
tangowithdjango - Ch15
tangowithdjango - Ch15tangowithdjango - Ch15
tangowithdjango - Ch15
 
History of the Caldecott Medal
History of the Caldecott MedalHistory of the Caldecott Medal
History of the Caldecott Medal
 

Similar to tangowithdjango - Ch12

Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
MongoDB
 
Introduction to App Engine Development
Introduction to App Engine DevelopmentIntroduction to App Engine Development
Introduction to App Engine Development
Ron Reiter
 
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptxWRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
salemsg
 
An Overview of Node.js
An Overview of Node.jsAn Overview of Node.js
An Overview of Node.js
Ayush Mishra
 

Similar to tangowithdjango - Ch12 (20)

Itb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinItb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin Pickin
 
Google app-engine-with-python
Google app-engine-with-pythonGoogle app-engine-with-python
Google app-engine-with-python
 
Dropwizard with MongoDB and Google Cloud
Dropwizard with MongoDB and Google CloudDropwizard with MongoDB and Google Cloud
Dropwizard with MongoDB and Google Cloud
 
Akash rajguru project report sem v
Akash rajguru project report sem vAkash rajguru project report sem v
Akash rajguru project report sem v
 
Firestore MENA digital days : GDG Abu dhabi
Firestore MENA digital days : GDG Abu dhabiFirestore MENA digital days : GDG Abu dhabi
Firestore MENA digital days : GDG Abu dhabi
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
 
MongoDB and Node.js
MongoDB and Node.jsMongoDB and Node.js
MongoDB and Node.js
 
Webinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.jsWebinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.js
 
Webinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.jsWebinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.js
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
 
Webinar: AngularJS and the WordPress REST API
Webinar: AngularJS and the WordPress REST APIWebinar: AngularJS and the WordPress REST API
Webinar: AngularJS and the WordPress REST API
 
Webinar: AngularJS and the WordPress REST API
Webinar: AngularJS and the WordPress REST APIWebinar: AngularJS and the WordPress REST API
Webinar: AngularJS and the WordPress REST API
 
Angular 2
Angular 2Angular 2
Angular 2
 
Dive into AngularJS and directives
Dive into AngularJS and directivesDive into AngularJS and directives
Dive into AngularJS and directives
 
Introduction to App Engine Development
Introduction to App Engine DevelopmentIntroduction to App Engine Development
Introduction to App Engine Development
 
Gohan
GohanGohan
Gohan
 
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptxWRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
 
An Overview of Node.js
An Overview of Node.jsAn Overview of Node.js
An Overview of Node.js
 
Angular Js Basics
Angular Js BasicsAngular Js Basics
Angular Js Basics
 
2016 - Serverless Microservices on AWS with API Gateway and Lambda
2016 - Serverless Microservices on AWS with API Gateway and Lambda2016 - Serverless Microservices on AWS with API Gateway and Lambda
2016 - Serverless Microservices on AWS with API Gateway and Lambda
 

Recently uploaded

Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
dharasingh5698
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdf
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 

tangowithdjango - Ch12

  • 1. TwD Chapter 12 Adding External Search Functionality asika Kuo For Django Summer
  • 2. Django Summer 2 12. Adding External Search Functionality ● 本章要利用 Bing API 替 APP 增加搜尋功能
  • 3. Django Summer 3 12.1. The Bing Search API ● 把用 Bing 搜尋到的資料顯示在自己的 APP 裡 ● Bing 伺服器回傳的 result 可以是 XML 或 JSON (可以自己 指定)
  • 4. Django Summer 4 12.1.1. Registering for a Bing API Key ● 註冊 MS 的帳號(可以直接用 hotmail 的) – https://account.windowsazure.com ● 到 Windows Azure Marketplace Bing Search API page 訂 閱免費版搜尋 API 服務 – 5,000 Transactions/month
  • 5. Django Summer 5 12.2. Adding Search Functionality ● 建立 rango/bing_search.py
  • 6. Django Summer 6 12.2. Adding Search Functionality ● 根據 API 的規定準備 好我們要送出的 request 字串 def run_query(search_terms): root_url = 'https://api.datamarket.azure.com/Bing/Search/' source = 'Web' results_per_page = 10 offset = 0 query = "'{0}'".format(search_terms) query = urllib.quote(query) search_url = "{0}{1}? $format=json&$top={2}&$skip={3}&Query={4}".format( root_url, source, results_per_page, offset, query)
  • 7. Django Summer 7 12.2. Adding Search Functionality ● 利用 urllib2 的 password manager 在送出的 HTTP request header 中加 入我們剛申請好的 API Key 資訊 ● # Setup authentication with the Bing servers. # The username MUST be a blank string, and put in your API key! username = '' bing_api_key = '<api_key>' # Create a 'password manager' which handles authentication for us. password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, search_url, username, bing_api_key)
  • 8. Django Summer 8 ● HTTP Basic Authentication – 在用戶端發送 request 時一併於 HTTP header 提供用戶名和密碼的一 種簡易認證方式 – 預設會將 <username>:<password> 用 Base64 編碼後送出 ● 不是為了安全性而是為了轉換掉與 HTTP 不相容的字元 ● Bing 規定的 API Key 認證方式 – Username: 空字串 – Password: 申請到的 API Key
  • 9. Django Summer 9 12.2. Adding Search Functionality ● 用 urllib2.openurl() 連同 query string 和 認證資訊一起送出 ● 接到的 response 會 是字串格式的 JSON ● 用 json.loads() 轉成 python dictionary # Prepare for connecting to Bing's servers. handler = urllib2.HTTPBasicAuthHandler(password_mgr) opener = urllib2.build_opener(handler) urllib2.install_opener(opener) # Connect to the server and read the response generated. response = urllib2.urlopen(search_url).read() # Convert the string response to a Python dictionary object. json_response = json.loads(response) # Loop through each page returned, populating out results list. for result in json_response['d']['results']: results.append({ 'title': result['Title'], 'link': result['Url'], 'summary': result['Description']})
  • 10. Django Summer 10 12.3. Putting Search into Rango ● 建立 templates/rango/se arch.html – 如果有傳入 result_list 就把內 容 render 到頁面 上 {% if result_list %} <!-- Display search results in an ordered list --> <div style="clear: both;"> <ol> {% for result in result_list %} <li> <strong><a href="{{ result.link }}">{{ result.title }}</a></strong> <br /> <em>{{ result.summary }}</em> </li> {% endfor %} </ol> </div> {% endif %}
  • 11. Django Summer 11 12.3.2. Adding the View def search(request): context = RequestContext(request) result_list = [] if request.method == 'POST': query = request.POST['query'].strip() if query: # Run our Bing function to get the results list! result_list = run_query(query) return render_to_response('rango/search.html', {'result_list': result_list}, context)
  • 12. Django Summer 12 處理 Unicode ● run_query() 預設處理的格式是 str – query = "'{0}'".format(search_terms) ● 從前端傳回來的 query string 是 unicode – 包含英文以外的字元, format() 就會發生 UnicodeEncodeError ● 解法 – 呼叫 unicode 的 format() ● query = u"'{0}'".format(search_terms) ●
  • 13. Django Summer 13 處理 Unicode ● urllib.quote() 傳入 unicode 字串發生 KeyError ● 解法 – 把 query 字串編碼為 UTF-8 – query = urllib.quote(query.encode('utf-8'))