Exemple #1
0
def add_resource(request, resource_pid=None):
    if request.method == 'POST':
        ds = DataSerialize()
        form = AddResourceForm(model=Menu, data=request.POST)
        if form.is_valid():
            new_resource = form.save()
            r_parent = new_resource.parent
            if r_parent is not None:
                new_resource.level = new_resource.parent.level - 1
            elif r_parent is None:
                new_resource.level = 0
            new_resource.save()

            sort_subnodes(parent_ins=r_parent)
            rs_data = {'timestamp': ds.get_create_date(), 'result': 'success'}
            html = json.dumps(rs_data)
            return HttpResponse(html, content_type="application/json")
    else:
        if resource_pid is None or resource_pid == '' or int(
                resource_pid) == 0:
            form = AddResourceForm(model=Menu, )
        else:
            form = AddResourceForm(model=Menu,
                                   instance=Menu(parent_id=resource_pid))

    app = app_info()
    app['name'] = "permission"
    app['location'] = 'add'
    return render(request, 'add_data2_not_nav.html', {
        'form': form,
        'app': app
    })
Exemple #2
0
def add_user(request):
    if request.method == 'POST':
        ds = DataSerialize()
        form = ManageAddUserForm(model=User, data=request.POST)
        if form.is_valid():
            new_user = form.save()
            rs_data = {'timestamp': ds.get_create_date(), 'result': 'success'}
            html = json.dumps(rs_data)
            return HttpResponse(html, content_type="application/json")
    else:
        form = ManageAddUserForm(model=User)

    m2m_fs = User._meta.many_to_many
    m2m_list = []
    for m2m_f in m2m_fs:
        if m2m_f.name in form.fields.keys():
            m2m_list.append(m2m_f.name)
    app = app_info()
    app['name'] = "m_account"
    app['location'] = 'add'
    return render(request, 'add_data2_not_nav.html', {
        'form': form,
        'app': app,
        'm2m_list': m2m_list
    })
Exemple #3
0
def edit_user(request, user_id):
    user = get_object_or_404(User, pk=user_id)
    # print 'is_active=%s' % user.is_active
    if request.method == 'POST':
        ds = DataSerialize()
        form = ManageEditUserForm(model=User, instance=user, data=request.POST)
        if form.is_valid():
            new_user = form.save()
            rs_data = {'timestamp': ds.get_create_date(), 'result': 'success'}
            html = json.dumps(rs_data)
            return HttpResponse(html, content_type="application/json")
    else:
        form = ManageEditUserForm(
            model=User,
            instance=user,
        )

    m2m_fs = User._meta.many_to_many
    m2m_list = []
    for m2m_f in m2m_fs:
        if m2m_f.name in form.fields.keys():
            m2m_list.append(m2m_f.name)
    app = app_info()
    app['name'] = "m_account"
    app['location'] = 'edit'
    return render(request, 'edit_data2_not_nav.html', {
        'form': form,
        'app': app,
        'm2m_list': m2m_list
    })
Exemple #4
0
def update_resource_position(request):
    '''
    更新资源节点的位置、排序、层级信息
    :param request:
    :return:
    '''
    if request.method == "POST":
        ds = DataSerialize()
        node_data = request.POST.get('node_data')
        node_data = ds.deserialize(node_data)
        # co.DD(node_data)
        node = node_data['curr_node']
        pre_node = node_data['pre_node']
        next_node = node_data['next_node']
        n_ins = get_object_or_404(Menu, pk=node['id'])
        old_parent_ins = n_ins.parent
        init_max_order_num = 2.0
        init_min_order_num = 1.0

        is_update_pid = False
        if n_ins.parent is not None:  # 非根节点
            if node['pId'] is None:  # 非根节点 --> 根节点
                n_ins.parent = None
            elif n_ins.parent.id != node['pId']:  # 非根节点 --> 非根节点(父节点有变化)
                is_update_pid = True
        elif node['pId'] is not None and n_ins.parent is None:  # 根节点 --> 非根节点
            is_update_pid = True
        else:
            is_update_pid = False
        if is_update_pid:
            n_ins.parent = get_object_or_404(Menu, pk=node['pId'])
            # 更新节点的level
            if n_ins.parent is None:
                n_ins.level = 0
            else:
                n_ins.level = n_ins.parent.level + 1
        else:
            n_ins.level = node['level']
        if pre_node is not None and next_node is not None:  # 夹在中间位
            t_order = round((pre_node['order'] + next_node['order']) / 2, 5)
        elif pre_node is None and next_node is None:  # 第一位或最后一位(有且只有一个元素)
            t_order = init_min_order_num
        elif pre_node is None and next_node is not None:  # 第一位
            t_order = round(next_node['order'] / 2, 5)
        elif pre_node is not None and next_node is None:  # 最后一位
            t_order = round((pre_node['order'] + 1), 5)
        n_ins.order = t_order
        n_ins.save()

        # 重新整理同级所有节点排序,使得序号范围在init_min_order_num -- init_max_order_num之间,
        # 同级的序号间距也重新规整为:round(init_max_order_num-init_min_order_num/subnodes_count, 5)
        new_parent_ins = n_ins.parent
        if new_parent_ins != old_parent_ins:
            sort_subnodes(parent_ins=new_parent_ins)
        sort_subnodes(parent_ins=old_parent_ins)

        rs_data = {'timestamp': ds.get_create_date()}
        html = json.dumps(rs_data)
        return HttpResponse(html, content_type="application/json")
Exemple #5
0
def save_resource_tree(request):
    '''
    保存所有节点的位置、排序、层级信息
    :param request:
    :return:
    '''
    if request.method == "POST":
        ds = DataSerialize()
        tree_data = request.POST.get('tree_data')
        tree_data = ds.deserialize(tree_data)
        sort_nodes(nodes=tree_data)
        rs_data = {'timestamp': ds.get_create_date()}
        html = json.dumps(rs_data)
        return HttpResponse(html, content_type="application/json")
Exemple #6
0
class Ajax(Common):
    def __init__(self, *args, **kwargs):
        self.s_method = kwargs.get('s_method', ['GET', 'POST'])
        self.request = kwargs.get('request', None)
        self.original_data = kwargs.get('original_data', 'form')
        self.is_origin_serial = kwargs.get('is_origin_serial', False)
        ds = kwargs.get('ds', None)
        if isinstance(ds, DataSerialize):
            self.ds = ds
        else:
            self.ds = DataSerialize(format='json', ensure_ascii=False)

        self.error_m = {
            'error_code': -1,
            'error_msg': 'Only support %s method!' % (','.join(self.s_method)),
        }
        self.response = HttpResponse('')
        self.response['Content-Type'] = "application/json; charset=utf-8"
        self.response['Vary'] = "Accept-Language"
        self.response_content = None

        self.callback(self, *args, **kwargs)

    def callback(self, *args, **kwargs):
        pass

    def load_data(self, content=None):
        self.response_content = content

    def get_ds_input_data(self):
        if self.request.method == 'POST':
            if self.original_data == 'form':
                self.in_data = self.request.POST
            else:
                self.in_data = self.request.body
        elif self.request.method == 'GET':
            self.in_data = self.request.GET
        else:
            self.in_data = {}
        # if self.is_origin_serial: #这里会产生错误。
        #   self.in_data=self.ds.deserialize('{"cc":1}')
        return self.in_data

    def make_response(self, *args, **kwargs):
        if self.request.method in self.s_method:
            self.response.content = self.ds.serialize(self.response_content)
        else:
            self.response.content = self.ds.serialize(self.error_m)
        return self.response
Exemple #7
0
def del_resource(request, resource_id):
    ds = DataSerialize()
    if request.method == "POST":
        new_resource = get_object_or_404(Menu, pk=resource_id)
        r_parent = new_resource.parent

        sub_menus = Menu.objects.filter(parent=new_resource)
        for sm in sub_menus:
            sm.parent = r_parent
            sm.save()
        del_res = del_model_data(model=Menu, id=resource_id)
        sort_subnodes(parent_ins=r_parent)
        rs_data = {'timestamp': ds.get_create_date(), 'result': 'success'}
        html = json.dumps(rs_data)
        return HttpResponse(html, content_type="application/json")
Exemple #8
0
def load_whois_server_config(config_file=None):
    '''
    https://raw.githubusercontent.com/regru/php-whois/master/src/Phois/Whois/whois.servers.json
    :param config_file:
    :return:
    '''
    if config_file is None:
        config_file = os.path.join(CONF_DIRS, 'whois.servers.json')
    content = ''
    ds = DataSerialize()
    config_dict = {}
    if os.path.exists(config_file):
        fh = File()
        content = fh.read_file(rfile=config_file)
        config_dict = ds.deserialize(content)
    return config_dict
Exemple #9
0
def save_perm_tree(request, role_id):
    if request.method == "POST":
        ds = DataSerialize()
        tree_data = request.POST.get('tree_data')
        tree_data = ds.deserialize(tree_data)
        role_id = request.POST.get('role_id')
        rs_data = {'timestamp': ds.get_create_date()}
        role_ins = get_object_or_404(Role, pk=role_id)
        for td in tree_data:
            if td['checked'] is True and td['checkedOld'] is False:
                role_ins.permissions.add(Menu.objects.get(pk=td['id']))
            elif td['checked'] is False and td['checkedOld'] is True:
                role_ins.permissions.remove(Menu.objects.get(pk=td['id']))
        role_ins.save()
        html = json.dumps(rs_data)
        return HttpResponse(html, content_type="application/json")
Exemple #10
0
 def __init__(self, *args, **kwargs):
     self.is_debug = kwargs.get('is_debug', False)
     self.data_format = kwargs.get('data_format', 'json')
     self.ds = DataSerialize(format=self.data_format)
     error_info = {'error_reason': '', 'error_code': 0}
     self.error_info = kwargs.get('error_info', error_info)
     self.is_data_serialize = kwargs.get('is_data_serialize', 0)
     if 'is_data_serialize' in kwargs:
         self.is_data_serialize = kwargs.get('is_data_serialize', 0)
         self.is_send_data_serialize = self.is_data_serialize
         self.is_rec_data_deserialize = self.is_data_serialize
     else:
         self.is_send_data_serialize = kwargs.get('is_send_data_serialize',
                                                  0)
         self.is_rec_data_deserialize = kwargs.get(
             'is_rec_data_deserialize', 0)
     headers = {"Content-type": "application/json", "Accept": "text/plain"}
     self.headers = kwargs.get('headers', headers)
Exemple #11
0
def add_role(request):
    if request.method == 'POST':
        ds = DataSerialize()
        form = AddRoleForm(model=Role, data=request.POST)
        if form.is_valid():
            new_role = form.save()
            rs_data = {'timestamp': ds.get_create_date(), 'result': 'success'}
            html = json.dumps(rs_data)
            return HttpResponse(html, content_type="application/json")
    else:
        form = AddRoleForm(model=Role)

    app = app_info()
    app['name'] = "m_role"
    app['location'] = 'add'
    return render(request, 'add_data2_not_nav.html', {
        'form': form,
        'app': app
    })
Exemple #12
0
    def __init__(self, *args, **kwargs):
        self.s_method = kwargs.get('s_method', ['GET', 'POST'])
        self.request = kwargs.get('request', None)
        self.original_data = kwargs.get('original_data', 'form')
        self.is_origin_serial = kwargs.get('is_origin_serial', False)
        ds = kwargs.get('ds', None)
        if isinstance(ds, DataSerialize):
            self.ds = ds
        else:
            self.ds = DataSerialize(format='json', ensure_ascii=False)

        self.error_m = {
            'error_code': -1,
            'error_msg': 'Only support %s method!' % (','.join(self.s_method)),
        }
        self.response = HttpResponse('')
        self.response['Content-Type'] = "application/json; charset=utf-8"
        self.response['Vary'] = "Accept-Language"
        self.response_content = None

        self.callback(self, *args, **kwargs)
Exemple #13
0
def edit_role(request, role_id):
    role = get_object_or_404(Role, pk=role_id)
    # print 'is_active=%s' % role.is_active
    if request.method == 'POST':
        ds = DataSerialize()
        form = AddRoleForm(model=Role, instance=role, data=request.POST)
        if form.is_valid():
            new_role = form.save()
            rs_data = {'timestamp': ds.get_create_date(), 'result': 'success'}
            html = json.dumps(rs_data)
            return HttpResponse(html, content_type="application/json")
    else:
        form = AddRoleForm(model=Role, instance=role)

    app = app_info()
    app['name'] = "m_role"
    app['location'] = 'edit'
    return render(request, 'edit_data2_not_nav.html', {
        'form': form,
        'app': app
    })
Exemple #14
0
def convert_view_name_to_url(request):
    ajax_ins = Ajax(request=request, s_method=['GET', 'POST'])
    ds = DataSerialize()
    in_data = ajax_ins.get_ds_input_data()
    data = {
        k: in_data.getlist(k) if len(in_data.getlist(k)) > 1 else v
        for k, v in in_data.items()
    }
    data['view_param'] = ds.deserialize(data['view_param'])
    view_name = data['view_name']
    id = None
    if 'id' in data['view_param']:
        id = int(data['view_param']['id'])
    da = {}
    if view_name is None or view_name == '':
        da = {'url': ''}
    else:
        if id is None or id == '':
            da = {'url': reverse(view_name)}
        else:
            da = {'url': reverse(view_name, args=(id, ))}
    ajax_ins.DD(da)
    return ajax_ins.make_response()
Exemple #15
0
def edit_resource(request, resource_id):
    resource = get_object_or_404(Menu, pk=resource_id)
    ds = DataSerialize()
    if request.method == 'POST':
        form = AddResourceForm(model=Menu,
                               instance=resource,
                               data=request.POST)
        if form.is_valid():
            new_resource = form.save()
            r_parent = new_resource.parent
            sort_subnodes(parent_ins=r_parent)
            rs_data = {'timestamp': ds.get_create_date(), 'result': 'success'}
            html = json.dumps(rs_data)
            return HttpResponse(html, content_type="application/json")
    else:
        form = AddResourceForm(model=Menu, instance=resource)

    app = app_info()
    app['name'] = "m_account"
    app['location'] = 'edit'
    return render(request, 'edit_data2_not_nav.html', {
        'form': form,
        'app': app
    })
Exemple #16
0
 def __init__(self, *args, **kwargs):
     self.is_debug = kwargs.get('is_debug', False)
     self.data_format = kwargs.get('data_format', 'json')
     self.ds = DataSerialize(format=self.data_format)
     error_info = {'error_reason': '', 'error_code': 0}
     self.error_info = kwargs.get('error_info', error_info)
     self.is_data_serialize = kwargs.get('is_data_serialize', 0)
     if 'is_data_serialize' in kwargs:
         self.is_data_serialize = kwargs.get('is_data_serialize', 0)
         self.is_send_data_serialize = self.is_data_serialize
         self.is_rec_data_deserialize = self.is_data_serialize
     else:
         self.is_send_data_serialize = kwargs.get('is_send_data_serialize',
                                                  0)
         self.is_rec_data_deserialize = kwargs.get(
             'is_rec_data_deserialize', 0)
     headers = {"Content-type": "application/json", "Accept": "text/plain"}
     self.headers = kwargs.get('headers', headers)
     self.cj_ins = cookielib.CookieJar()
     self.opener = urllib.request.build_opener(
         urllib.request.HTTPCookieProcessor(self.cj_ins))
     urllib.request.install_opener(self.opener)
     self.cookies = {}
     self.disable_ssl_check = kwargs.get('disable_ssl_check', False)
Exemple #17
0
class Http2(Common):
    def __init__(self, *args, **kwargs):
        self.is_debug = kwargs.get('is_debug', False)
        self.data_format = kwargs.get('data_format', 'json')
        self.ds = DataSerialize(format=self.data_format)
        error_info = {'error_reason': '', 'error_code': 0}
        self.error_info = kwargs.get('error_info', error_info)
        self.is_data_serialize = kwargs.get('is_data_serialize', 0)
        if 'is_data_serialize' in kwargs:
            self.is_data_serialize = kwargs.get('is_data_serialize', 0)
            self.is_send_data_serialize = self.is_data_serialize
            self.is_rec_data_deserialize = self.is_data_serialize
        else:
            self.is_send_data_serialize = kwargs.get('is_send_data_serialize',
                                                     0)
            self.is_rec_data_deserialize = kwargs.get(
                'is_rec_data_deserialize', 0)
        headers = {"Content-type": "application/json", "Accept": "text/plain"}
        self.headers = kwargs.get('headers', headers)
        self.cj_ins = cookielib.CookieJar()
        self.opener = urllib.request.build_opener(
            urllib.request.HTTPCookieProcessor(self.cj_ins))
        urllib.request.install_opener(self.opener)
        self.cookies = {}
        self.disable_ssl_check = kwargs.get('disable_ssl_check', False)

    def set_cookie(self, request=None, domain=None, cookies={}):
        if domain is not None and domain != '':
            if len(cookies) > 0:
                set_cookie(self.cj_ins, domain=domain, cookies=cookies)
            elif len(self.cookies) > 0:
                set_cookie(self.cj_ins, domain=domain, cookies=self.cookies)
        if request is not None:
            self.cj_ins.add_cookie_header(request)

    def reset_error_info(self):
        self.error_info = {'error_reason': '', 'error_code': 0}

    def set_http_headers(self, headers={}):
        self.headers = headers

    def update_http_headers(self, headers={}):
        self.headers.update(headers)

    def connect(self,
                uri_h=None,
                content=None,
                api_url=None,
                http_method='GET',
                cookies={}):
        api_url_scheme = uri_h['scheme']
        api_url_hostname = uri_h['hostname']
        api_url_port = uri_h['port']
        api_url_path = uri_h['path']
        api_url_params = uri_h['params']
        api_url_query = uri_h['query'].lstrip(' ').rstrip(' ')
        url = join_uri(uri_h)
        # if self.cj_ins is None or isinstance(self.cj_ins, cookielib.CookieJar) is False:
        #     print('get new cookie ins...')
        #     self.cj_ins = cookielib.CookieJar()

        if http_method in ['GET']:
            # # 确保GET方法采用HTTP协议标准用法,当有query时,加入url中
            if api_url_query is not None and api_url_query != '':
                if api_url_path == '' or api_url_path is None:
                    api_url_path = '/?' + api_url_query
                else:
                    if self.is_debug:
                        print('api_url_query:"%s"' % api_url_query)
                    api_url_path = api_url_path + '?' + api_url_query
        uri_h2 = copy.copy(uri_h)
        uri_h2.update({'query': api_url_query})
        # url = join_uri()
        url = join_uri(uri_h2)
        if content is not None:
            if type(content) != bytes:
                request_data = content.encode('utf-8')
                # request_data = bytes(content, 'utf-8')
            else:
                request_data = content
        else:
            request_data = b''
        req = urllib.request.Request(url=url,
                                     headers=self.headers,
                                     data=request_data,
                                     method=http_method)

        self.set_cookie(request=req, domain=uri_h['hostname'], cookies=cookies)
        response_status = {}
        response_data = {}
        response = None
        if self.is_debug: self.DD(req.header_items())
        try:
            if self.disable_ssl_check == True:
                response = urllib.request.urlopen(
                    req, context=ssl._create_unverified_context())
            else:
                response = urllib.request.urlopen(req)
            # response = self.opener.open(req)
            response_status['code'] = response.code
            response_status['response_headers'] = dict_from_httpmessage(
                response.headers)
            response_status['requset_headers'] = req.header_items()
            response_status['msg'] = response.msg
            response_status['reason'] = response.msg
            response_data = response.read().decode("utf8")
        except urllib.error.HTTPError as err:
            response_status['code'] = err.code
            response_status['reason'] = err.reason
            response_status['response_headers'] = dict_from_httpmessage(
                err.headers)
            response_status['requset_headers'] = req.header_items()
            response_status['msg'] = 'ERROR'
            response_data = err.fp.read().decode("utf8")
        except urllib.error.URLError as err:
            response_status['reason'] = err.reason
            response_status['msg'] = 'ERROR'
        finally:
            if response and hasattr(response, 'close'):
                response.close()
        response_cookie = dict_from_cookiejar(self.cj_ins)
        return response_data, response_status, response_cookie

    def http_connect(self,
                     content=None,
                     api_url=None,
                     http_method='GET',
                     cookies={}):
        self.error_code = 0
        self.error_reason = ''
        self.reset_error_info()

        data = None
        error = None
        conn = None
        response = None
        uri_h = parse_uri(uri=api_url)
        if self.is_debug: print('api_url:%s, content:%s' % (api_url, content))
        response_data, response_status, response_cookie = self.connect(
            uri_h=uri_h,
            content=content,
            api_url=api_url,
            http_method=http_method,
            cookies=cookies)
        # self.DD(response_status)
        if response_status['code'] in (301, 302, 304, 307):
            new_url = response.getheader("Location")
            new_uri_h = parse_uri(uri=new_url)
            new_uri_h = dict(uri_h, **new_uri_h)
            new_uri_h['query'] = uri_h['query']
            response_data, response_status, response_cookie = self.connect(
                uri_h=new_uri_h,
                content=content,
                api_url=new_url,
                http_method=http_method,
                cookies=cookies)

        if self.is_debug:
            print('stats:%s, reason:%s' %
                  (response_status['code'], response_status['reason']))
        if self.is_debug: self.DD(response_status['response_headers'])
        if response_status['code'] in (
                200, 201, 202) and response_status['reason'] in ('OK',
                                                                 'Accepted'):
            return response_data, response_status, response_cookie
        else:
            if response_status['code'] == 401:
                self.error_info['error_code'] = 2
            else:
                self.error_info['error_code'] = 1
            self.error_info[
                'error_reason'] = 'connect %s error: status>%s  reason> %s' % (
                    api_url, response_status['code'],
                    response_status['reason'])
            return response_data, response_status, response_cookie

    def api_connect(self,
                    api_url=None,
                    params=None,
                    http_method='GET',
                    cookies={}):
        if self.is_debug: self.DD(params)
        if http_method.upper() in ['GET', 'HEAD']:
            # 确保GET 请求使用HTTP协议标准用法,参数放入url中,而不是放入body中。
            params = urlencode(params)
            params = params.lstrip(' ').rstrip(' ')
            if params is not None and params != '':
                api_url = api_url + '?' + params
            content = None
        elif http_method.upper() == 'POST':
            if params is not None:
                if self.is_send_data_serialize == 1 and isinstance(
                        params, dict):
                    params = self.ds.serialize(params)
                else:
                    if 'Content-Type' in self.headers and \
                            self.headers['Content-Type'] == 'application/x-www-form-urlencoded':
                        # 只有在请求头中Content-Type明确使用urlencode,才对参数进行urlencode
                        params = urlencode(params)
            content = params
        else:
            content = params
        # if self.is_debug: print('api_url = %s' % api_url)
        data, response_status, response_cookie = self.http_connect(
            content=content,
            api_url=api_url,
            http_method=http_method,
            cookies=cookies)
        if self.is_debug: self.DD(data)
        if self.is_debug: self.DD(self.error_info)
        if self.error_info[
                'error_code'] == 0 and self.is_rec_data_deserialize == 1:
            if self.is_debug: self.DD(response_status)
            if data is not None and data != '' and response_status[
                    'response_headers']['Content-Type'].lower().find(
                        'application/json') >= 0:
                data = self.ds.deserialize(data)
        return data, response_status, response_cookie
Exemple #18
0
class Http(Common):
    def __init__(self, *args, **kwargs):
        self.is_debug = kwargs.get('is_debug', False)
        self.data_format = kwargs.get('data_format', 'json')
        self.ds = DataSerialize(format=self.data_format)
        error_info = {'error_reason': '', 'error_code': 0}
        self.error_info = kwargs.get('error_info', error_info)
        self.is_data_serialize = kwargs.get('is_data_serialize', 0)
        if 'is_data_serialize' in kwargs:
            self.is_data_serialize = kwargs.get('is_data_serialize', 0)
            self.is_send_data_serialize = self.is_data_serialize
            self.is_rec_data_deserialize = self.is_data_serialize
        else:
            self.is_send_data_serialize = kwargs.get('is_send_data_serialize',
                                                     0)
            self.is_rec_data_deserialize = kwargs.get(
                'is_rec_data_deserialize', 0)
        headers = {"Content-type": "application/json", "Accept": "text/plain"}
        self.headers = kwargs.get('headers', headers)

    def reset_error_info(self):
        self.error_info = {'error_reason': '', 'error_code': 0}

    def set_http_headers(self, headers={}):
        self.headers = headers

    def update_http_headers(self, headers={}):
        self.headers.update(headers)

    def connect(self,
                uri_h=None,
                content=None,
                api_url=None,
                http_method=None,
                conn=None,
                response=None):
        api_url_scheme = uri_h['scheme']
        api_url_hostname = uri_h['hostname']
        api_url_port = uri_h['port']
        api_url_path = uri_h['path']
        api_url_params = uri_h['params']
        api_url_query = uri_h['query'].lstrip(' ').rstrip(' ')
        if api_url_scheme == 'https':
            conn = httplib.HTTPSConnection(api_url_hostname, api_url_port)
        elif api_url_scheme == 'http':
            conn = httplib.HTTPConnection(api_url_hostname, api_url_port)
        else:
            self.error_code = 1
            self.error_reason = 'invalid url !'
        # print 'method: %s,   url:%s' % (http_method,  api_url_path)

        if http_method == 'GET':
            # # 确保GET方法采用HTTP协议标准用法,当有query时,加入url中
            if api_url_query is not None and api_url_query != '':
                if api_url_path == '' or api_url_path is None:
                    api_url_path = '/?' + api_url_query
                else:
                    if self.is_debug:
                        print('api_url_query:"%s"' % api_url_query)
                    api_url_path = api_url_path + '?' + api_url_query
        try:
            if self.is_debug: print('api_url_path: %s' % api_url_path)
            if 'Authorization' in self.headers:
                if self.is_debug:
                    print('auth headers: %s' % self.headers['Authorization'])

            if hasattr(conn, 'request'):
                conn.request(
                    http_method,
                    api_url_path,
                    content,
                    self.headers,
                )
                response = conn.getresponse()
                response_data = response.read()

            else:
                response_data = None
        finally:
            if hasattr(conn, 'close'):
                conn.close()
        return response, response_data

    def http_connect(self, content=None, api_url=None, http_method='POST'):
        self.error_code = 0
        self.error_reason = ''
        self.reset_error_info()

        data = None
        error = None
        conn = None
        response = None
        uri_h = parse_uri(uri=api_url)
        if self.is_debug: print('api_url:%s, content:%s' % (api_url, content))
        (response, response_data) = self.connect(uri_h=uri_h,
                                                 content=content,
                                                 api_url=api_url,
                                                 http_method=http_method)
        if response.status in (301, 302, 304, 307):
            new_url = response.getheader("Location")
            new_uri_h = parse_uri(uri=new_url)
            new_uri_h = dict(uri_h, **new_uri_h)
            new_uri_h['query'] = uri_h['query']
            (response, response_data) = self.connect(uri_h=new_uri_h,
                                                     content=content,
                                                     api_url=new_url,
                                                     http_method=http_method)

        if self.is_debug:
            print('stats:%s, reason:%s' % (response.status, response.reason))
        if self.is_debug: self.DD(response.getheaders())
        if response.status in (200, 202) and response.reason in ('OK',
                                                                 'Accepted'):
            return response_data
        else:
            if response.status == 401:
                self.error_info['error_code'] = 2
            else:
                self.error_info['error_code'] = 1
            self.error_info[
                'error_reason'] = 'connect %s error: status>%s  reason> %s' % (
                    api_url, response.status, response.reason)

    def api_connect(self, params=None, api_url=None, http_method='POST'):
        self.error_code = 0
        self.error_reason = ''
        self.reset_error_info()
        data = None
        error = None

        if http_method.upper() == 'GET':
            # 确保GET 请求使用HTTP协议标准用法,参数放入url中,而不是放入body中。
            params = urlencode(params)
            params = params.lstrip(' ').rstrip(' ')
            if params is not None and params != '':
                api_url = api_url + '?' + params
            content = None
        elif http_method.upper() == 'POST':
            if params is not None:
                if self.is_send_data_serialize == 1 and isinstance(
                        params, dict):
                    params = self.ds.serialize(params)
                else:
                    if 'Content-Type' in self.headers and \
                            self.headers['Content-Type'] == 'application/x-www-form-urlencoded':
                        # 只有在请求头中Content-Type明确使用urlencode,才对参数进行urlencode
                        params = urlencode(params)
            content = params
        else:
            pass
        if self.is_debug: print('api_url = %s' % api_url)
        data = self.http_connect(content=content,
                                 api_url=api_url,
                                 http_method=http_method)
        if self.is_debug: self.DD(data)
        if self.is_debug: self.DD(self.error_info)
        if self.error_info[
                'error_code'] == 0 and self.is_rec_data_deserialize == 1:
            data = self.ds.deserialize(data)
        return data