python:微型微服務框架bottle實踐

1 背景

在公司跑FT,需要一些樁服務來配合整個測試流程,樁服務本身沒啥處理邏輯,唯一的要求就是寫起來方便的,能快速開發。
發現了Bottle這個框架,感覺還可以,把第一次使用的代碼實踐貼出來

2 代碼實踐

資源接口類MyWeb.py,定義了資源接口,代碼時python2的代碼,和3語法略有不同!

# coding: utf-8
import json
import logging
import os

from bottle import get, run, post, request, response, put

class MyWeb(object):
    excepted_return = "success"
    base_url = "/api/MyWeb/v1"
    test_url = base_url + "/test"
    set_response_url = base_url + "/set_response"
    send_motep_url = base_url + "/channel"

    @staticmethod
    @post(send_motep_url)
    def send_json_body():
        response.content_type = 'application/json'
        return MyWeb.excepted_return

    @staticmethod
    @put(set_response_url)
    def set_response():
        response.content_type = 'application/json'
        body = request.json  # request對象裏的,json屬性,是字典類型
        if body is None:
            return {'code': 1, 'message': 'body param is null'}
        if type(body) is not dict:
            return {'code': 1, 'message': 'body param is not dict'}
        MyWeb.excepted_return = body
        # 返回值既可以直接發送字典類型對象,框架支持自動轉換
        # 也可以用json.dumpes(object)轉成字符串發送,客戶端收到的是完全相同的
        return {"code": 0, "message": "success"}

    @staticmethod
    @get(test_url)
    def check_connection():
        response.content_type = 'application/json'
        return {"code": 0, "message": {"excepted_return": MyWeb.excepted_return}}

服務啓動類,Main.py

# coding=utf-8

import json
import logging
import os

from bottle import get, run, post, request, response

import MyWeb # 必須顯式導入,才能使用該類中定義好的資源接口

if __name__ == '__main__':
    logging.info("start pa-tcp-rnc fake service")
    run(host='0.0.0.0', port=8087, debug=True)

使用:python Main.py,即可啓動微服務,使用可使用postman對上面定義好的接口進行使用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章