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?xxx
def 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","%s",0);'%(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',別人可以訪問

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM