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

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 FastlyFastly
 
Building Android apps with Parse
Building Android apps with ParseBuilding Android apps with Parse
Building Android apps with ParseDroidConTLV
 
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 TalkRed Hat Developers
 
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 TalkRed Hat Developers
 
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 DevChattrobrighter
 
Intro to Google Apps Script
Intro to Google Apps ScriptIntro to Google Apps Script
Intro to Google Apps Scriptmodmonstr
 
gunicorn introduction
gunicorn introductiongunicorn introduction
gunicorn introductionAdam Lowry
 
VBA API for scriptDB primer
VBA API for scriptDB primerVBA API for scriptDB primer
VBA API for scriptDB primerBruce McPherson
 
Pythonの勉強がてら死活監視ツールを作った話
Pythonの勉強がてら死活監視ツールを作った話Pythonの勉強がてら死活監視ツールを作った話
Pythonの勉強がてら死活監視ツールを作った話虎の穴 開発室
 
Server Logs: After Excel Fails
Server Logs: After Excel FailsServer Logs: After Excel Fails
Server Logs: After Excel FailsOliver Mason
 
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 oauth2Bruce McPherson
 

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

TangoWithDjango - ch8
TangoWithDjango - ch8TangoWithDjango - ch8
TangoWithDjango - ch8Asika Kuo
 
нептун
нептуннептун
нептунDRNanno
 
tangowithdjango - Ch15
tangowithdjango - Ch15tangowithdjango - Ch15
tangowithdjango - Ch15Asika Kuo
 
History of the Caldecott Medal
History of the Caldecott MedalHistory of the Caldecott Medal
History of the Caldecott Medalcutebluefrog
 

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 Add external Bing search to Django app

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 PickinGavin Pickin
 
Google app-engine-with-python
Google app-engine-with-pythonGoogle app-engine-with-python
Google app-engine-with-pythonDeepak Garg
 
Dropwizard with MongoDB and Google Cloud
Dropwizard with MongoDB and Google CloudDropwizard with MongoDB and Google Cloud
Dropwizard with MongoDB and Google CloudYun Zhi Lin
 
Akash rajguru project report sem v
Akash rajguru project report sem vAkash rajguru project report sem v
Akash rajguru project report sem vAkash Rajguru
 
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 dhabiShashank Kakroo
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBTobias Trelle
 
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.jsMongoDB
 
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.jsMongoDB
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBMongoDB
 
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 APIWP Engine
 
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 APIWP Engine UK
 
Introduction to App Engine Development
Introduction to App Engine DevelopmentIntroduction to App Engine Development
Introduction to App Engine DevelopmentRon Reiter
 
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptxWRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptxsalemsg
 
An Overview of Node.js
An Overview of Node.jsAn Overview of Node.js
An Overview of Node.jsAyush Mishra
 
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 Lambdadevopsdaysaustin
 

Similar to Add external Bing search to Django app (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

Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
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...roncy bisnoi
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
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.pdfankushspencer015
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 

Recently uploaded (20)

Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
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...
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
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
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 

Add external Bing search to Django app

  • 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'))