python實現自定義接口


一、開發接口的作用

  1、mock 服務:在別的接口沒有開發完成的時候可以模擬一些接口以便測試已經開發完成的接口,例如假的支付接口,模擬支付成功、支付失敗。

  2、了解接口是如何實現的:數據交互、數據返回

  3、開發給別人查看數據,避免其他人直接操作、查看數據庫

 

二、 flask

flask是一個python編寫的輕量級框架,可以使用它實現一個網站或者web服務。本文就用flask來開發一個接口。

flask需要先安裝再引用。pip install flask

用flask開發接口的流程為:

1、定義一個server

server=flask.Flask(__name__) #__name__代表當前的python文件。把當前的python文件當做一個服務啟動

2、然后定義接口函數,一般函數和接口函數的區別在於,定義為接口的函數上方要特別加上裝飾器:

@server.route('/index',methods=['get','post']) #第一個參數就是路徑,第二個參數支持的請求方式,不寫的話默認是get,也可以指定一個

@server.route('/index',methods=['get','post'])#第一個參數就是路徑,第二個參數支持的請求方式,不寫的話默認是get
def index():
    res={'msg':'這是我開發的第一個接口','msg_code':0}
    return json.dumps(res,ensure_ascii=False)#轉成字符串類型

 

三、接口開發的步驟

  1、實例化server

  2、將裝飾器下面的函數變為一個接口

  3、啟動服務

 

  簡單的接口開發示例:

import flask,json
server = flask.Flask(__name__)           # 實例化server,把當前這個python文件當作一個服務,__name__代表當前這個python文件
@server.route('/index',methods=['get'])  # 'index'是接口路徑,如methods不寫,則默認get請求
# 裝飾器,下面的函數變為一個接口
def index():
    res = {'msg':'這是我開發的第一個接口','msg_code':'0000'}
    return json.dumps(res,ensure_ascii=False)
    # json.dumps 序列化時對中文默認使用的ascii編碼.想輸出真正的中文需要指定ensure_ascii=False

server.run(port=8888,debug=True,host='0.0.0.0')  # 啟動服務;端口不寫默認是5000,也可以自定義,但注意不要與機器上已占用的port起沖突,
# debug=True,改了代碼后,不用重啟,它會自動加載重啟
# 'host='0.0.0.0'同一局域網下,別人可以通過IP訪問
# 最終這個接口的訪問地址就是  http://127.0.0.1/index  ,get方法。返回數據是json格式res內容

接口訪問中,經常會需要輸入參數。那么如果要接受傳入的參數,則可用以下方法:

  username=flask.request.values.get('username')

  示例:開發一個登錄接口

import flask
import tools #自己寫的py,里面寫了一些下面需要調用的函數
import json
server = flask.Flask(__name__)
#新建一個服務,把當前這個python文件當做一個服務

#開發一個登錄接口
@server.route('/login',methods=['get'])
def login():
    uname = flask.request.values.get('username')
    pd = flask.request.values.get('passwd')
    sql = 'select * from app_myuser where username="%s"'%uname
    res = tools.my_db(sql) #tools里的函數:連接數據庫,執行sql並返回結果
    if res:
        if tools.my_md5(pd) == res.get('passwd'): #tools里的函數,加密密碼
            res = {"code":0,"msg":"登錄成功!"}
        else:
            res = {"code":1,"msg":"密碼錯誤!"}
    else:
        res = {'code':2,"msg":"用戶不存在"}
    return json.dumps(res,ensure_ascii=False,indent=4) #輸出json格式

server.run(host='127.0.0.1',port=8998,debug=True)#若別人訪問這個接口,則host需要輸入自己的ip地址,而不是127.0.0.1

#以上接口訪問地址即:http://127.0.0.1:8998/login?username=usertest&passwd=123123

tools里面封裝的函數如下:

import pymysql  #連接數據庫,執行sql並返回sql執行結果
def my_db(sql):
    conn = pymysql.connect(host='127.0.0.1',user='xxx',password='123456',
                    db='db1',port=3306,charset='utf8',autocommit=True)
    cur = conn.cursor(pymysql.cursors.DictCursor)
    cur.execute(sql)
    res = cur.fetchone() #{'username':'test'}  {}
    cur.close()
    conn.close()
    return res

import hashlib
def my_md5(s,salt=''): #md5加密
    s = s+salt
    news = str(s).encode()
    m = hashlib.md5(news)
    return m.hexdigest()

if __name__ == '__main__':
    #判斷如果是在別的文件里面導入這個python文件的話,就不執行下面的代碼
    print(strTotimestamp())
    print(clean_log('.'))
    print(clean_log('.',2))

 


免責聲明!

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



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