Commit dce4cb54 authored by 邓莹莹's avatar 邓莹莹

优化登录

parent 6d41c279
''' '''
钩子函数,解决ids乱码问题 钩子函数,解决ids乱码问题
''' '''
import pytest
import path_setting
from in_common.base_request import BaseRequest
data = BaseRequest().api_load(path_setting.LOGIN_FUNCTION_DATA)
def pytest_collection_modifyitems(items): def pytest_collection_modifyitems(items):
for item in items: for item in items:
item.name = item.name.encode("utf-8").decode("unicode_escape") item.name = item.name.encode("utf-8").decode("unicode_escape")
item._nodeid = item.nodeid.encode("utf-8").decode("unicode_escape") item._nodeid = item.nodeid.encode("utf-8").decode("unicode_escape")
@pytest.fixture(scope = "session",autouse=True)
def login_function():
headers = BaseRequest().get_cookie(data["backend_login"])
with open(path_setting.GET_COOKIE, 'w+') as f:
f.write(str(headers))
print("看看执行几次")
\ No newline at end of file
...@@ -3,8 +3,10 @@ import random ...@@ -3,8 +3,10 @@ import random
import string import string
import requests import requests
import yaml import yaml
import os
import sys
# from jsonpath import jsonpath # from jsonpath import jsonpath
from login_session_function import LoginFunction # from login_session_function import LoginFunction
# from pymysql import OperationalError # from pymysql import OperationalError
import path_setting import path_setting
...@@ -26,13 +28,23 @@ class BaseRequest: ...@@ -26,13 +28,23 @@ class BaseRequest:
# 调用yaml加载文件API加载 # 调用yaml加载文件API加载
def api_load(self, path: object) -> object: def api_load(self, path: object) -> object:
print("path路径",path) print("path路径", path)
return self.yaml_load(path) return self.yaml_load(path)
# def jsonpath(self, path, r=None, **kwargs): # def jsonpath(self, path, r=None, **kwargs):
# if r is None: # if r is None:
# r = self.r.json() # r = self.r.json()
# return jsonpath(r, path) # return jsonpath(r, path)
def read_header(self):
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
sys.path.append(BASE_DIR)
print("os.getcwd()",os.getcwd())
path = os.path.join(BASE_DIR, "in_common/get_cookie.txt")
print("path---------", path)
with open(path, 'r', encoding='utf-8') as f:
cookies = f.read()
headers = {"cookie": cookies}
return headers
def api_send(self, req: object) -> object: def api_send(self, req: object) -> object:
host = self.api_load(path_setting.HOSTYAML_CONFIG) host = self.api_load(path_setting.HOSTYAML_CONFIG)
...@@ -46,7 +58,7 @@ class BaseRequest: ...@@ -46,7 +58,7 @@ class BaseRequest:
if host_service not in host['develop_host']: if host_service not in host['develop_host']:
host_service = 'backend' host_service = 'backend'
url_host = host['develop_host'][host_service] url_host = host['develop_host'][host_service]
print("-----------",url_host) print("-----------", url_host)
# if host["develop_host"].get("doctor") is not None: # if host["develop_host"].get("doctor") is not None:
# url_host = host['develop_host']['doctor'] # url_host = host['develop_host']['doctor']
# elif host["develop_host"].get("backend") is not None: # elif host["develop_host"].get("backend") is not None:
...@@ -57,25 +69,23 @@ class BaseRequest: ...@@ -57,25 +69,23 @@ class BaseRequest:
raw = raw.replace(f"${{{key}}}", repr(value)) raw = raw.replace(f"${{{key}}}", repr(value))
req = yaml.safe_load(raw) req = yaml.safe_load(raw)
print('req:', req) print('req:', req)
# print("self.read_header()",self.read_header())
s = requests # s = requests
if req.get('isLogin'): # if req.get('isLogin'):
s = LoginFunction().get_session() # s = LoginFunction().get_session()
# 调用具体case的url # 调用具体case的url
r = s.request( r = requests.request(
req['method'], req['method'],
url=url_host + req['url'], url=url_host + req['url'],
params=req.get('params'), params=req.get('params'),
# headers=user_headers, headers=self.read_header(),
data=req.get('data'), data=req.get('data'),
json=req.get('json'), json=req.get('json'),
# verify=False # verify=False
# proxies={"http":"172.30.9.226:8888"} # proxies={"http":"172.30.9.226:8888"}
) )
# print("0000000",r.json())
# return r.json()
try: try:
content_type = r.headers.get("content-type").split(";")[0] content_type = r.headers.get("content-type").split(";")[0]
except: except:
...@@ -85,37 +95,26 @@ class BaseRequest: ...@@ -85,37 +95,26 @@ class BaseRequest:
return r.text return r.text
# 随机生成trace_id def get_cookie(self, req: dict):
def trace_id(self): host = self.api_load(path_setting.HOSTYAML_CONFIG)
return ''.join(random.sample(string.ascii_lowercase + string.digits, 32)) print(host)
r = requests.request(
''' req['method'],
def get_cookie(self, req: dict): url=host['develop_host']['backend'] + req['url'],
params=req['params'],
host = self.api_load(path_setting.HOSTYAML_CONFIG) headers=req['headers'],
print(host) data=req['data'],
r = requests.request( json=req['json']
req['method'], )
url=host['develop_host']['url'] + req['url'], dict = {}
params=req['params'], for i in r.cookies:
headers=req['headers'], dict[i.name] = i.value
data=req['data'], headers = '_gtid={};sessionid={}'.format(dict["_gtid"], dict["sessionid"])
json=req['json'] return headers
)
dict = {}
for i in r.cookies:
dict[i.name] = i.value
headers = '_gtid={};sessionid={}'.format(dict["_gtid"], dict["sessionid"])
return headers
def read_header(self):
with open("../in_common/get_cookie.txt", 'r', encoding='utf-8') as f:
cookies = f.read()
headers = {"cookie": cookies}
return headers
'''
if __name__ == '__main__': if __name__ == '__main__':
# BaseRequest().api_load("../api/api.yaml") # BaseRequest().api_load("../api/api.yaml")
print(BaseRequest().trace_id()) print(BaseRequest().trace_id())
_gtid=a5dc3a8ff66a11eba9bbfa6400b8dbcd9180;sessionid=qaoahf1vwrxsumc6vl1ok4tx9lckf12f
\ No newline at end of file
import path_setting
import requests
import yaml
"""
此文件是封装session的
"""
class LoginFunction:
def __init__(self):
self.host = self.login_yaml_load(path_setting.HOSTYAML_CONFIG)
self.params = self.login_yaml_load(path_setting.LOGIN_FUNCTION_DATA)
def login_yaml_load(self, path) -> list:
with open(path, encoding='utf-8') as f:
return yaml.safe_load(f)
def get_session(self):
hostList = self.host['develop_host']
for key in hostList:
if 'backend' == key:
return self.get_develop_session()
if 'doctor' == key:
return self.get_doctor_session()
elif 'om' == key:
return self.get_om_session()
def get_develop_session(self):
url = self.host["develop_host"]["backend"] + self.params["backend_login"]["url"]
s = requests.session()
r = s.request(
self.params["backend_login"]["method"],
url=url,
params=self.params["backend_login"]["params"],
data=self.params["backend_login"]["data"],
headers={'Connection': 'close'},
# verify=False
)
return s
def get_doctor_session(self):
url = self.host["develop_host"]["doctor"] + self.params["doctor_login"]["url"]
s = requests.session()
r = s.request(
self.params["doctor_login"]["method"],
url=url,
params=self.params["doctor_login"]["params"],
data=self.params["doctor_login"]["data"],
headers={'Connection': 'close'}
)
return s
def get_om_session(self):
url = self.host["develop_host"]["om"] + self.params["om_login"]["url"]
s = requests.session()
r = s.request(
self.params["om_login"]["method"],
url=url,
params=self.params["om_login"]["params"],
data=self.params["om_login"]["data"],
headers={'Connection': 'close'}
)
return s
if __name__ == '__main__':
LoginFunction().get_session()
\ No newline at end of file
...@@ -3,9 +3,14 @@ backend_login: ...@@ -3,9 +3,14 @@ backend_login:
url: /api/accounts/login/password url: /api/accounts/login/password
params: params:
current_city_id: "beijing" current_city_id: "beijing"
headers: {
"User-Agent": com.wanmeizhensuo.zhensuo/7.27.2 AsyncHttpClient/1.4.5 Android/9,
"Content-Type": application/x-www-form-urlencoded
}
data: data:
phone: "18301089928" phone: "12345654321"
password: 123456 password: 123456
lng: 116.4879672787569 lng: 116.4879672787569
lat: 39.98338452087316 lat: 39.98338452087316
face_token: face_token:
json: {}
\ No newline at end of file
...@@ -5,6 +5,8 @@ sys.path.append(BASE_DIR) ...@@ -5,6 +5,8 @@ sys.path.append(BASE_DIR)
HOSTYAML_CONFIG = os.path.join(BASE_DIR, "on_line_product", "host.yaml") HOSTYAML_CONFIG = os.path.join(BASE_DIR, "on_line_product", "host.yaml")
LOGIN_FUNCTION_DATA = os.path.join(BASE_DIR, "on_line_product", "login_session_function.yaml") LOGIN_FUNCTION_DATA = os.path.join(BASE_DIR, "on_line_product", "login_session_function.yaml")
GET_COOKIE = os.path.join(BASE_DIR, "on_line_product/in_common", "get_cookie.txt")
APYAML_CONFIG = os.path.join(BASE_DIR, "on_line_product/all_backend_api", "account_request.yaml") APYAML_CONFIG = os.path.join(BASE_DIR, "on_line_product/all_backend_api", "account_request.yaml")
LOGIN_VFC = os.path.join(BASE_DIR, "on_line_product/test_backend_data/account_data", "login_vfc.yaml") LOGIN_VFC = os.path.join(BASE_DIR, "on_line_product/test_backend_data/account_data", "login_vfc.yaml")
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment