如何使用flask restplus设计web的api实现?

时间:2018-02-15 08:00:07

标签: python flask swagger flask-restplus

我是第一次在烧瓶中写REST api,

所以现在我有这样的事情:

import uuid
import pytz
from datetime import datetime
from flask_restplus import Resource, Api, fields
from ..models import publicip_schema

from ..controller import (
    jsonified,
    get_user_ip,
    add_new_userIp,
    get_specificIp,
    get_all_publicIp
    )

from flask import request, jsonify

from src import app
from src import db
from src import models

api = Api(app, endpoint="/api", versio="0.0.1", title="Capture API", description="Capture API to get, modify or delete system services")

add_userIp = api.model("Ip", {"ip": fields.String("An IP address.")})
get_userIp = api.model("userIp", {
    "ipid": fields.String("ID of an ip address."), 
    "urlmap" : fields.String("URL mapped to ip address.")
    })

class CaptureApi(Resource):

    # decorator = ["jwt_required()"]

    # @jwt_required()
    @api.expect(get_userIp)
    def get(self, ipid=None, urlmap=None):
        """
           this function handles request to provide all or specific ip
        :return:
        """
        # handle request to get detail of site with specific location id.
        if ipid:
            ipobj = get_user_ip({"id": ipid})
            return jsonified(ipobj)

        # handle request to get detail of site based on  site abbreviation
        if urlmap:
            locate = get_user_ip({"urlmap": urlmap})
            return jsonified(locate)

        return jsonify(get_all_publicIp())

    # @jwt_required()
    @api.expect(add_userIp)
    def post(self, username=None):
        """
            Add a new location.
            URI /location/add
        :return: json response of newly added location
        """
        data = request.get_json(force=True)
        if not data:
            return jsonify({"status": "no data passed"}), 200

        if not data["ip"]:
            return jsonify({"status" : "please pass the new ip you want to update"})

        if get_user_ip({"ipaddress": data["ip"]}):
                return jsonify({"status": "IP: {} is already registered.".format(data["ip"])})

        _capIpObj = get_user_ip({"user_name": username})

        if _capIpObj:
            # update existing ip address
            if "ip" in data:
                if _capIpObj.ipaddress == data["ip"]:
                    return jsonify({"status": "nothing to update."}), 200
                else:
                    _capIpObj.ipaddress = data["ip"]
            else:
                return jsonify({
                    "status" : "please pass the new ip you want to update"
                    })

            db.session.commit()
            return jsonified(_capIpObj)
        else:
            device = ""
            service = ""
            ipaddress = data["ip"]
            if "port" in data:
                port = data["port"]
            else:
                port = 80
            if "device" in data:
                device = data["device"]
            if "service" in data:
                service = data["service"]
            date_modified = datetime.now(tz=pytz.timezone('UTC'))
            urlmap = str(uuid.uuid4().get_hex().upper()[0:8])    
            new_public_ip = add_new_userIp(username, ipaddress, port, urlmap, device, service, date_modified)
            return publicip_schema.jsonify(new_public_ip)


api.add_resource(
    CaptureApi,
    "/getallips",  # GET
    "/getip/id/<ipid>",  # GET
    "/getip/urlmap/<urlmap>",  # GET
    "/updateip/username/<username>" # POST
                 )

我遇到了两个问题

  1. 如果我指定

    get_userIp = api.model("userIp", { "ipid": fields.String("ID of an ip address."), "urlmap" : fields.String("URL mapped to ip address.") })

  2. 并在上面的get方法中添加@api.expect(get_userIp)。我被迫传递任意值的可选参数(甚至可以获取所有ip的列表,即来自&#34; / getallips&#34;):见下面的截图。

    enter image description here 但是这些选项参数并不需要使用所有IP,但我确实需要使用这些参数来基于ipidurlmap使用get方法获取IP。

    1. 查看由我flask_restplus.Api生成的招摇文档
    2. 获取和发布所有端点,而我已经定义了端点get和post。因此技术上updateip/username/<username>不应列出get enter image description here

      我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

好问题!您可以通过为每个端点定义单独的Resource子类来解决这两个问题。下面是一个示例,我将端点分为&#34; / getallips&#34;,&#34; / getip / id /&#34;和&#34; / getip / urlmap /&#34;。< / p>

Ip = api.model("Ip", {"ip": fields.String("An IP address.")})
Urlmap = api.model("UrlMap", {"urlmap": fields.String("URL mapped to ip address.")})

@api.route("/getallips")
class IpList(Resource):
    def get(self):
        return jsonify(get_all_publicIp())

@api.route("/getip/id/<ipid>")
class IpById(Resource):
    @api.expect(Ip)
    def get(self, ipid):
        ipobj = get_user_ip({"id": ipid})
        return jsonified(ipobj)

@api.route("/getip/urlmap/<urlmap>")
class IpByUrlmap(Resource):
    @api.expect(Urlmap)
    def get(self, urlmap):
        ipobj = get_user_ip({"id": ipid})
        return jsonified(ipobj)

请注意,您可以免费解决expect问题 - 因为现在每个端点都完全定义了它的界面,因此很容易为其提供明确的期望。您还可以解决为不应该使用的端点定义的&#34; get和post;您可以为每个端点决定是否应该有getpost

由于个人喜好,我使用api.route装饰器而不是为每个班级调用api.add_resource。您可以通过为每个新的api.add_resource(<resource subclass>, <endpoint>)子类调用Resource来获得相同的行为(例如api.add_resource(IpList, "/getallips")