2015-09-14 17 views
1

我構建了一個Python腳本,用於使用python請求庫將數據上載到名爲Intercom的應用程序。我們的想法是在自定義屬性中插入一個全新的字段,並使用我們需要的數據來鎖定我們的自動消息。Python請求可在控制檯中使用,但不能在應用程序中使用

劇本是很長,但畢竟是破方法如下:

def post_user(self, input_user, session=None): 
    """ 
    :param user: a JSON object with all the user pieces needed to be posted to the endpoint 
    :param session: a Requests session to be used. If None we'll create one 
    """ 
    if not session: 
     session = self.create_requests_session() 
    else: 
     session = session 

    # JSON encode the user 
    payload = json.dumps(input_user, sort_keys=True, indent=2, separators=(',', ': ')) 

    print(payload) # DEBUG CODE 

    # Post the data to endpoint 
    response = session.post(self.endpoint, data=payload) 

    # This will raise a status code on a bad status code 
    response.raise_for_status() 

下面也是create_requests_session()方法:

def create_requests_session(self): 
    """ 
    Start a requests session. Set Auth & Headers so we don't have to send it with each request 
    :return: A new requests.Session object with auth & header values prepopulated. 
    """ 

    session = requests.Session() 
    session.auth = (self.app_id, self.api_key) 
    session.headers = {'Content-Type': 'application/json', 'accept': 'application/json'} 

    return session 

當我運行整個腳本和步第一個input_user它是一個字典,看起來像。 (注:數據是匿名的,但結構仍然是完全一樣的):

{'user_id': '123456', 
    'email': '[email protected]', 
    'custom_attributes': { 
     'test_cell' : 'Variation'} 
} 

但是,用戶交付給json.dumps(user),然後通過POST請求發送之後,我回到了404錯誤。

這是奇怪的部分。我給這完全一樣的用戶提供完全相同的JSON,除了我創建的所有使用Python控制檯部分(注意,有些行被隱藏,以保持用戶數據匿名):

In[82]: sesh = requests.session() 
In[86]: header 
Out[86]: {'Content-Type': 'application/json', 'accept': 'application/json'} 
In[87]: sesh.headers = header 
In[89]: payload = json.dumps(update_user) 
In[91]: response = sesh.post(endpoint, data=payload) 
In[92]: response 
Out[92]: <Response [200]> 

在這一點上,我完全失去了。我試圖設置一個代理來嘗試逐字節比較請求,但沒有太多運氣。任何幫助或見解都非常感謝。

+0

問題可能在你的self.endpoint你確定兩者都是相同的 – DreadfulWeather

+0

直接從我的代碼複製粘貼:'self.endpoint ='https://api.intercom。 io/users'' –

回答

0

你確定你的驗證是有效的嗎?

session.auth = (self.app_id, self.api_key)

尤其是APP_ID應設置相應的API密鑰(因此,如果您使用的是測試應用程序測試應用程序的APP_ID)之一。

如果內部通信收到一個應用程序ID它不能識別它(當前)返回一個404,這是你所看到的。這應該現在修復返回401.

+0

不幸的是,事實並非如此。我將這些值存儲在環境中,它們是正確的。加認證失敗會導致401狀態碼。 –

+0

@JamieOsler。我剛剛在調試中驗證了這一點,會話正在通過正確的'app_id'和'api_key'來驗證,並且標頭是正確的。爲什麼這很奇怪,它們是我在命令行中傳遞的基本身份驗證密鑰;但是,它在我的腳本中不起作用,但它在Python控制檯中非常實用。 –

+0

我確保爲同一個應用程序創建一個全新的'api_key',並且確保會話auth頭文件在運行時是正確的。任何想法,爲什麼我仍然未經授權?我得到error_code''token_not_found「'完整的響應內容如下:'b'{」type「:」error.list「,」request_id「:」f6ff25d1-771e-49d1-8c8b-77c360bf53ed「,」錯誤「:[{」code「:」token_not_found「,」message「:」未經授權「}]}'' –

相關問題