歡迎您光臨本站 註冊首頁

Python接口開發實現步驟詳解

←手機掃碼閱讀     火星人 @ 2020-04-28 , reply:0

一、操作步驟



二、源碼舉例

#!/usr/bin/python3

# encoding:utf-8 import flask,json

# 實例化api,把當前這個python文件當作一個服務,__name__代表當前這個python文件 api = flask.Flask(__name__)

# 'index'是接口路徑,methods不寫,默認get請求 @api.route('/index',methods=['get']) # get方式訪問 def index(): ren = {'msg':'成功訪問首頁','msg_code':200} #json.dumps 序列化時對中文默認使用的ascii編碼.想輸出中文需要指定ensure_ascii=False return json.dumps(ren,ensure_ascii=False)

#post入參訪問方式一:

url格式參數 @api.route('/article',methods=['post']) def article(): #url格式參數?id=12589&name='lishi' id = flask.request.args.get('id') if id: if id == '12589': ren = {'msg':'成功訪問文章','msg_code':200} else: ren = {'msg':'找不到文章','msg_code':400} else: ren = {'msg':'請輸入文章id參數','msg_code':-1} return json.dumps(ren,ensure_ascii=False) #post入參訪問方式二:from-data(k-v)格式參數 @api.route('/login',methods=['post']) def login(): #from-data格式參數 usrname = flask.request.values.get('usrname') pwd = flask.request.values.get('pwd') if usrname and pwd: if usrname =='test' and pwd =='123456': ren = {'msg':'登錄成功','msg_code':200} else: ren = {'msg':'用戶名或密碼錯誤','msg_code':-1} else: ren = {'msg':'用戶名或密碼為空','msg_code':1001} return json.dumps(ren,ensure_ascii=False) #post入參訪問方式二:josn格式參數 @api.route('/loginjosn',methods=['post']) def loginjosn(): #from-data格式參數 usrname = flask.request.json.get('usrname') pwd = flask.request.json.get('pwd') if usrname and pwd: if usrname =='test' and pwd =='123456': ren = {'msg':'登錄成功','msg_code':200} else: ren = {'msg':'用戶名或密碼錯誤','msg_code':-1} else: ren = {'msg':'用戶名或密碼為空','msg_code':1001} return json.dumps(ren,ensure_ascii=False) if __name__ == '__main__': api.run(port=8888,debug=True,host='127.0.0.1') # 啟動服務 # debug=True,改了代碼後,不用重啟,它會自動重啟 # 'host='127.0.0.1'別IP訪問地址


[火星人 ] Python接口開發實現步驟詳解已經有249次圍觀

http://coctec.com/docs/python/shhow-post-231953.html