flask开发接口简介
flask是一个python编写的轻量级框架,可以使用它实现一个网站或者web服务。此外,python运用Django开发后台接口。本文就用flask来开发一个接口。
flask需要先安装再引用。pipinstallflask
用flask开发接口的流程为:
定义一个server
server=flasFlask(__name__)#__name__代表当前的python文件。把当前的python文件当做一个服务启动
然后定义接口函数,一般函数和接口函数的区别在于,定义为接口的函数上方要特别加上:
@server.route('/index',methods=['get','post'])#第一个参数就是路径,第二个参数支持的请求方式,不写的话默认是get
@server.route('/index',methods=['get','post'])#第一个参数就是路径,第二个参数支持的请求方式,不写的话默认是get
def index():
res={'msg':'这是我开发的第一个借口','msg_code':0}
return json.dumps(res,ensure_ascii=False)
让server执行起来
#port可自定义填写,默认是5000。不要与机器上已占用的port冲突。
#debug=True,在代码进行修改后,程序会自动重新加载,不用再次运行。也就是运行一次即可,即使改动代码,也不需要重启服务
#host本地ip地址,写0.0.0.0,可以让其他人直接访问本机的ip。
#最终这个接口的访问地址就是 http://127.0.0.1/index ,get方法或者post方法都可。返回数据是json格式res内容
闲话少说,下面就给出例子和测试结果
编写server_new.py,代码如下:
#!/usr/bin/envpython#-*-coding:utf-8-*-importsubprocessimportflask,json'''CREATETABLEIFNOTEXISTS`my_user`(`auto_id`INTUNSIGNEDAUTO_INCREMENT,`username`VARCHAR(50)NOTNULL,`passwd`VARCHAR(40)NOTNULL,`is_admin`INT,PRIMARYKEY(`auto_id`))ENGINE=InnoDBDEFAULTCHARSET=utf8;'''server=flasFlask(__name__)#__name__代表当前的python文件,把当前这个python文件,当成一个服务defexcute_command(username,pw:ifusername=='yyz':return'excute_commandusername=yyzpwd=%s'%pwdelse:return'excute_commandusername=%spwd=%s'%(username,pwdefmy_db(sq:importpymysqlcoon=pymysqconnect(host='120.0.1',user='root',passwd='y44444444',port=3306,db='test_db',charset='utf8')cur=coocursor()cur.execute(sqifsqstrip()[:6].upper()=='SELECT':#判断sql语句是否select开头res=cur.fetchall()#获取到sql语句所有的返回结果else:coocommit()res='ok'cur.close()cooclose()returnres@server.route('/index',methods=['get'])#装饰器ip:5000/index?xxxdefindex():res={'msg':'这个是我开发的第一个接口','msg_code':0}#这个是字典,接口返回的是json,所以需要引入json,并且返回进行jsodumpsreturnjsodumps(res,ensure_ascii=Fals#返回结果是unicode,需要增加ensure_ascii=False@server.route('/reg',methods=['post'])defreg():try:date=flasrequest.values.get('date')print'date-date',datecourse_id=int(flasrequest.values.get('course_id'))chapter_id=int(flasrequest.values.get('chapter_id'))subprocess.Popen('bas/maish''+str(dat+''',shell=Trures={'msg':str(dat+'执行shell成功!','msg_code':0}except:res={'msg':'参数非法,请检查接口文档!','msg_code':1001}returnjsodumps(res,ensure_ascii=Falsif__name__=='__main__':server.run(port=5001,debug=True,host='0.0.0.0')#端口号要是不指定,默认为5000.debug=True,改了代码之后不用重启,会自动重启一次。后面增加host='0.0.0.0',别人可以访问
接口访问中,经常会需要输入参数。那么如果要接受传入的参数,则可用以下方法:
编写maish脚本,这里面可以进行任何种类的开发:
#!/usr/bin/bashPYTHON='/usr/bin/python'functionhandle_function(){$PYTHO/new_mysqpy$1if[$?-ne0];thenreturn0fireturn1}functionmain(){#检查参数if[$#-eq0];thenlocalstart_date=`date-dlast-day+%Y-%m-%d`localend_date=`date-d'$start_date+1day'+%Y-%m-%d`#localend_date=$start_dateelif[$#-eq1];thenlocalstart_date=$1localend_date=`date-d'$start_date+1day'+%Y-%m-%d`#localend_date=$start_dateelif[$#-eq2];thenlocalstart_date=$1localend_date=$2elseecho'Usage:bas/maish2017-05-022017-05-03'exitfiecho'success--yyz--start_date${start_date}'echo'success--yyz--end_date${end_date}'for((i=0;;i++));dodate_str=`date-d'$start_date+$iday'+%Y-%m-%d`date_str_s=`date-d'${date_str}'+%s`end_date_s=`date-d'${end_date}'+%s`echo'success--yyz--date_str${date_str}'echo'success--yyz--end_date_s${end_date_s}'ifhandle_function$date_strthenecho'handlesuccess'elseecho'handlefailed'fiif[$date_str_s-ge$end_date_s];thenbreakfidonereturn0}main$@
运行和测试:
之后需要在本地配置绑定host,这样便于记忆,
运行接口服务器:$pythonserver_new.py*ServingFlaskapp'server_new'(lazyloadin*Environment:productionWARNING:Donotusethedevelopmentserverinaproductionenvironment.UseaproductionWSGIserverinstea*Debugmode:on*Runningonhttp://0.0.0.0:5001/(PressCTRL+Ctoquit)*Restartingwithstat*Debuggerisactive!*DebuggerPIN:264-088-175
测试在浏览器输入以下命令http://yyz.edu.com:5001/index,可以看到如下界面:
测试由于浏览器无法模拟post请求,所以才有postman等模拟工具http://yyz.edu.com:5001/reg?date=2018-12-28&course_id=123456&chapter_id=99999
此外,curl命令是一个利用URL规则在命令行下工作的文件传输工具。它支持文件的上传和下载。curl支持包括HTTP、HTTPS、ftp等众多协议,还支持POST、cookies、认证、从指定偏移处下载部分文件、用户代理字符串、限速、文件大小、进度条等特征。
在进行web后台程序开发测试过程中,常常会需要发送url进行测试,使用curl可以方便地模拟出符合需求的url命令
测试使用curl命令行测试get请求
$curlhttp://yyz.edu.com:5001/index{'msg':'这个是我开发的第一个接口','msg_code':0}
测试使用curl发送POST请求:
$curl-d'date=2018-12-28&course_id=123456&chapter_id=99999'http://yyz.edu.com:5001/reg{'msg':'2018-12-28执行shell成功!','msg_code':0}
这种方法是参数直接在header里面的,如需将输出指定到文件可以通过重定向进行操作.curl-H'Content-Type:application/json'-XPOST-d'jsondata'URL
文章为作者独立观点,不代表观点