测试自动化学习8

批量备份py第三方模块

pip freeze > 第三方模块.txt

# 批量安装第三方模块
pip install -r 第三方模块.txt

 

使用flask开发接口

import flask, json, random, string

server = flask.Flask(__name__)


@server.route('/login')  # 紧贴着函数加上装饰器,就可以变成接口
def welcome():
    session_id = ''.join(random.sample(string.ascii_letters + string.digits, 16))  # 随机16位字符串
    data = {'code': 0, 'msg': '登陆成功', 'session_id': session_id}
    return json.dumps(data, ensure_ascii=False)


@server.route('/test')  # 紧贴着函数加上装饰器,就可以变成接口
def test():
    data = {'code': 0, 'msg': 'test success!\n嘤嘤嘤\n一拳一个☝️的嘤嘤怪啊'}
    return json.dumps(data, ensure_ascii=False)  # 返回中文不乱码

# 入参是get
@server.route('/urldata')  # get请求,参数在url里面的:http://127.0.0.1:8899/urldata?name=晴天娃娃&passwd=123456
def urlData():
    msg = flask.request.args.get('name')
    passwd = flask.request.args.get('passwd')
    data = {'msg':msg, 'passwd':passwd}

    return json.dumps(data, ensure_ascii=False)

# 入参是post的
@server.route('/post', methods=['post'])  # post请求,参数在url里面的:http://127.0.0.1:8899/urldata?name=晴天娃娃&passwd=123456
def post():
    # url形式传过来的
    msg = flask.request.args.get('name')  
    passwd = flask.request.args.get('passwd')  

    # k-v模式传过来的
    stu_name = flask.request.values.get('stu_name')
    addr = flask.request.values.get('addr')

    data = {'user':msg, 'passwd':passwd, 'stu_name':stu_name, 'addr':addr}

    return json.dumps(data, ensure_ascii=False)

# 入参是json
@server.route('/add_student2', methods=['post'])
def add_stu2():
    if flask.request.is_json:
        stu_name = flask.request.get_json('name')
        age = flask.request.get_json('age')
        sex = flask.request.get_json('sex')
        addr = flask.request.get_json('addr')
        phone = flask.request.get_json('phone')
        stu_class = flask.request.get_json('class')
        return json.dumps({'msg': '添加成功!', 'stu_name:': stu_name, 'age:': age, 'sex:': sex, 'addr:': addr, 'phone:': phone, 'class:': stu_class}, ensure_ascii=False)
    else:
        return json.dumps({'msg': '请传入json!'}, ensure_ascii=False)


# 上传文件
@server.route('/file', methods=['post'])  # 使用postman请求,文件在Body--form-data--key(类型选file)--value(上传本地文件)
def uploadFile():
    file = flask.request.files.get('f')
    print(file.filename)
    file.save(file.filename)
    # print(dir(file))
    return json.dumps({'msg': '上传完成!'}, ensure_ascii=False)


server.run(host='0.0.0.0', port=8899, debug=True)  # 默认端口 5000,debug开关表示代码更改后自动重启服务(不要在生产环境中使用),host='0.0.0.0'指定ip则非本机也能访问

 

通过接口传参从数据库获取数据

import pymysql, hashlib
import flask, json

def op_mysql(sql: str):
    mysql_info = {
        'host': '127.0.0.1',
        'port': 3306,
        'password': '123456',
        'user': 'admin',
        'db': 'stu',
        'charset': 'utf8',
        'autocommit': True
    }
    result = '执行完成'
    conn = pymysql.connect(**mysql_info)
    cur = conn.cursor(pymysql.cursors.DictCursor)  # 建立游标
    cur.execute(sql)
    if sql.strip().lower().startswith('select'):
        result = cur.fetchall()
    cur.close()
    conn.close()
    return result


server = flask.Flask(__name__)


@server.route('/table_data')
def get_table_data():
    table_name = flask.request.args.get('table_name')
    limit = flask.request.args.get('limit', '10')  # 默认限制10个
    allow_table = ['app_myuser', 'dxk_test', 'app_student', 'app_product']
    if not table_name:
        return json.dumps({'msg:': 'table_name为必填字段'}, ensure_ascii=False)
    # if table_name not in str(op_mysql('show tables;')):  # 未实现检查table是否存在
    #     return json.dumps({'msg:': 'table_name不存在'}, ensure_ascii=False)
    # # if table_name not in allow_table:
    # #     return json.dumps({'msg:': '没有权限获取该表数据'}, ensure_ascii=False)
    if limit.isdigit():
        sql = 'select * from %s limit %s' % (table_name, limit)
    else:
        return json.dumps({'msg:': 'limit请传入整数'}, ensure_ascii=False)
    res = op_mysql(sql)
    return json.dumps(res, ensure_ascii=False)


server.run(debug=True)

 

 

拆分python功能模块

"""
主要分为一下文件
➜  day8 git:(master) ✗ tree work
work
├── README.txt
├── config
│   ├── __pycache__
│   │   └── setting.cpython-37.pyc
│   └── setting.py
├── lib
│   ├── __pycache__
│   │   ├── interface.cpython-37.pyc
│   │   └── tools.cpython-37.pyc
│   ├── interface.py
│   └── tools.py
└── main.py
"""

# README.txt 介绍各文件夹功能及整个项目实现的功能,以及安装依赖等

# config 文件夹存放各种配置文件及参数,如一下setting文件内容
mysql_info = {
    'host': '127.0.0.1',
    'port': 3306,
    'password': '123456',
    'user': 'admin',
    'db': 'stu',
    'charset': 'utf8',
    'autocommit': True
}


redis_info = {
    'host': '127.0.0.1',
    'password': '123456',
    'db': 7,
    'decode_responses': True

}

server_info = {
    'host': '0.0.0.0',
    'port': 8888,
    'debug': True
}


SALT = 'kadsjijv'

# lib 文件夹存放重新运行逻辑部分,如 tools 文件
import hashlib, pymysql, redis, time
from config import setting


def md5(s):
    s = (str(s) + setting.SALT).encode()
    m = hashlib.md5(s)  # 加密
    return m.hexdigest()


def op_mysql(mysql_info, sql: str):
    result = '执行完成'
    conn = pymysql.connect(**mysql_info)
    cur = conn.cursor(pymysql.cursors.DictCursor)  # 建立游标
    cur.execute(sql)
    if sql.strip().lower().startswith('select'):
        result = cur.fetchall()
    cur.close()
    conn.close()
    return result


def redis_add_session(redis_info, username: str):
    r = redis.Redis(**redis_info)
    r.set('prw_session:%s' % username,
          md5('%s' % username))  # 以 prw_session 为文件夹 prw_session:username和username 的md5为 k-v
    r.expire('prw_session:%s' % username, 3600 * 24)
    # username_md5 = md5('%s' % username)
    return md5('%s' % username)


def get_user_session(redis_info, session_r: str):
    r = redis.Redis(**redis_info)
    list = []
    for i in r.keys():
        if 'prw_session:' in i:
            list.append(r.get(i))
    if session_r in list:
        return True
    else:
        return False



def StrToTimeStamp(str_time=None, format='%Y-%m-%d %H:%M:%S'):
    """格式化好的时间转时间戳"""
    if str_time:
        time_tuple = time.strftime(str_time, format)  # 把格式化好的时间转为时间元祖
        res = time.mktime(time_tuple)  # 时间元祖转时间戳
        return int(res)
    return int(time.time())  # 获取当前时间戳


def TimeStampToStr(timestamp=None, format='%Y-%m-%d %H:%M:%S'):
    if timestamp:
        time_tuple = time.localtime(timestamp)
        res = time.strftime(format, time_tuple)
        return res
    else:
        return time.strftime(format)

#以及interface文件
import flask, json
from config.setting import mysql_info
from config.setting import redis_info
from lib import tools

server = flask.Flask(__name__)


@server.route('/table_data')
def get_table_data():
    table_name = flask.request.args.get('table_name')
    limit = flask.request.args.get('limit', '10')  # 默认限制10个
    allow_table = ['app_myuser', 'dxk_test', 'app_student', 'app_product']

    if not table_name:
        return json.dumps({'msg:': 'table_name为必填字段'}, ensure_ascii=False)
    # if table_name not in str(op_mysql('show tables;')):  # 未实现检查table是否存在
    #     return json.dumps({'msg:': 'table_name不存在'}, ensure_ascii=False)
    # # if table_name not in allow_table:
    # #     return json.dumps({'msg:': '没有权限获取该表数据'}, ensure_ascii=False)
    if limit.isdigit():
        sql = 'select * from %s limit %s' % (table_name, limit)
    else:
        return json.dumps({'msg:': 'limit请传入整数'}, ensure_ascii=False)
    res = tools.op_mysql(mysql_info, sql)
    return json.dumps(res, ensure_ascii=False)


@server.route('/login', methods=['post'])
def login():
    username = flask.request.values.get('username')
    password = flask.request.values.get('password')
    if not username and not password:
        return json.dumps({'msg:': 'username和password为必填字段'}, ensure_ascii=False)
    sql_checkname = "select count(*) as c from prw_users where user='%s';" % username  # 查询用户名是否存在
    res_cn = tools.op_mysql(mysql_info, sql_checkname)
    sql = "select password from prw_users where user='%s';" % username
    res = tools.op_mysql(mysql_info, sql)
    # [{'password': '5ee212502e41b931dff96f1a336783dd'}]
    if res_cn[0]['c'] == 0:
        return json.dumps({'msg:': '请输入正确的用户名/密码'}, ensure_ascii=False)
    passwd_r = res[0]['password']
    if tools.md5('%s' % password) != passwd_r:
        return json.dumps({'msg:': '请输入正确的用户名/密码'}, ensure_ascii=False)
    else:
        username_md5 = tools.redis_add_session(redis_info, username)
        return json.dumps({"session": "%s" % str(username_md5), "code": 0, "msg:": "登录成功"}, ensure_ascii=False)


@server.route('/add_qq_mem', methods=['post'])
def add_qq_mem():
    qq = flask.request.values.get('qq')
    nick = flask.request.values.get('nick')
    join_time = flask.request.values.get('join_time')
    gender = flask.request.values.get('gender')
    card = flask.request.values.get('card')
    session = flask.request.values.get('session')
    if tools.get_user_session(redis_info, session):
        if qq and nick and join_time and session:
            sql_checkqq = "select count(*) as c from prw_qq_mem where qq='%s';" % qq  # 查询qq是否已存在
            res_qq = tools.op_mysql(mysql_info, sql_checkqq)
            if res_qq[0]['c'] == 1:
                return json.dumps({'msg:': 'QQ号码已存在,请重新输入'}, ensure_ascii=False)
            else:
                sql = "insert into prw_qq_mem (qq, nick, join_time,gender, card) values ('%s', '%s', '%s', '%s', '%s')" % (
                    qq, nick, join_time, gender, card)
                res = tools.op_mysql(mysql_info, sql)
                return json.dumps(
                    {'msg:': '添加QQ成员信息成功!', 'qq': qq, 'nick': nick,
                     'join_time': '%s' % tools.TimeStampToStr(int(join_time)),
                     'gender': gender,
                     'card': card},
                    ensure_ascii=False)
        else:
            return json.dumps({'msg:': '请输入qq、nick、join_time'}, ensure_ascii=False)
    else:
        return json.dumps({'msg:': '未登录'}, ensure_ascii=False)


# 最后是主程序,在工程文件夹的根目录 main.py,开始运行整个程序直接运行main即可
from lib import interface
from config.setting import server_info
import sys, os

BASE_PATH = os.path.dirname(os.path.abspath(__file__))  # 获取父目录,__file__ 获取当前文件绝对位置
sys.path.insert(0,BASE_PATH)  # 将工程文件目录加入环境变量,位置0,即可实现import此文件夹下面 config、lib 文件夹里面各模块
# print(sys.path)


interface.server.run(**server_info)

 

posted @ 2019-05-24 09:02  fatenet  阅读(170)  评论(0编辑  收藏  举报