您好,欢迎来到筏尚旅游网。
搜索
您的当前位置:首页python简单开发接口

python简单开发接口

来源:筏尚旅游网
python简单开发接⼝

1、⾸先需要安装flask这个模块:pip install flask。flask是个轻量级的接⼝开发框架2、开发接⼝有什么作⽤

  1、mock接⼝,模拟⼀些接⼝,在别的接⼝没有开发好的时候,需要⽤mock去模拟⼀些接⼝。  2、知道接⼝是怎么开发的,了解接⼝怎么测试  3、查看数据

温馨提⽰:如果在pycharm设置了环境变量,另外⼀个接⼝再次需要设置环境变量时,需要把之前的环境变量去掉先

import flask,json# print(__name__)

server=flask.Flask(__name__) #__name__代表当前的python⽂件,把当前这个python⽂件,当成⼀个服务def my_db(sql): import pymysql

coon = pymysql.connect(host='xx.xx.xx.xx',user='jxz',passwd='123456',port=3306,db='jxz',charset='utf8') cur = coon.cursor() cur.execute(sql)

if sql.strip()[:6].upper() == 'SELECT': #判断sql语句是否select开头 res = cur.fetchall() #获取到sql语句所有的返回结果 else:

coon.commit() res = 'ok' cur.close() coon.close() return res

@server.route('/index',methods=['get']) #装饰器 ip:8080/index?xxxdef index():

res={'msg':'这个是我开发的第⼀个接⼝','msg_code':0} #这个是字典,接⼝返回的是json,所以需要引⼊json,并且返回进⾏json.dumps return json.dumps(res,ensure_ascii=False) #返回结果是unicode,需要增加ensure_ascii=False@server.route('/reg',methods=['post'])def reg():

username = flask.request.values.get('username') pwd = flask.request.values.get('passwd') if username and pwd:

sql = 'select * from my_user WHERE username=\"%s\";'%username if my_db(sql):

res = {'msg':'⽤户已存在!','msg_code':2001} else:

insert_sql='insert into my_user(username,passwd,is_admin)values(\"%s\%(username,pwd) my_db(insert_sql)

res = {'msg':'注册成功!','msg_code':0} else:

res = {'msg':'必填字段未填,请检查接⼝⽂档!','msg_code':1001} return json.dumps(res,ensure_ascii=False)

server.run(port=7777,debug=True,host='0.0.0.0') #端⼝号要是不指定,默认为5000.debug=True,改了代码之后不⽤重启,会⾃动重启⼀次。后⾯增加host='0.0.0.0',别⼈可以访问

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- efsc.cn 版权所有 赣ICP备2024042792号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务