python mock接口 ,网络请求2

使用模块 flask  

为什么用,为了本地写一些接口使用psotman一些工具测试  

import flask
#轻量级的web开发框架
import tools
import json
import datetime
import time
server = flask.Flask(__name__)
@server.route('/login',methods=['post','get'])#写接口的方法
def login():
username = flask.request.values.get('username','') #获取请求参数
password = flask.request.values.get('password','')
# print(flask.request.cookies.get('PHPSESSID'))#传cookie方法
# print('json',flask.request.json) #传json
# flask.json.get('xxxx')#如果入参是json类型的话,这么搞
# flask.request.cookies.get('xxx')#获取cookie里面的数据
# flask.request.headers.get('xx')#在hrader里面传
# flask.request.files.get("xxx")#文件

if username.strip() and password.strip():
p = tools.my_md5(password)
query_sql = 'select * from app_myuser where username= "%s" and passwd="%s";' % (username, p)
if tools.execute_sql(query_sql):
return json.dumps({'code': '0', 'msg': '登录成功','sessionid':'xxxx'},ensure_ascii=False)
else:
return json.dumps({'code': '-1', 'msg': '输入的用户名/密码错误'})
else:
return json.dumps({'code': '-1', 'msg': '不能为空'})

@server.route('/reg',methods=['post','get'])#定义接口
def reg():
username = flask.request.values.get('username')
password = flask.request.values.get('password')
cpassword = flask.request.values.get('cpassword')
if username.strip() and password.strip() and cpassword.strip():
if password.strip() != cpassword.strip():
return json.dumps({'code': -1, 'msg': '两次输入的密码不一样'})
else:
sql='select * from app_myuser where username="%s";'%username
if tools.execute_sql(sql):
return json.dumps({'code':-1,'msg':'用户已经存在'})
else:
p = tools.my_md5(password)
insert_sql = 'insert into app_myuser (username,passwd) value ("%s","%s");'%(username,p)
tools.execute_sql(insert_sql)
return json.dumps({'code':0,'msg':'注册成功!'},ensure_ascii=False)

else:
return json.dumps({'code':-1,'msg':'必填参数不能为空'})

count = 1
start_time = 0
f = open('a2.txt','a+',encoding='utf-8')
@server.route('/')
def test():
global count,start_time
t = datetime.datetime.now().strftime("%H:%M:%S")
id = flask.request.values.get("id")
f.write("%s %s %s " % (t,id,count))
if id=='1':
start_time = time.time()
count+=1
if id == '10000':
end_time = time.time()
run_time = end_time - start_time
print('运行时间',run_time)
f.write("运行时间 %s" % run_time)
f.close()

return str(flask.request.values.get("id"))


server.run(host='127.0.0.1',port=8999)#写127别人都可以访问你网址,提供给别人你的IP和端口

最最简单的接口实战

import flask
#轻量级的web开发框架
import tools
import json
import datetime
import time
server = flask.Flask(__name__)
@server.route('/login',methods=['post','get'])#写接口的方法
def login():
username = flask.request.values.get('username','') #获取请求参数
password = flask.request.values.get('password','')
if username=='王海兰'and password=='123':
return json.dumps({'恭喜你':'登录成功'},ensure_ascii=False)
else:
return json.dumps({'不好意思': '王海兰太丑'},ensure_ascii=False)
server.run(host='127.0.0.1',port=8999)#写127别人都可以访问你网址,提供给别人你的IP和端口


原文地址:https://www.cnblogs.com/weilemeizi/p/14533157.html