開發接口(1)
接口開發作用:
1、mock接口,模擬一些接口,在別的接口沒有開發好的時候,你需要用它
2、基本了解數據如何來源等
3、查看數據,方便第三方查看 也避免直接操作數據庫
import flask,json #flask是接口開發所需的一個輕量級web開發框架
# __name__,代表當前這個python文件
server = flask.Flask(__name__) #把咱們當前這個python文件,當做一個服務 接口相當於服務端的一些服務
def my_db(sql):
import pymysql
coon = pymysql.connect(
host=‘XXX‘, user=‘jxz‘, passwd=‘123456‘,
port=3306, db=‘jxz‘, charset=‘utf8‘)
cur = coon.cursor() #建立遊標
cur.execute(sql)#執行sql
if sql.strip()[:6].upper()==‘SELECT‘:
res = cur.fetchall()
else:
coon.commit()
res = ‘ok‘
cur.close()
coon.close()
return res
接口列子:
@server.route(‘/index‘,methods=[‘get‘]) #裝飾器 接口函數寫要求
def index():
res = {‘msg‘:‘這是我開發的第一個接口‘,‘msg_code‘:0} #這是個字典
return json.dumps(res,ensure_ascii=False) #json串編碼問題
server.run(port=7777,debug=True,host=‘0.0.0.0‘) #debug=True,改了代碼之後,不用重啟它會自動幫你重啟 默認5000 保證只有一個在運行
接口練習,寫一個註冊接口
@server.route(‘/reg‘,methods=[‘post‘]) #可以不寫 默認get請求
def reg():
username = flask.request.values.get(‘username‘)#用戶所用發過來的數據放入cookie等字典中使用這個方法獲取
pwd = flask.request.values.get(‘passwd‘)
print(‘username..‘,username)
if username and pwd:
sql = ‘select * from my_user where username="%s";‘%username
# res = my_db(sql)
if my_db(sql):
res = {‘msg‘:‘用戶已存在‘,‘msg_code‘:2001}
else:
insert_sql = ‘insert into my_user (username,passwd,is_admin) values ("%s","%s",0);‘%(username,pwd)
my_db(insert_sql)
res = {‘msg‘:‘註冊成功!‘,‘msg_code‘:0}
else:
res = {‘msg‘:‘必填字段未填,請查看接口文檔!‘,‘msg_code‘:1001}
# 1001必填字段未填
return json.dumps(res,ensure_ascii=False)
server.run(port=7777,debug=True,host=‘0.0.0.0‘) #debug=True,改了代碼之後,不用重啟它會自動幫你重啟 默認5000
# host=0.0.0.0表示別人訪問的時候,用你的ip就可以訪問了。
# 127.0.0.1 本機ip
# 192.168.
#腳本
開發接口(1)