装饰器封装:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2022/1/15 5:06 下午
# @Author : Wayne
# @Email : wayne@wayne.com
# @File : wayne.py
# @Software: PyCharm
from client.env import ENV
import requests
requests.packages.urllib3.disable_warnings()
import base64
from api.executor_log import ExecutorLogger
from functools import wraps
# 日志调用
log = ExecutorLogger()
def login(event, password, username, s):
def looo(func):
@wraps(func)
def llo(*args, **wkargs):
password_1 = base64.b64encode(password.encode('utf-8')).decode()
log.info('---- 开始登录 ---')
try:
login_url = ENV.get(event).get('urls').get('loginurl')
except AttributeError:
raise TypeError('ENV无法获取用户数据')
login_json = {"email": username, "password": password_1}
headers = {"x-bus": '20', "x-logintype": '10'}
client = s.post(login_url, headers=headers, json=login_json, verify=False).json()
try:
decode = client.get("data").get("mokaJwtCode")
except AttributeError:
raise TypeError(F'登陆失败,-->{client}')
host = ENV.get(event).get('urls').get('host')
url = F'{host}/api/outer/wayne-gateway/wayne/verifyCode?bus=20'
verify_code_json = {'bus': '20', 'loginType': "10", 'wayneCode': decode}
a = s.post(url, json=verify_code_json, verify=False)
log.info(F'环境:{event},用户{username}登录成功,%s' % (a.json()))
# event1变量 为了传递给用到装饰器函数
event1 = event
return func(event1,*args, **wkargs)
return llo
return looo
使用装饰器方法:
from api.executor_log import ExecutorLogger
import requests
from test.wayne_test2 import login
requests.packages.urllib3.disable_warnings()
from client.env import ENV
requests.packages.urllib3.disable_warnings()
log = ExecutorLogger()
s = requests.Session()
@login(event='online', username='wayne@wayne.com', password='123456', s=s)
def get_rule(event1):
'''参数event1通过装饰器传递过来'''
url = ENV.get(event1).get('urls').get('host') + '/api/core/v1/abs/clock/rule?bus=20&loginType=20&clientType=1'
res = s.post(url, json={}, verify=False)
log.info(F'获取规则成功--》{res.json()}')
return res.json()
get_rule()