您的位置:首页 > 移动开发 > 微信开发

豆瓣搜索—微信公共平台查询功能

2015-05-06 16:39 309 查看
该篇将主要介绍通过豆瓣api查询书籍相关信息,并组装成微信的图文信息发动到微信客户端。

首先我们需要通过豆瓣书籍api,查询到书籍的相关信息

#!/bin/env python
# -*- coding: utf-8 -*-

import urllib, urllib2, json
from config import DOUBAN_APIKEY

# 访问豆瓣API获取书籍数据
BOOK_URL_BASE = 'http://api.douban.com/v2/book/search'

# 通过豆瓣API获取书籍数据,然后把数据格式化成特定的格式:
# [{"title":"失控", "description":"", "image":"http://xxx", "url":"http://xxx"},
# {"title":"失控", "description":"", "image":"http://xxx", "url":"http://xxx"},
# {"title":"失控", "description":"", "image":"http://xxx", "url":"http://xxx"}]
def search_book(q):
params = {'q': q.encode('utf-8'), 'apikey': DOUBAN_APIKEY, 'count': 3}
url = BOOK_URL_BASE + '?' + urllib.urlencode(params)
resp = urllib2.urlopen(url)
r = json.loads(resp.read())
books = r['books']

bookList = []
for i, book in enumerate(books):
item = {}
title = u'%s\t%s分\n%s\n%s\t%s' % (
book['title'], book['rating']['average'], ','.join(book['author']), book['publisher'], book['price'])
description = ''
picUrl = book['images']['large'] if i == 1 else book['images']['small']
url = book['alt']
item['title'] = title
item['description'] = description
item['image'] = picUrl
item['url'] = url
bookList.append(item)

return bookList
通过豆瓣书籍搜索api,可以获取到书籍的详细描述信息,我们只需要获取该书籍相关的前三条信息就可以,所以参数count设置为3.豆瓣api具体使用方法可以到豆瓣api,查看其相关文档。

搜索的结果要格式化为特定的格式,然后组装成微信的图文混合消息返回到微信客户端,最终会把这些信息格式化为

[{"title":"失控", "description":"", "image":"http://xxx", "url":"http://xxx"},
{"title":"失控", "description":"", "image":"http://xxx", "url":"http://xxx"},
{"title":"失控", "description":"", "image":"http://xxx", "url":"http://xxx"}]
接下来我们就要使用搜索之后的特定格式数据组装成微信图文混合消息,具体代码如下:

msg = parse_message(request.data)
if msg.type == 'text':
reply = create_reply(douban_book.search_book(msg.content), msg)
else:
reply = create_reply('Sorry, can not handle this for now', msg)
return reply.render()

上述代码中,我们使用了wechatpy中的create_reply函数把书籍信息列表格式化为微信的图文混合消息,并返回到微信客户端



源码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: