11. 接口開發--注冊接口


注冊接口

import flask,json
def my_db(sql):
    import pymysql
    coon = pymysql.connect(
    host='xxx.xx.x.xx', user='xxx', passwd='123456',
    port=3306, db='xxx', 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
#__name__,表示當前這個python文件
server = flask.Flask(__name__)  #把當前這個python文件,當作一個服務。
@server.route('/index',methods=['get'])     #裝飾器,index()就不是一個普通的函數了
    #methods不寫,默認get請求,根據情況要get還是post還是都要
def index():
    res = {'msg':'這是我開發的一個接口','msg_code':100}
    return json.dumps(res,ensure_ascii=False)   #

@server.route('/reg',methods=['get','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}  #1001必填字段未填
    return json.dumps(res,ensure_ascii=False)

#serve.run要寫到最下方,否則接口不能啟動到。
server.run(port =7777,debug=True)  #debug=True,表示改了代碼之后,不用重啟,它會自動幫你重啟一次
#默認端口號是5000,

# server.run(port =7777,debug=True,host='0.0.0.0')
#指定host='0.0.0.0',同一個局域網內,別人訪問我的ip地址就可以訪問到

  

 


免責聲明!

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



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