我構建了一個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]>
在這一點上,我完全失去了。我試圖設置一個代理來嘗試逐字節比較請求,但沒有太多運氣。任何幫助或見解都非常感謝。
問題可能在你的self.endpoint你確定兩者都是相同的 – DreadfulWeather
直接從我的代碼複製粘貼:'self.endpoint ='https://api.intercom。 io/users'' –