# ----------------------------------------------------------------------------------------------------------------------
#                                                     Imports
# ----------------------------------------------------------------------------------------------------------------------
import torch
import torch.nn as nn
import torch.nn.functional as tf
from .PytorchNet import PytorchNet
from util.gen import banner
from math import log10,floor,ceil

# ----------------------------------------------------------------------------------------------------------------------
#                                              Spatial Layer Implementation
# ----------------------------------------------------------------------------------------------------------------------
class Spatial(nn.Module):
    def __init__(self, channels,conv_to_MAC):
        super().__init__()

        self.channels = channels
        self.conv_to_MAC = conv_to_MAC
        self.ops_saved = 0
        self.total_ops = 0
        self.total_conv = 0
        self.conv_saved = 0
        self.is_init = False
        self.enable = False
        self.mask = None

        self.p_size, self.batch_size, self.in_shape, = (None, None, None)
        self.padded_in_shape, self.use_cuda, self.pad_s = (None, None, None)
        self.conv_filt, self.batch_mask = (None, None)

    def init_to_input(self, p_size, batch_size, in_shape, padded_in_shape, use_cuda):

        self.p_size, self.batch_size, self.in_shape, self.padded_in_shape, self.use_cuda = \
            p_size, batch_size, in_shape, padded_in_shape, use_cuda

        self.pad_s = self.padded_in_shape[1] - self.in_shape[1]
        self.conv_filt = nn.Conv2d(self.channels, self.channels, kernel_size=self.p_size, stride=self.p_size,
                                   bias=False, groups=self.channels)
        self.conv_filt.weight.data.fill_(1)
        # Make convolution later constant on backward passes
        for p in self.conv_filt.parameters():
            p.requires_grad = False

        if use_cuda:
            self.conv_filt = self.conv_filt.cuda()

        self.is_init = True

    def set_constant_mask(self, val):
        # To be used only after layer is initialized to input size
        assert self.is_init  # Did not include this in set_mask to savee complexity
        self.set_mask(val * torch.ones(self.padded_in_shape))

    def set_mask(self, mask):
        # To be used only after layer is initialized to input size
        self.mask = mask
        self.batch_mask = self.mask.unsqueeze(0).repeat(self.batch_size, 1, 1, 1)
        if self.use_cuda:
            self.mask = self.mask.cuda()  # TODO - Check if we can already allocate on GPU, maybe with set_
            self.batch_mask = self.batch_mask.cuda()

    def set_enable(self, enable):
        # To be used only after layer is initialized to input size
        self.enable = enable

    def num_ops_saved(self,use_conv=False):
        if use_conv:
            return self.conv_saved
        else:
            return self.ops_saved

    def num_ops_total(self,use_conv=False):
        if use_conv:
            return self.total_conv
        else:
            return self.total_ops

    def reset_ops(self):
        self.total_ops = 0
        self.ops_saved = 0
        self.conv_saved =0
        self.total_conv = 0

    def forward(self, x):
        if not self.enable:
            # print('Layer')
            return x

        if self.pad_s != 0:
            x = torch.nn.functional.pad(x, (0, self.pad_s, 0, self.pad_s), value=0)  # Pad with ZEROS

        if x.size(0) != self.batch_size:
            #print('Batch size event')  # - Will happen once every test forward
            batch_mask = self.batch_mask[:x.size(0), :, :, :]
        else:
            batch_mask = self.batch_mask

        # The convolution basically sums over all non-zero cells. We get a block predicator for each patch
        # Anywhere that is zero - That's where we are saving operations
        b = (self.conv_filt(torch.mul(x, batch_mask)) > 0).float()
        # TODO - Check if this could be shortened (Maybe via the Pytorch Upsample module?)
        b_expanded = b.repeat(1, 1, self.p_size, self.p_size). \
            reshape(b.size(0), b.size(1), self.p_size, -1).permute(0, 1, 3, 2). \
            reshape(b.size(0), b.size(1), b.size(2) * self.p_size, -1)

        self.conv_saved += torch.sum(torch.mul(1 - b_expanded, 1 - batch_mask))
        self.total_conv += x.shape[0] * x.shape[1] * x.shape[2] * x.shape[3]
        self.ops_saved += self.conv_to_MAC*self.conv_saved
        self.total_ops += self.conv_to_MAC*self.total_conv
        # Out predicator (after padding removal)
        if self.pad_s == 0:
            return torch.mul(x, b_expanded)
        else:
            return torch.mul(x, b_expanded)[:, :, :self.in_shape[1], :self.in_shape[1]]

# ----------------------------------------------------------------------------------------------------------------------
#                                        Spatial Net Abstract Class
# ----------------------------------------------------------------------------------------------------------------------
class SpatialNet(PytorchNet):
    def __init__(self, device):
        super().__init__(device)

        self.spatial_layers = []
        self.sp = None  # Will be set on first init of spatial layers - is a tuple
        self.sp_padded = None  # Will be set on first init of spatial layers - is a tuple
        self.x_shape = None
        self.p_size = None
        self.fam_name = None
        self.clustering_indices = None # Used for clustering layers together

    def forward(self, x):
        # Make it abstract
        raise NotImplementedError

    def family_name(self):
        # Abstract
        assert self.fam_name is not None # Needs to be calculated
        return self.fam_name

    def reset_spatial(self):
        for sp in self.spatial_layers:
            sp.reset_ops()
            sp.set_enable(False)

    def reset_ops(self):
        for sp in self.spatial_layers:
            sp.reset_ops()

    def name(self):
        return self.__class__.__name__

    def num_ops(self):
        ops_saved = 0
        total_ops = 0
        for sp in self.spatial_layers:
            ops_saved += int(sp.ops_saved)
            total_ops += sp.total_ops
        return ops_saved, total_ops

    def num_conv(self):
        conv_saved = 0
        total_conv = 0
        for sp in self.spatial_layers:
            conv_saved += int(sp.conv_saved)
            total_conv += sp.total_conv
        return conv_saved, total_conv

    def print_ops_summary(self,use_conv=False):

        if use_conv:
            name = 'Conv'
            all_ops_saved, all_total_ops = self.num_conv()
        else:
            name = 'MAC'
            all_ops_saved, all_total_ops = self.num_ops()

        for i, l in enumerate(self.spatial_layers):

            total_ops = l.num_ops_total(use_conv)
            saved_ops = l.num_ops_saved(use_conv)

            if total_ops == 0:
                print(f'Spatial Layer {i}: {name} Ops saved: {saved_ops}/{total_ops}')
            else:
                spacer = ' ' * (len(str(len(self.spatial_layers))) - len(str(i)))
                assert(saved_ops <= all_ops_saved)
                if all_ops_saved ==0: # Handle div by 0 case
                    midstr = '0'
                else:
                    midstr = f'{l.ops_saved*100/all_ops_saved:.3f}'
                print(
                    f'Spatial Layer {i}:{spacer} {name} Ops saved: {saved_ops*100 /total_ops:.3f} % [{int(saved_ops)} / {total_ops}]',
                    f'of [{midstr} % / {total_ops*100/all_total_ops:.3f} %]')

        if all_total_ops > 0:
            print(f'Grand total [{name}]: {all_ops_saved}/{all_total_ops} {all_ops_saved*100/all_total_ops:.3f} %')
        else:
            print(f'Grand total [{name}]: {all_ops_saved}/{all_total_ops}')

    def initialize_spatial_layers(self, x_shape, batch_size, p_size,freeze=True):

        if freeze:
            self.eval() #LOCK Network for testing only
        # From init phase and on, set the spatial sizes
        self.x_shape = x_shape
        self.p_size = p_size
        self.sp = self.generate_spatial_sizes(x_shape)
        self.sp_padded = self.generate_padded_spatial_sizes(x_shape, p_size)

        for i, layer in enumerate(self.spatial_layers):
            layer.init_to_input(p_size=p_size, batch_size=batch_size, in_shape=self.sp[i],
                                padded_in_shape=self.sp_padded[i],
                                use_cuda=self.use_cuda)

    def num_spatial_layers(self):
        return len(self.spatial_layers)

    def enabled_layers(self):
        return [i for i in range(self.num_spatial_layers()) if self.spatial_layers[i].enable]

    def disabled_layers(self):
        return [i for i in range(self.num_spatial_layers()) if not self.spatial_layers[i].enable]

    def enable_spatial_layers(self, idx_list):
        for resurrected in idx_list:
            self.spatial_layers[resurrected].set_enable(True)

    def disable_spatial_layers(self, idx_list):
        for goner_id in idx_list:
            self.spatial_layers[goner_id].set_enable(False)

    def print_spatial_status(self):
        init_status = ['-Initialized-' if sp.is_init else '-Uninitialized-' for sp in self.spatial_layers]
        enable_status = ['-Enabled-' if sp.enable else '-Disabled-' for sp in self.spatial_layers]
        mask_status = ['-Mask Not Set-' if sp.mask is None else '-Mask Set-' for sp in self.spatial_layers]
        banner('Spatial Status')
        for i, (iS, eS, mS) in enumerate(zip(init_status, enable_status, mask_status)):
            print(f'Spatial Layer {i}: {iS} {eS} {mS}')

    def strict_mask_update(self, update_ids, masks):
        # Turn on all the update ids
        self.lazy_mask_update(update_ids, masks)

        # Turn off all others
        disabled = [i for i in range(len(self.spatial_layers)) if i not in update_ids]
        self.disable_spatial_layers(disabled)

    def lazy_mask_update(self, update_ids, masks):
        for (i, mask) in zip(update_ids, masks):
            self.spatial_layers[i].set_mask(mask)
            self.spatial_layers[i].set_enable(True)

    def fill_masks_to_val(self, val):
        for layer in self.spatial_layers:
            layer.set_constant_mask(val)
            layer.set_enable(True)

    def generate_spatial_sizes(self, x_shape):
        # NOTE - This returns the sizes *WITHOUT* the padding and wit
        if self.sp is None or self.x_shape != tuple(x_shape):  # Spatial layers were not init or new dataset
            summary = self.summary(x_shape, print_it=False)
            sp = tuple(tuple(value['input_shape'][1:]) for key, value in summary.items() if key.startswith('Spatial'))

            if self.clustering_indices is not None:
                sp = tuple([sp[i] for i in self.clustering_indices])
            return sp
        else:
            return self.sp

    def generate_padded_spatial_sizes(self, x_shape, p_size):

        if self.sp_padded is None or self.p_size != p_size or self.x_shape != x_shape:
            sp_padded = []
            sps = self.generate_spatial_sizes(x_shape)
            for param in sps:
                pad_s = param[1] % p_size
                if pad_s != 0:
                    pad_s = p_size - pad_s
                    sp_padded.append((param[0], param[1] + pad_s, param[2] + pad_s))
                else:
                    sp_padded.append(param)
            return tuple(sp_padded)
        else:
            return self.sp_padded

    # Override
    def summary(self, x_shape, batch_size=-1, print_it=True):
        # TODO - Make this "careful" activation wrapper a built in private function
        if self.sp is None:
            return super().summary(x_shape, print_it=print_it)
        else:
            enabled = self.enabled_layers()
            if not enabled:
                return super().summary(x_shape, print_it=print_it)
            else:
                self.disable_spatial_layers(enabled)
                summary = super().summary(x_shape, print_it=print_it)
                self.enable_spatial_layers(enabled)
                return summary

    def output_size(self, x_shape,cuda_allowed=False):

        if self.sp is None:
            return super().output_size(x_shape,cuda_allowed)
        else:
            enabled = self.enabled_layers()
            if not enabled:
                return super().output_size(x_shape,cuda_allowed)
            else:
                self.disable_spatial_layers(enabled)
                siz = super().output_size(x_shape,cuda_allowed)
                self.enable_spatial_layers(enabled)
                return siz

def sequential_spatial_layer_extract(seq_model):
    spatial_layers = []
    for idx, m in enumerate(seq_model.modules()):
        #print(idx, '->', m)
        if isinstance(m,Spatial):
            spatial_layers.append(m)
    return spatial_layers


from .views import *
from django.contrib.auth import views as auth_views
from django.contrib.auth.models import AnonymousUser
from datetime import timedelta, date
import code;

class CustomerIndexView(View):
    def get(self, request, *args, **kwargs):
        context = {}
        user = request.user
        featured_products = ProductVariant.objects.filter(is_selling=True, is_feature=True)[:6]
        for product in featured_products:
            options = VariantOption.objects.filter(product_id=product.id)
            setattr(product,"option", options.first().id)
        electronic_category = Category.objects.get(pk=1)
        electronic_subcategories = SubCategory.objects.filter(parent=electronic_category)
        for subcategory in electronic_subcategories:
            products = ProductVariant.objects.distinct().filter(is_selling=True,product__sub_category__id=subcategory.id)
            for product in products:
                options = VariantOption.objects.filter(product_id=product.id)
                setattr(product,"option", options.first().id)
            setattr(subcategory, "products", products)

        clothing_category = Category.objects.get(pk=3)
        clothing_subcategories = SubCategory.objects.filter(parent=clothing_category)
        for subcategory in clothing_subcategories:
            products = ProductVariant.objects.distinct().filter(is_selling=True,product__sub_category__id=subcategory.id)
            for product in products:
                options = VariantOption.objects.filter(product_id=product.id)
                setattr(product,"option", options.first().id)
            setattr(subcategory, "products", products)

        book_category = Category.objects.get(pk=2)
        book_subcategories = SubCategory.objects.filter(parent=book_category)
        for subcategory in book_subcategories:
            products = ProductVariant.objects.distinct().filter(is_selling=True,product__sub_category__id=subcategory.id)
            for product in products:
                options = VariantOption.objects.filter(product_id=product.id)
                setattr(product,"option", options.first().id)
            setattr(subcategory, "products", products)

        if 'cart' not in request.session:
            cart = []
        else:
            cart = request.session['cart']
        if user.is_authenticated:
            context["user_id"] = user
            context["favorite"] = Favorite.objects.filter(customer=user).count()
        context["featured_products"] = featured_products
        context["electronic_subcategories"] = electronic_subcategories
        context["clothing_subcategories"] = clothing_subcategories
        context["book_subcategories"] = book_subcategories

        context["cart"] = len(cart)
        return render(request, "boec_core/customer/index.html",context)

class CartView(View):
    def get(self, request, *args, **kwargs):
        context = {}
        user = request.user
        context["user"] = user
        cart = {}
        cart_items = []
        total = 0
        if 'cart' not in request.session:
            cart = {}
        else:
            cart = request.session['cart']
        for item in cart:
            variant = VariantOption.objects.get(pk=item)
            quantity = cart[item]
            amount = quantity * variant.price
            setattr(variant, 'quantity', quantity)
            setattr(variant, 'total', amount)
            total += amount
            cart_items.append(variant)
        context["cart"] = len(cart)
        context["cart_items"] = cart_items
        context["total"] = total

        return render(request, "boec_core/customer/shoping-cart.html",context)

class FavoriteView(View):
    def get(self, request, *args, **kwargs):
        context = {}
        user = request.user
        favorites = Favorite.objects.filter(customer=user)
        featured_products = []
        for favorite in favorites:
            featured_products.append(favorite.product)

        if 'cart' not in request.session:
            cart = []
        else:
            cart = request.session['cart']
        if user.is_authenticated:
            context["user_id"] = user
            context["favorite"] = Favorite.objects.filter(customer=user).count()
        context["featured_products"] = featured_products
        context["cart"] = len(cart)
        return render(request, "boec_core/customer/favorite.html",context)

class ShopGridView(View):
    def get(self, request, *args, **kwargs):
        context = {}
        user = request.user
        search = request.GET.get("search")
        if search is None:
            selling_products = ProductVariant.objects.filter(is_selling=True)
        else:
            selling_products = ProductVariant.objects.distinct().filter(is_selling=True, product__name__icontains=search)

        if 'cart' not in request.session:
            cart = []
        else:
            cart = request.session['cart']
        if user.is_authenticated:
            favorites = Favorite.objects.filter(customer=user)
            context["user_id"] = user
            context["favorite"] = Favorite.objects.filter(customer=user).count()
        context["selling_products"] = selling_products
        context["cart"] = len(cart)
        page_size = settings.PAGE_SIZE
        page_num = request.GET.get("page_num")
        p = Paginator(selling_products, page_size)
        cur_page = p.page(1)
        if page_num is not None:
            cur_page = p.page(page_num)

        context["num_pages"] = p.num_pages
        context["pages"] = range(1, p.num_pages+1)
        return render(request, "boec_core/customer/shop-grid.html",context)
class VariantDetailView(View):
    def get(self, request, *args, **kwargs):
        context = {}
        user = request.user
        variant_id = kwargs.get('variant_id')
        variant = ProductVariant.objects.get(pk=variant_id)
        options = VariantOption.objects.filter(product=variant)
        reviews = CustomerReview.objects.filter(product=variant)
        recommend_products = ProductVariant.objects.filter(is_selling=True, is_feature=True)[:6]
        if 'cart' not in request.session:
            cart = []
        else:
            cart = request.session['cart']
        if user.is_authenticated:
            context["user_id"] = user
            context["favorite"] = Favorite.objects.filter(customer=user).count()
        rating = 0
        for review in reviews:
            rating += review.rating
            replies = Reply.objects.filter(review=review)
            setattr(review, "replies", replies)

        if reviews.count() == 0:
            rating = 0
            context["is_float"] = False
        else:
            rating = rating/reviews.count()
            if(rating%1!=0):
                context["is_float"] = True
        context["cart"] = len(cart)
        context["variant"] = variant
        context["options"] = options
        context["reviews"] = reviews
        context["price"]   = options.first().price
        context["ratings"] = int(rating)
        context["max_rating"] = [1,2,3,4,5]
        context["current_rating"] = [1] * int(rating)
        return render(request, "boec_core/customer/shop-details.html",context)

class SuccessView(View):
    def get(self, request, *args, **kwargs):
        context = {}
        user = request.user
        return render(request, "boec_core/customer/success_page.html",context)

class FailureView(View):
    def get(self, request, *args, **kwargs):
        context = {}
        user = request.user
        return render(request, "boec_core/customer/failure_page.html",context)
class FailureVoucherView(View):
    def get(self, request, *args, **kwargs):
        context = {}
        user = request.user
        return render(request, "boec_core/customer/failure_voucher.html",context)
class CheckoutView(View):
    def post(self, request, *args, **kwargs):
        user = request.user
        cart = {}
        cart_items = []
        total = 0
        name = request.POST.get("name")
        phone = request.POST.get("phone")
        email = request.POST.get("email")
        # Lấy các thông tin được gửi qua post request
        city = int(request.POST.get("city"))
        district = int(request.POST.get("district"))
        street = int(request.POST.get("street"))
        department = int(request.POST.get("department"))
        voucher = request.POST.get("voucher")
        detail = request.POST.get("detail")
        city = City.objects.get(pk=city)
        district = District.objects.get(pk=district)
        street = Street.objects.get(pk=street)
        department = ShippingDepartment.objects.get(pk=department)
        has_voucher = voucher
        voucher = Voucher.objects.filter(code=voucher).first()
        note = request.POST.get("note")
        # hiện tại chưa có api lấY giá vận chuyểN -> mặc định giá vậN chuyển là 30
        shipping_fee = 30
        # nếu user đăng nhập
        if voucher is None and has_voucher is not None:
            return HttpResponseRedirect("/boec/failure_voucher")
        if user.is_authenticated:
            order = Order(recv_name=name,recv_city=city, recv_district = district, recv_street=street, recv_house=detail, recv_phone=phone,
            recv_email=email,note=note,customer=user,payment_type="COD")
        else:
            order = Order(recv_name=name,recv_city=city, recv_district = district, recv_street=street, recv_house=detail,recv_phone=phone,
            recv_email=email,note=note,payment_type="COD")
        try:
            order.save()
            if 'cart' not in request.session:
                cart = {}
            else:
                cart = request.session['cart']
            for item in cart:
                variant = VariantOption.objects.get(pk=item)
                quantity = cart[item]
                amount = quantity * variant.price
                ordered_product = OrderedProduct(quantity=quantity, price=variant.price,
                order=order, product=variant)
                variant.quantity -= quantity
                total+=amount
                variant.save()
                ordered_product.save()
            if voucher:
                if voucher.role == 1:
                    shipping_fee = shipping_fee - voucher.offset
                elif voucher.role == 2:
                    total = total - (total * voucher.sale)/100
                order.voucher = voucher
            # chưa có api của bên giao hàng nên bọn em sẽ tự đạt ra ngày nhận hàng là 3 ngày sau
            estimated = date.today()+timedelta(days=3)

            # Tạo thông tin ship hàng
            ordership = OrderShip(estimated_arrival=estimated, price = shipping_fee, ship=department, order=order)
            ordership.save()
            # Cập nhật đơn hàng
            order.amount = total + shipping_fee
            order.ship = shipping_fee
            order.save()
            # Xoá giỏ hàng cũ
            del request.session['cart']
            return HttpResponseRedirect("/boec/success")
        except:
            return HttpResponseRedirect("/boec/failure")

    def get(self, request, *args, **kwargs):
        context = {}
        user = request.user
        context["user"] = user
        cart = {}
        cart_items = []
        total = 0
        cities = City.objects.all()
        districts = District.objects.all()
        streets = Street.objects.all()
        departments = ShippingDepartment.objects.all()
        address = ShippingAdress.objects.filter(customer=user)
        if 'cart' not in request.session:
            cart = {}
        else:
            cart = request.session['cart']
        for item in cart:
            variant = VariantOption.objects.get(pk=item)
            quantity = cart[item]
            amount = quantity * variant.price
            setattr(variant, 'quantity', quantity)
            setattr(variant, 'total', amount)
            total += amount
            cart_items.append(variant)
        estimated = date.today()+timedelta(days=3)
        context["cart"] = len(cart)
        context["cart_items"] = cart_items
        context["cities"] = cities
        context["districts"] = districts
        context["streets"] = streets
        context["address"] = address
        context["total"] = total
        context["departments"] = departments
        context["estimated"] = estimated

        return render(request, "boec_core/customer/checkout.html",context)


import json
import pandas as pd

total1 =[]
total2 =[]

# 读取json文件内容,返回字典格式
with open('./a.json','r',encoding='utf8')as fp:
    json_data = json.load(fp)
    print('这是读取到文件数据的数据类型：', type(json_data))
    data_list=json_data['data']
    print(len(data_list))

with open('./b.json','r',encoding='utf8')as fp:
    jason_date = json.load(fp)
    data_dict=jason_date['data']['stocks']
    print(len(data_dict))
list1=[]
list2=[]
list3=[]
list4=[]

for i in data_list.values():
    data1=i['symbol'] #用来存放股票代码
    data2=i['stock_chi_name'] #变量用来存放股票名称
    list1.append(data1)
    list2.append(data2)

for data in data_dict:
    data3=data['desc']
    data4=data['symbol']
    list3.append(data3)
    list4.append(data4)

total_data = []

for i in range(len(data_dict)):
    combined_data = []
    combined_data.append(list1[i+1])
    combined_data.append(list2[i+1])
    combined_data.append(list3[i])
    combined_data.append(list4[i])
    total_data.append(combined_data)
    # print(combined_data)

df = pd.DataFrame(total_data)
df.columns =['股票代码', '股票名称',"股票归因","股票代码"]
# print(df)
df.to_csv(r'./res.csv',index=True,encoding='utf_8_sig')


#!/usr/bin/python
# -*- coding: utf-8 -*-

import os
import socket
import logging
import requests
import certifi

try:
    from urllib.parse import urlparse
except ImportError:
    from urlparse import urlparse

from mathtranslate.tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException

logger = logging.getLogger("tencentcloud_sdk_common")

def _get_proxy_from_env(host, varname="HTTPS_PROXY"):
    no_proxy = os.environ.get("NO_PROXY") or os.environ.get("no_proxy")
    if no_proxy and host in no_proxy:
        return None
    return os.environ.get(varname.lower()) or os.environ.get(varname.upper())

class ProxyConnection(object):
    def __init__(self, host, timeout=60, proxy=None, certification=None, is_http=False):
        self.request_host = host
        self.certification = certification
        if certification is None:
            self.certification = certifi.where()
        self.timeout = timeout
        self.proxy = None
        if is_http:
            proxy = proxy or _get_proxy_from_env(host, varname="HTTP_PROXY")
        else:
            proxy = proxy or _get_proxy_from_env(host, varname="HTTPS_PROXY")
        if proxy:
            self.proxy = {"http": proxy, "https": proxy}
        self.request_length = 0

    def request(self, method, url, body=None, headers={}):
        self.request_length = 0
        headers.setdefault("Host", self.request_host)
        return requests.request(method=method,
                                url=url,
                                data=body,
                                headers=headers,
                                proxies=self.proxy,
                                verify=self.certification,
                                timeout=self.timeout)

class ApiRequest(object):
    def __init__(self, host, req_timeout=60, debug=False, proxy=None, is_http=False, certification=None):
        self.conn = ProxyConnection(host, timeout=req_timeout, proxy=proxy, certification=certification, is_http=is_http)
        url = urlparse(host)
        if not url.hostname:
            if is_http:
                host = "http://" + host
            else:
                host = "https://" + host
        self.host = host
        self.req_timeout = req_timeout
        self.keep_alive = False
        self.debug = debug
        self.request_size = 0
        self.response_size = 0

    def set_req_timeout(self, req_timeout):
        self.req_timeout = req_timeout

    def is_keep_alive(self):
        return self.keep_alive

    def set_keep_alive(self, flag=True):
        self.keep_alive = flag

    def set_debug(self, debug):
        self.debug = debug

    def _request(self, req_inter):
        if self.keep_alive:
            req_inter.header["Connection"] = "Keep-Alive"
        if self.debug:
            logger.debug("SendRequest %s" % req_inter)
        if req_inter.method == 'GET':
            req_inter_url = '%s?%s' % (self.host, req_inter.data)
            return self.conn.request(req_inter.method, req_inter_url,
                              None, req_inter.header)
        elif req_inter.method == 'POST':
            return self.conn.request(req_inter.method, self.host,
                              req_inter.data, req_inter.header)
        else:
            raise TencentCloudSDKException(
                "ClientParamsError", 'Method only support (GET, POST)')

    def send_request(self, req_inter):
        try:
            http_resp = self._request(req_inter)
            headers = dict(http_resp.headers)
            resp_inter = ResponseInternal(status=http_resp.status_code,
                                          header=headers,
                                          data=http_resp.text)
            self.request_size = self.conn.request_length
            self.response_size = len(resp_inter.data)
            logger.debug("GetResponse %s" % resp_inter)
            return resp_inter
        except Exception as e:
            raise TencentCloudSDKException("ClientNetworkError", str(e))

class RequestInternal(object):
    def __init__(self, host="", method="", uri="", header=None, data=""):
        if header is None:
            header = {}
        self.host = host
        self.method = method
        self.uri = uri
        self.header = header
        self.data = data

    def __str__(self):
        headers = "\n".join("%s: %s" % (k, v) for k, v in self.header.items())
        return ("Host: %s\nMethod: %s\nUri: %s\nHeader: %s\nData: %s\n"
                % (self.host, self.method, self.uri, headers, self.data))

class ResponseInternal(object):
    def __init__(self, status=0, header=None, data=""):
        if header is None:
            header = {}
        self.status = status
        self.header = header
        self.data = data

    def __str__(self):
        headers = "\n".join("%s: %s" % (k, v) for k, v in self.header.items())
        return ("Status: %s\nHeader: %s\nData: %s\n"
                % (self.status, headers, self.data))