2016-08-12 23 views
2

ZenDeskで私の個人的なマクロの署名を一括編集しようとしていましたが、それを行う唯一の方法はAPI経由です。予想通り、私のZenDeskマクロはなぜ更新されますが、実際には変更はありませんか?

import sys 
import time 
import logging 
import requests 
import re 

start_time = time.time() 

# Set up logging 
logger = logging.getLogger() 
log_handler = logging.StreamHandler(sys.stdout) 
log_handler.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s - %(funcName)s - line %(lineno)d")) 
log_handler.setLevel(logging.DEBUG) 
logger.addHandler(log_handler) 
logger.setLevel(logging.DEBUG) 

def doTheGet(url, user, pwd): 
     response = requests.get(url, auth=(user + "/token", pwd)) 

     if response.status_code != 200: 
       logger.error("Status: %s (%s) Problem with the request. Exiting. %f seconds elapsed" % (response.status_code, response.reason, time.time() - start_time)) 
       exit() 

     data = response.json() 
     return data 

def doThePut(url, updated_data, user, pwd): 
     response = requests.put(url, json="{'macro': {'actions': %r}}" % updated_data, headers={"Content-Type": "application/json"}, auth=(user + "/token", pwd)) 

     if response.status_code != 200: 
       logger.error("Status: %s (%s) Problem with the request. Exiting. %f seconds elapsed" % (response.status_code, response.reason, time.time() - start_time)) 
       exit() 

     data = response.json() 
     return data 

def getMacros(): 
     macros = {} 

     data = doTheGet("https://mydomain.zendesk.com/api/v2/macros.json", "[email protected]", "111tokenZZZ") 

     def getMacros(macro_list, page, page_count): 
       if not page: 
         for macro in macro_list: 
           if macro["restriction"] and macro["active"]: 
             if macro["restriction"]["type"] == "User": 
               macros[macro["id"]] = macro["actions"] 
       else: 
         for macro in macro_list: 
           if macro["restriction"] and macro["active"]: 
             if macro["restriction"]["type"] == "User": 
               macros[macro["id"]] = macro["actions"] 

         page_count += 1 
         new_data = doTheGet(page, "[email protected]", "111tokenZZZ") 
         new_macs = new_data["macros"] 
         new_next_page = new_data["next_page"] 
         getMacros(new_macs, new_next_page, page_count) 


     macs = data["macros"] 
     current_page = 1 
     next_page = data["next_page"] 
     getMacros(macs, next_page, current_page) 
     return macros 

def updateMacros(): 
     macros = getMacros() 

     regular = "RegEx to match signature to be replaced$" #since some macros already have the updated signature 

     for macro in macros: 
       for action in macros[macro]: 
         if action["field"] == "comment_value": 
           if re.search(regular, action["value"][1]): 
             ind = action["value"][1].rfind("\n") 
             action["value"][1] = action["value"][1][:ind] + "\nNew signature" 

     return macros 

macs = updateMacros() 

for mac in macs: 
     doThePut("https://mydomain.zendesk.com/api/v2/macros/%d.json" % (mac), macs[mac], "[email protected]", "111tokenZZZ") 

すべてのランニングをし、私はエラーを取得していない:だから私はそれを実行しようとするために、この迅速なPythonスクリプトを書きました。私がZenDeskのマクロに行き、最後に更新して並べ替えると、今日最後に更新されたので、スクリプトが何かをしたことがわかります。しかし、何も変わりません。 を送信しているデータがupdateMacrosの仕事をしています)であることを確認しました。私は、要求がOK応答を送り返すことを確認しました。更新されたデータを送信して、200応答を返すが、the response sent backは以前と同じようにマクロをゼロ変化で表示する。

何らかの形で間違っている可能性があることは、私が送信しているデータの形式や種類のものだけです。しかしそれでも、私はその応答が200ではないと期待しています。

私はここで何が欠けていますか?あなたはPUTリクエストでJSONデータをダブルエンコードしているよう

答えて

4

はルックス:JSONパラメータは、それがその後、律儀にJSONとしてエンコードし、要求の本文として送信したオブジェクトを、期待し

response = requests.put(url, json="{'macro': {'actions': %r}}" % updated_data, headers={"Content-Type": "application/json"}, auth=(user + "/token", pwd)) 

。これは単なる利便性です。実装は単純で、

if not data and json is not None: 
     # urllib3 requires a bytes-like body. Python 2's json.dumps 
     # provides this natively, but Python 3 gives a Unicode string. 
     content_type = 'application/json' 
     body = complexjson.dumps(json) 
     if not isinstance(body, bytes): 
      body = body.encode('utf-8') 

(ソース:https://github.com/kennethreitz/requests/blob/master/requests/models.py#L424):

値は、あなたが既にエンコードされたJSONを表す文字列を渡した場合、それ自体がエンコードされます、常にjson.dumps()を通過あるので、

ZenDeskは、期待していないJSONが与えられると、updated_atフィールドを更新します。他には何もしません。これは、空の文字列(同じ結果)を渡すことで確認できます。

また、JSONを記入するためにPythonのrepr書式設定にも依存していることに注意してください。それはおそらく悪い考えです。

response = requests.put(url, json={'macro': {'actions': updated_data}}, headers={"Content-Type": "application/json"}, auth=(user + "/token", pwd)) 

これは、あなたが期待する何をすべき:代わりに、ちょうど私達のマクロオブジェクトを再構築し、要求がそれをコード化させてみましょう。

関連する問題