Python學習筆記十五_開發介面

來源:互聯網
上載者:User

標籤:直接   methods   %s   false   etc   資料庫   select   upper   admin   

1、mock介面,類比一些介面,在別的介面沒有開發好的時候,你需要用它 假的支付介面,類比支付成功

2、

3、查看資料,避免直接操作資料庫flask web開發架構

  1. 執行個體化server
  2. 裝飾器,下面的函數變為一個介面
  3. 啟動服務
import flask,json#__name__代表當前這個python檔案server = flask.Flask(__name__)#執行個體化server,把當前這個python檔案,當做一個服務def my_db(sql):    import pymysql    conn = pymysql.connect(        host=‘127.0.0.1‘, user=‘root‘, passwd=‘123456‘,        port=3306, db=‘data‘, charset=‘utf8‘)    cur = conn.cursor() #建立遊標    cur.execute(sql)#執行sql    if sql.strip()[:6].upper()==‘SELECT‘:        res =  cur.fetchall()    else:        conn.commit()        res = ‘ok‘    cur.close()    conn.close()    return res@server.route(‘/index‘,methods=[‘get‘])#裝飾器,下面的函數變為一個介面#method預設只有get,methods=[‘get‘,‘post‘]def index():    res = {‘msg‘:‘這是我開發的第一個介面‘,‘msg_code‘:0}    # 返回狀態代碼0,表示返回成功    return json.dumps(res,ensure_ascii=False)    #json.dumps 序列化時對中文預設使用的ascii編碼.想輸出真正的中文需要指定ensure_ascii=False@server.route(‘/reg‘,methods=[‘post‘])#/reg介面路徑def ref():    username = flask.request.values.get(‘username‘)#username是介面調用的key,即入參    pwd = flask.request.values.get(‘passwd‘)#passwd是介面調用的key,即入參    if username and pwd:        sql = ‘select * from my_user where username = "%s";‘ % username        if my_db(sql):            res = {‘msg‘: ‘使用者已存在‘, ‘msg_code‘: 2001}            # 2001,以2開頭都是跟使用者有關的        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=7788,debug=True)

 

Python學習筆記十五_開發介面

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.