码迷,mamicode.com
首页 > 编程语言 > 详细

python中的__call__函数

时间:2019-08-22 00:41:42      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:ase   单实例   ram   log   param   try   error   eva   rdl   

简单实例:

class TmpTest:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __call__(self, x, y):
        self.x, self.y = x, y


a = TmpTest(1, 2)
a(4, 5)
print(a.x, a.y)
4 5

实战中应用:

import json
import requests

from common.RecordLog import log


class HttpRequests(object):
    def __init__(self):
        self.session = requests.Session()
        log.info(建立请求...)

    def send_request(self, method, url, params_type=form, data=None, **kwargs):
        method = method.upper()
        params_type = params_type.upper()
        if isinstance(data, str):
            try:
                data = json.loads(data)
            except Exception:
                    data = eval(data)
        if GET == method:
            response = self.session.request(method=method, url=url, params=data, **kwargs)
        elif POST == method:
            if params_type == FORM:
                log.info("开始发送{}请求,URL为:{},请求数据为:{}".format(method, url, data))
                response = self.session.request(method=method, url=url, data=data, **kwargs)
            elif params_type == JSON:
                response = self.session.request(method=method, url=url, json=data, **kwargs)
            else:
                response = self.session.request(method=method, url=url, **kwargs)
        else:
            log.error("请求方法错误:request method ‘{}‘ error ! please check".format(method))
            raise ValueError(request method "{}" error ! please check.format(method))
        return response

    def __call__(self, method, url, params_type=form, data=None, **kwargs):
        return self.send_request(method, url,
                                 params_type=params_type,
                                 data=data,
                                 **kwargs)

    def close_session(self):
        self.session.close()
        try:
            log.info(关闭请求...)
            del self.session.cookies[JSESSIONID]
        except Exception:
            pass


request = HttpRequests()

 

python中的__call__函数

标签:ase   单实例   ram   log   param   try   error   eva   rdl   

原文地址:https://www.cnblogs.com/wang-mengmeng/p/11391878.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!