如何使用flaskrestplus为web设计api实现?

2024-09-28 21:55:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我第一次在烧瓶里写restapi

所以现在我有了这样的东西:

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.") })

并在上面的get方法上添加@api.expect(get_userIp)。我被迫传递带有任何值的可选参数(甚至可以从“/getallips”获取所有ip的列表):请参见下面的屏幕截图。在

enter image description here 但是这些选项参数不是设置所有IP所必需的,但是我确实需要使用这些参数来基于ipid或使用get方法的urlmap来获得IP。在

  1. 正在查看由flask_restplus.Api生成的swagger文档

所有端点的get和post,而我只定义了endpoint get和post。所以从技术上讲updateip/username/<username>不应该是getenter image description here

我怎么解决这个问题?在


Tags: tofromimportipapinewdataget
1条回答
网友
1楼 · 发布于 2024-09-28 21:55:28

好问题!您可以通过为每个端点定义单独的Resource子类来解决这两个问题。下面是一个例子,我在这里分割“/getallips”、“/getip/id/”和“/getip/urlmap/”的端点。在

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问题,因为每个端点现在都完全定义了它的接口,所以很容易对它附加一个明确的期望值。您还可以解决“get and post defined for endpoints that not should”,您可以为每个端点决定它应该具有get还是{}。在

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

相关问题 更多 >