Message connection method for WeChat public development

Source: Internet
Author: User
This article explains how to enable public development and use the message connection method.

Because I have designed an article to implement a robot and respond to users, this app is very simple and does not need to be designed in depth. my thoughts are as follows, anyway, for so many blog systems written in python on github, I only need to implement the response part, that is, to obtain the article data from the database, and then set the article title, url, the image and other information are packaged into xml format and returned to the server, and then to the user. In addition, I found that menus would be much better, just like a complete app. you can click to view an article instead of a reply from a hard state. I used a blog system written by someone else to transform it-saepy-log. this blog system is based on the tornado framework. I didn't want to touch tornado, but I had to dig into it. I encountered a lot of difficulties in writing like statements in SQL statements and reading documents.

Deployment and development

I have explained in advance that I may not be able to follow this article because of all kinds of tossing and tossing. After downloading the source code of saepy-log, follow these steps to upload the source code. then, you can install the blog system on the sae platform, use svn to synchronize the code to the local working directory. everything is ready.

What we want to modify is that blog. py is the core function of the blog, and modle. py is the key to the data model. we will expand the data model function to complete our functions.

Add our function class weixin. py in blog. py (because the tornado framework is used, the method is slightly different from that in django ):

Import required packages

# weixin used packageimport xml.etree.ElementTree as ETimport urllib,urllib2,time,hashlib                                               import tornado.wsgiimport tornado.escape

Mainly xml parsing and some packages that process strings. next we define the subject of the weixin class:

# Add the push account class WeiXinPoster (BaseHandler): # handler # handle the get method corresponding to check_signature def get (self): global TOKEN signature = self. get_argument ("signature") timestamp = self. get_argument ("timestamp") nonce = self. get_argument ("nonce") echoStr = self. get_argument ("echostr") token = TOKEN tmpList = [token, timestamp, nonce] tmpList. sort () tmpstr = "% S" % tuple (tmpList) tmpstr = hashlib. sha1 (tmpstr ). hexdigest () if tmpstr = signature: self. write (echoStr) # return echoStr else: self. write (None); # return None # handle the post method, corresponding to response_msg def post (self): global SORRY # retrieve the request text rawStr = self from the request. request. body # parse the text to obtain the requested data msg = self. parse_request_xml (ET. fromstring (rawStr) # query_str = msg is returned for processing content based on the request message. get ("Content") query_str = torna Do. escape. utf8 (query_str) # The Data types sent by the TODO user may vary, so you need to determine response_msg = "" return_data = "" # use simple processing logic, if query_str [0] = "h": # send help menu to user response_msg = self. get_help_menu () # returned message # Including post_msg, and corresponding response_msg if response_msg: return_data = self. pack_text_xml (msg, response_msg) else: response_msg = SORRY return_data = self. pack_text_xml (msg, response_msg) self. write (return_data) # Classification elif query_str [0] = "c": category = query_str [1:] response_msg = self. get_category_articles (category) if response_msg: return_data = self. pack_news_xml (msg, response_msg) else: response_msg = SORRY return_data = self. pack_text_xml (msg, response_msg) self. write (return_data) # List articles elif query_str [0] = "l": response_msg = self. get_article_list () if response_msg: return_data = self. pack_text_x Ml (msg, response_msg) else: response_msg = SORRY return_data = self. pack_text_xml (msg, response_msg) self. write (return_data) # directly obtain an article elif query_str [0] = "a": # directly obtain the article id, then, query article_id = int (query_str [1:]) in the database # perform the response_msg = self operation. get_response_article_by_id (article_id) if response_msg: return_data = self. pack_news_xml (msg, response_msg) else: response_msg = SORRY return_data = self. pac K_text_xml (msg, response_msg) self. write (return_data) # consider other elif query_str [0] = "s": keyword = str (query_str [1:]) # search for keywords and return response_msg = self. get_response_article (keyword) # returns the text information if response_msg: return_data = self. pack_news_xml (msg, response_msg) else: response_msg = SORRY return_data = self. pack_text_xml (msg, response_msg) self. write (return_data) elif query_str [0] = "n": response_m Sg = self. get_latest_articles () # returns the text information if response_msg: return_data = self. pack_news_xml (msg, response_msg) else: response_msg = SORRY return_data = self. pack_text_xml (msg, response_msg) self. write (return_data) # if no help is found, else: response_msg = get_help_menu () if response_msg: return_data = response_msg else: return_data = SORRY self is returned. write (return_data) # n for getting the latest article def get_latest_articles (s Elf): global MAX_ARTICLE global PIC_URL article_list = Article. condition () article_list_length = len (article_list) count = (article_list_length <MAX_ARTICLE) and article_list_length or MAX_ARTICLE if article_list: # construct a text message articles_msg = {'articles ': []} for I in range (0, count): article = {'Title': article_list [I]. slug, 'description': article_list [I]. description, 'picurl': PIC_URL, 'Ur L': article_list [I]. absolute_url} # insert article articles_msg ['articles']. append (article) article = {}# return the article return articles_msg # Parser # parse the request and disassemble it into a dictionary def parse_request_xml (self, root_elem ): msg = {} if root_elem.tag = 'xml': for child in root_elem: msg [child. tag] = child. text # get the content return msg #------------------------------------------- ---------------------------- Def get_help_menu (self): menu_msg = ''' Welcome to the Nanyuan essay. here you can get information and stories about the campus. Reply to the following button to get the corresponding response h: help l: article list f: Get category list n: Get the latest article a + number: view an article a2 View 2nd articles s + Keywords: search related articles s scientific research View scientific research c + classification name: Get classification articles c campus life View campus life classification others: features to be enriched '''return menu_msg # Article # retrieve the Article list def get_article_list (self): # query the database to obtain the Article list article_list = Article. get_all_article_list () article_list_str = "the latest article list is available for you to read. reply to a + number to read: \ n" for I in range (len (article_list )): art_id = str (article_list [I]. id) art_id = tornado. escape. native_str (art_id) art_title = article_list [I]. title art_title = tornado. escape. native_str (art_title) art_category = article_list [I]. category art_category = tornado. escape. native_str (art_category) article_list_str + = art_id + ''+ art_title +'' + art_category + '\ n' return article_list_str # Query def get_category_articles (self, category) by category ): global MAX_ARTICLE global PIC_URL article_list = Article. inline (category) article_list_length = len (article_list) count = (article_list_length <MAX_ARTICLE) and article_list_length or MAX_ARTICLE if article_list: # construct a text message articles_msg = {'articles ': []} for I in range (0, count): article = {'Title': article_list [I]. slug, 'description': article_list [I]. description, 'picurl': PIC_URL, 'URL': article_list [I]. absolute_url} # insert article articles_msg ['articles']. append (article) article ={}# return the article return articles_msg # Response # obtain the msg def get_response_article (self, keyword) used to return: global PIC_URL keyword = str (keyword) # get several articles from database query: article = Article. get_article_by_keyword (keyword) # first use the test data if article: title = article. slug description = article. description picUrl = PIC_URL url = article. absolute_url count = 1 # There may also be several articles # Here we implement the relevant logic, get the content from the database # construct the text message articles_msg = {'articles ': []} for I in range (0, count): article = {'Title': title, 'description': description, 'picurl': picUrl, 'URL ': url} # insert article articles_msg ['articles']. append (article) article = {}# return the article return articles_msg else: return def get_response_article_by_id (self, post_id): global PIC_URL # obtain several articles from database query: Article = article. get_article_by_id_detail (post_id) # postId is the document id if article: title = article. slug description = article. description picUrl = PIC_URL url = article. absolute_url count = 1 # implement the relevant logic here, get the content from the database # construct a text message articles_msg = {'articles ': []} for I in range (0, count ): article = {'Title': title, 'description': description, 'picurl': picUrl, 'URL': url} # insert article articles_msg ['article']. append (article) article = {}# return the article return articles_msg else: return

It can be seen that the app is not very difficult. it is still close to the sum in the last API use. you need to define several global variables, such as tokens, such as PIC_URL. The principle of the program is to parse the user request. if it starts with h, a help menu is provided. if it starts with a number, an article is provided. then, corresponding functions are provided for processing, the description here is complicated. let's get the classification article:

Analyze user request strings:

# Classification elif query_str [0] = "c": category = query_str [1:] response_msg = self. get_category_articles (category) if response_msg: return_data = self. pack_news_xml (msg, response_msg) else: response_msg = SORRY return_data = self. pack_text_xml (msg, response_msg) self. write (return_data)

Here we need to provide the get_category_articles (category) function, so we need to implement such a function in the weixin class:

# Search for def get_category_articles (self, category) by category: global MAX_ARTICLE global PIC_URL article_list = Article. inline (category) article_list_length = len (article_list) count = (article_list_length <MAX_ARTICLE) and article_list_length or MAX_ARTICLE if article_list: # construct a text message articles_msg = {'articles ': []} for I in range (0, count): article = {'Title': article_list [I]. slug, 'description': article_list [I]. description, 'picurl': PIC_URL, 'URL': article_list [I]. absolute_url} # insert article articles_msg ['articles']. append (article) article = {}# return the article return articles_msg

Obviously, we need to deal with the database model Article to see if Article has implemented this function. Unfortunately, we have to roll up our sleeves and expand the Article, so we have to switch to modle. in the py file, write the following code:

# Return an array limit 5 def get_articles_by_category (self, category) that contains several articles: sdb. _ ensure_connected () article_list = sdb. query ('select * FROM 'sp _ posts' WHERE 'Category '= % s LIMIT 5', str (category) for I in range (len (article_list )): article_list [I] = post_detail_formate (article_list [I]) return article_list

The database query is conducted here. the category parameter is passed in. five articles with the category parameter selected are packaged and returned. Post_detail_formate is already written by the blog system. we just need to use it. In python, be careful when writing SQL statements. if you want to input parameters, use commas instead of % to fill the parameters. Especially when using like, we often need to write such SQL statements:

SELECT * FROM 'sp _ posts' WHERE 'Category 'LIKE' % study %'

However, in python, % s is used as the parameter placeholder, which may cause many unnecessary errors, such as here. To ensure security, it is best to pass it as a parameter. python will separate them from the % in the original string.

The above is the details of the message connection method developed by the public. For more information, see other related articles on php Chinese network!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.