【Python】學習筆記5-利用flask來mock介面

來源:互聯網
上載者:User

標籤:mys   支援   ...   file   利用   nbsp   imp   __name__   參數   

# 1、mock介面
# import flask #python的輕量級的開發架構
# # 介面,後台服務的開發
# # 在瀏覽器運行http://127.0.0.1:8080/get_user即可,或者其他提供者的方式
# server = flask.Flask(__name__) #__name__當前檔案名稱,把咱們這個app python當做一個server
# @server.route(‘/get_user‘,methods=[‘get‘,‘post‘]) #將下面函數變成一個介面
# def get_all_user():
# return ‘cm的介面‘ #return只能返回字串
# #啟動服務,加debug自動幫忙重啟
# server.run(port = 8080,debug = True)


# 2、調用自己的模組,串連資料庫,瀏覽器請求介面
# import tools #使用時,需要用tools.op_mysql()
from lib.tools import op_mysql #使用時,直接用op_mysql()
# 以上兩種方式都可以

3、寫介面前先要形成標準的目錄結構,分解一下各個目錄的檔案

  4、start.py啟動並執行啟動程式,在這裡啟動 服務

 1 #這是程式的入口檔案,將啟動服務的命令放裡面 2  3 #增加根目錄為環境變數,方便底層目錄執行時目錄錯誤 4 import sys,os 5 BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #取到api目錄,根目錄 6 sys.path.insert(0,BASE_PATH) 7  8 #加環境變數才能匯入,否則匯入會異常 9 from lib.main  import server10 server.run(port = 8080,host = ‘0.0.0.0‘,debug = True) #預設連接埠號碼是500011 #host = ‘0.0.0.0‘ 代表區域網路內別人都可以通ip訪問自己的介面

5、setting 設定常規變數等

1 MYSQL_HOST = ‘X.X.X.X‘2 PASSWORD = ‘123456‘3 PORT = 33064 USER = ‘jxz‘5 DB = ‘jxz‘

6、main.py......自己的主程式

 1 # import tools #使用時,需要用tools.op_mysql() 2 from lib.tools import op_mysql  #使用時,直接用op_mysql() 3 # 以上兩種方式都可以 4  5 import flask,json #python的輕量級的開發架構 6 # 介面,後台服務的開發 7 # 在瀏覽器運行http://127.0.0.1:8080/get_user即可,或者其他提供者的方式 8 server = flask.Flask(__name__) #__name__當前檔案名稱,把咱們這個app python當做一個server 9 10 11   #瀏覽器輸出bt_stu表中前5條的資料12 @server.route(‘/get_user‘,methods=[‘get‘,‘post‘]) #將下面函數變成一個介面13 def get_all_user():14     sql = ‘select * from bt_stu limit 5;‘15     res = op_mysql(sql = sql)16     response = json.dumps(res,ensure_ascii=False)17     return response #return只能返回字串18 19 20 # 瀏覽器輸入使用者id、姓名,插入資料到資料庫stu表,21 @server.route(‘/add_user‘,methods=[‘post‘]) #代碼支援什麼類型的介面22 def add_user():23     user_id = flask.request.values.get(‘id‘)24     user_name = flask.request.values.get(‘u‘)25     sql = "insert into stu values (‘%s‘,‘%s‘);"%(user_id,user_name)26     if user_id and user_name:27         res = op_mysql(sql = sql)28         response = {"code":"308","message":"success"}29     else:30         response = {"code":"503","message":"參數不可為空"}31     return json.dumps(response,ensure_ascii=False) #return只能返回字串

7、tools工具類檔案,相關的函數在這裡面

 1 import pymysql 2 from conf import setting 3  4 # 1、操作mysql 5 def op_mysql(sql): 6     conn = pymysql.connect(host=setting.MYSQL_HOST,user= setting.USER, 7                            password=setting.PASSWORD, 8                            port=setting.PORT, 9                            charset = ‘utf8‘,10                            db = setting.DB)11     cur = conn.cursor(cursor=pymysql.cursors.DictCursor)12     #判斷是否需要commit,根據select update delete insert的類型13     cur.execute(sql)14     sql_start = sql[:6].upper()# select不區分大小寫,取前6位轉換成大寫15     if sql_start == ‘SELECT‘:16         res = cur.fetchall()17     else:18         conn.commit()19         res = ‘ok‘20     cur.close()21     conn.close()22     return res

【Python】學習筆記5-利用flask來mock介面

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.