Posted by:Phodal HuangOct. 25, 2015, 9:29 p.m. 在写书的事业上忙了一段时间,终于想在周末抽出点时间来整理一下我的博客,先是修了几个bug。后来,想了想决定加上微信功能,好在一会就完成了。 在Github上找到了一个微信公众平台的SDK:wechat-python-sdk,里面提供了一堆官方SDK的功能,也提供了一些非官方SDK的功能。 Django Wechat与Django集成便是蛮方便的,于是在网上找到了一个DEMO,先将appid等定义在local_settings中,避免发生意外。。。。 再初始化这个instance: from MK_dream.local_settings import WECHAT_TOKEN, AppID, AppSecretwechat_instance = WechatBasic( token=WECHAT_TOKEN, appid=AppID, appsecret=AppSecret) 接着就是从request中提取相关信息了: @csrf_exemptdef wechat(request): if request.method == 'GET': # 检验合法性 # 从 request 中提取基本信息 (signature, timestamp, nonce, xml) signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') 接着从instance中获取消息: message = wechat_instance.get_message() 如果,消息的内容是博客就返回最新的博客。。。 if isinstance(message, TextMessage): # 当前会话内容 content = message.content.strip() if content == '博客' or content == 'blog' or content == '最新': return HttpResponse(wechat_instance.response_news(get_new_blogposts(request)), content_type='application/xml') if content == '功能': reply_text = ( '目前支持的功能:最新博客、博客搜索\n' + '回复【最新】或者【博客】,将返回最新博客' + '回复【search:ionic】,将搜索ionic相关内容 \n' + '正在实现: Google、Wiki' ) response = wechat_instance.response_text(content=reply_text) return HttpResponse(response, content_type='application/xml') 看上去还算挺简单的。 |
|