python进阶-mock接口

setting.py

MYSQL_HOST='192.168.127.139'
PASSWORD='123456'
PORT=3306
USER='root'
DB='stu'

tools.py

import pymysql,redis
from conf import setting
def op_mysql(sql):
    conn=pymysql.connect(host=setting.MYSQL_HOST,user=setting.USER,
                         passwd=setting.PASSWORD,
                         port=setting.PORT,db=setting.DB,
                         charset='utf8'
                         )
    cur=conn.cursor(cursor=pymysql.cursors.DictCursor)
    cur.execute(sql)
    sql_start=sql[:6].upper()
    if sql_start=='SELECT':
        res=cur.fetchall()
    else:
        conn.commit()
        res='ok'
    cur.close()
    conn.close()
    return res

def op_redis(host,password,k,v=None,port=6379,db=0):
    r=redis.Redis(host=host,password=password,port=port,db=db)
    if v:
        r.set(k,v)#有传key就说明是set操作
        res='ok'
    else:
        res=r.get(k)
        if res:#判断有没有get到数据
            res=res.decode()#没有传key就说明是get操作,如果传的key不存在返回None,None没有decode
        else:
            res=None
    return res

student.py

import flask,json#轻量级的web开发框架
from lib.tools import op_mysql
#接口 后台服务
server=flask.Flask(__name__) #返回python文件名,此处把python文件当成一个服务
#获取所有用户信息的接口
@server.route('/get_user',methods=['get','post'])#装饰器,接受两个参数:路径/请求方式
def get_all_user():
    sql='select * from Student limit 10;'
    res = op_mysql(sql=sql)
    response=json.dumps(res,ensure_ascii=False)#把list转化成jason
    return response#return 只能reture字符串


#添加学生的接口
@server.route('/add_user',methods=['post'])#装饰器,路径/请求方式
def add_user():
    s_no=flask.request.values.get('s_no')#获得传入的参数
    sname = flask.request.values.get('sname')#获得传入的参数
    age = flask.request.values.get('age')
    sex = flask.request.values.get('sex')
    if s_no and sname and age and sex:#判断必填参数非空
        sql = "insert into Student values ('%s','%s','%s','%s');" % (s_no,sname,age,sex)#添加学生的sql语句
        #sql ="INSERT INTO Student  VALUES ('%s','%s','%s','%s');"%(s_no,sname,age,sex)
        res = op_mysql( sql=sql)#调用封装的mysql函数
        response={'code':203,'msg':'成功了'}#请求成功后返回的信息
    else:#必填项为空提示信息
        response = {'code': 403, 'msg': '必填参数未填!'}
    return json.dumps(response,ensure_ascii=False)#将response转化成jason返回,ensure_ascii=False,使中文正常显示,不指定的话,会显示中文对应的ascii

 

start.py

import sys,os
#os.path.dirname(__file__)
#print(sys.path)
BATH_PATH=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))#取两次父目录 ,__file__代表当前目录,os.path.dirname取父目录
sys.path.insert(0,BATH_PATH)#加入环境变量
from lib.student import server
#server.run(port=8088,debug=True)
#想让别人访问,同一个局域网host='0.0.0.0',用实际的ip访问
server.run(port=8088,host='0.0.0.0',debug=True)

返回的信息是:

* Restarting with stat
* Debugger is active!
* Debugger PIN: 290-225-122
* Running on http://127.0.0.1:9999/ (Press CTRL+C to quit)

以 http://127.0.0.1:9999/add_user访问接口


 

posted @ 2018-01-23 11:30  笨笨的妞  Views(394)  Comments(0Edit  收藏  举报