transfer_knowledgebase.py 文件源码

python
阅读 45 收藏 0 点赞 0 评论 0

项目:zendesk-utils 作者: trailbehind 项目源码 文件源码
def update_zendesk_article_html(self):
    '''
    rewrite the html of zendesk articles 
    to point anchor tags at new zendesk articles, instead of old uservoice articles
    '''
    print "**UPDATING HTML to switch anchor hrefs to zendesk"
    url = '{}/api/v2/help_center/categories/{}/articles.json'.format(self.zendesk_url, self.zendesk_destination_category_id)

    articles = []
    while url:
      response = requests.get(url, headers=self.headers, auth=self.credentials)
      if response.status_code != 200:
        print('FAILED to get get article list with error {}'.format(response.status_code))
        exit()
      data = response.json()
      for article in data['articles']:
        articles.append(article)
      url = data['next_page']

    print "UPDATING HTML for {} articles".format(len(articles))
    for article in articles:
      url = "{}/api/v2/help_center/articles/{}.json".format(self.zendesk_url, article['id'])
      response = requests.get(url, headers=self.headers, auth=self.credentials)
      if response.status_code != 200:
        print('FAILED to update HTML for article {} with error {}'.format(article['id'], response.status_code))
        exit()
      html_doc = fromstring(article['body'])
      for anchor_tag in html_doc.cssselect('a'):
        if not anchor_tag.get('href'):
          continue
        number_from_string_regex = re.search('(\d+)', anchor_tag.get('href'))
        if not number_from_string_regex:
          continue
        uv_id = int(number_from_string_regex.group(0))
        if uv_id in self.uvid_to_zdid:
          url = "{}/api/v2/help_center/articles/{}.json".format(self.zendesk_url, self.uvid_to_zdid[uv_id])
          response = requests.get(url, headers=self.headers, auth=self.credentials)
          if response.status_code != 200:
            print('FAILED to get article {} with error {}'.format(self.uvid_to_zdid[uv_id], response.status_code))
            exit()
          new_url = response.json()['article']['html_url']
          try:
            print('CHANGING {} to {}'.format(anchor_tag.get('href'), new_url))
          except:
            e = sys.exc_info()[0]
            print "lxml parsing error {}".format(e)
          anchor_tag.set('href', new_url)
          info = {
            'body': tostring(html_doc)
          }
          payload = json.dumps({'article': info})
          url = "{}/api/v2/help_center/articles/{}.json".format(self.zendesk_url, article['id'])
          response = requests.put(url, data=payload, headers=self.headers, auth=self.credentials)
          if response.status_code != 200:
            print('FAILED to update HTML for article {} with error {}'.format(article['id'], response.status_code))
            exit()
        else:
          print "SKIPPING this href {}".format(anchor_tag.get('href'))
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号