89 lines
2.5 KiB
Python
89 lines
2.5 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""登录态管理:JSESSIONID + 业务 token 的获取、持久化与读取。
|
|
|
|
设计要点:
|
|
1. 会话只落 artifacts/session.json,该目录已 gitignore —— 凭据不进版本库;
|
|
2. 路径统一走 core.path,不出现硬编码的用户目录,跨平台可跑;
|
|
3. 账号密码一律走环境变量 MES_USER / MES_PASS,缺省为合成 demo 账号。
|
|
"""
|
|
import json
|
|
import os
|
|
import uuid
|
|
|
|
import requests
|
|
|
|
from core import config
|
|
from core.path import artifact_path
|
|
|
|
_SESSION_FILE = artifact_path('session.json')
|
|
|
|
# 进程内缓存,避免每次请求都读盘
|
|
_cache = {}
|
|
|
|
|
|
def login(user=None, pwd=None):
|
|
"""调 /mes/login 换取 JSESSIONID,再取 token,落盘到 artifacts/。"""
|
|
user = user or config.username()
|
|
pwd = pwd or config.password()
|
|
url = config.base_url() + '/mes/login'
|
|
resp = requests.post(url, data={'username': user, 'password': pwd, 'encrypt': 0},
|
|
headers={'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'})
|
|
body = resp.json()
|
|
if body.get('code') != 200:
|
|
raise RuntimeError('登录失败: {0}'.format(body))
|
|
|
|
session = {
|
|
'cookie': resp.cookies.get('JSESSIONID', ''),
|
|
'username': user,
|
|
'mes_id': None,
|
|
'token': None,
|
|
}
|
|
|
|
# 换取业务 token
|
|
cookie_header = 'JSESSIONID=' + session['cookie']
|
|
token_resp = requests.get(config.base_url() + '/mes/login/token',
|
|
headers={'Cookie': cookie_header})
|
|
if token_resp.text:
|
|
session['token'] = token_resp.json().get('token')
|
|
|
|
user_resp = requests.get(config.base_url() + '/mes/login/user',
|
|
headers={'Cookie': cookie_header})
|
|
if user_resp.text:
|
|
session['mes_id'] = user_resp.json().get('data', {}).get('mesId')
|
|
|
|
with open(_SESSION_FILE, 'w', encoding='utf-8') as f:
|
|
f.write(json.dumps(session, ensure_ascii=False))
|
|
_cache.update(session)
|
|
return session
|
|
|
|
|
|
def _load():
|
|
if not _cache:
|
|
if os.path.exists(_SESSION_FILE):
|
|
with open(_SESSION_FILE, encoding='utf-8') as f:
|
|
_cache.update(json.load(f))
|
|
else:
|
|
login()
|
|
return _cache
|
|
|
|
|
|
def get_cookie():
|
|
return _load().get('cookie', '')
|
|
|
|
|
|
def get_token():
|
|
return _load().get('token')
|
|
|
|
|
|
def get_mes_id():
|
|
return _load().get('mes_id')
|
|
|
|
|
|
def get_username():
|
|
return _load().get('username')
|
|
|
|
|
|
def new_session_id():
|
|
"""给 mock / 单测用的合成会话 id。"""
|
|
return uuid.uuid4().hex
|