class AccountSync(object):
def __init__(self):
# 环信
self.app_key = 'XXXXX' # 环信后台获取
self.client_id = 'XXXXX'
self.client_secret = 'XXXXX'
self.url = "https://a1.easemob.com/" + self.app_key.replace('#', '/', 1)
self.headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
# 环信token
def get_admin_token(self, client_id, client_secret):
body = {'grant_type': 'client_credentials',
'client_id': client_id,
'client_secret': client_secret}
response = hx_request.post(self.url + '/token', self.headers, body)
if response.code == 0:
self.admin_token = response.data['access_token']
self.admin_rest_token = 'Bearer ' + self.admin_token
return self.admin_rest_token
else:
logger.error('获取环信token失败') # 获取环信token失败
return ''
# 添加环信用户
def set_hx_user(self, user_list):
if user_list:
for user in user_list:
username = user['name_']
password = user['password_']
body = {'username': username, 'password': password}
auth_headers = {'Authorization': self.get_admin_token(self.client_id, self.client_secret)}
auth_headers.update(self.headers)
url = self.url + '/users'
find_res = hx_request.get(url=url + '/' + username, headers=auth_headers, parameters=None)
if find_res.code != 0: # 环信没有该用户
logger.error('环信没有用户: %s' % user)
response = hx_request.post(url, auth_headers, body)
if response.code != 0: # 增加环信用户失败
logger.error('增加环信用户失败: %s' % user)
else:
logger.info('增加环信用户成功: %s' % user)
import json
import urllib
import urllib2
from sync.hx_response import DXResponse
def http_request(url, headers, parameters, method):
body_data = None
if parameters is not None and len(parameters) > 0:
if 'Content-Type' in headers:
content_type = headers['Content-Type']
if content_type == 'application/json':
body_data = json.dumps(parameters).encode('utf-8')
else:
body_data = urllib.urlencode(parameters).encode('utf-8')
req = urllib2.Request(url, body_data, headers, method)
if method == 'PUT' or method == 'DELETE':
req.get_method = lambda: method
code = 0
des = ''
respdata = None
try:
response = urllib2.urlopen(req)
respdata = response.read().decode('utf-8')
print(respdata)
if 'Accept' in headers:
accept = headers['Accept']
if accept == 'application/json':
respdata = json.loads(respdata)
except urllib2.HTTPError as err:
code = err.code
des = err.reason
except urllib2.URLError as err:
code = -1
des = err.reason
tmp = DXResponse(code, des, respdata)
return tmp
def get(url, headers, parameters=None):
return http_request(url, headers, parameters, 'GET')
def post(url, headers, parameters=None):
return http_request(url, headers, parameters, 'POST')
该项目适用python2,python3的urllib2集合了python2的urllib和urllib2的功能
其他服务端对接环信api文档
http://docs-im.easemob.com/im/server/ready/user#%E7%94%A8%E6%88%B7%E7%AE%A1%E7%90%86