Flask:使用" add_url_rule"对于相同的终点,使用两个GET url的defaults参数

时间:2018-06-01 18:22:38

标签: python flask

我正在使用烧瓶蓝图,我在这里添加网址&#34; add_url_rule&#34;方法。 我的要求是我想使用GET方法创建</pets>/pets<int:pet_id>之类的网址。

  • </pets>: - 返回所有宠物的清单。
  • </pets/<int:pet_id>:返回特定的宠物详情。

这是代码段:

    from flask import Blueprint
    from pet.api import PetAPI

    pet_app=Blueprint('pet_app',__name__)

    pet_app.add_url_rule('/pets',view_func = PetAPI.as_view('pets'),methods= 
          ['GET'],defaults={'pet_id': None})
    pet_app.add_url_rule('/pets/<int:pet_id>',view_func =       PetAPI.as_view('pets'),methods=['GET','POST'])

这是注册码:

from flask import Flask
from flask import Blueprint
app= Flask(__name__)
app.config.from_pyfile('setting.py')

def create_app():

        # DB intialize
        from db import DB
        DB.init_app(app)

        # import blueprint

        from pet.views import pet_app

        #register Blueprint

        app.register_blueprint(pet_app)

        return app

if __name__=="__main__":
  create_app().run(port=5000)

当我运行时,我得到以下错误:

File "app.py", line 27, in <module>
    create_app().run(port=5000)
  File "app.py", line 22, in create_app
    app.register_blueprint(pet_app)
  File "E:\FlaskApp\FlaskRestFUl\section6\venv\lib\site-packages\flask\app.py",
line 65, in wrapper_func
    return f(self, *args, **kwargs)
  File "E:\FlaskApp\FlaskRestFUl\section6\venv\lib\site-packages\flask\app.py",
line 968, in register_blueprint
    blueprint.register(self, options, first_registration)
  File "E:\FlaskApp\FlaskRestFUl\section6\venv\lib\site-packages\flask\blueprint
s.py", line 154, in register
    deferred(state)
  File "E:\FlaskApp\FlaskRestFUl\section6\venv\lib\site-packages\flask\blueprint
s.py", line 173, in <lambda>
    s.add_url_rule(rule, endpoint, view_func, **options))
  File "E:\FlaskApp\FlaskRestFUl\section6\venv\lib\site-packages\flask\blueprint
s.py", line 76, in add_url_rule
    view_func, defaults=defaults, **options)
  File "E:\FlaskApp\FlaskRestFUl\section6\venv\lib\site-packages\flask\app.py",
line 65, in wrapper_func
    return f(self, *args, **kwargs)
  File "E:\FlaskApp\FlaskRestFUl\section6\venv\lib\site-packages\flask\app.py",
line 1068, in add_url_rule
    'existing endpoint function: %s' % endpoint)
AssertionError: View function mapping is overwriting an existing endpoint functi
on: pet_app.pets

如果我将以上网址缩减为以下网址:

pet_app.add_url_rule('/pets/<int:pet_id>',view_func = PetAPI.as_view('pets'),defaults={'pet_id': None},methods=['GET','POST'])

我的本​​地服务器启动并提供输出:

for URL:  http://127.0.0.1:5000/pets/  :- output= Not found URL.
for URL:   http://127.0.0.1:5000/pets/1 :- output:
{
     "pets_list": [
        {
      "id": 1, 
      "name": "Vinod"
       }, 
       {
      "id": 2, 
      "name": "Alok"
       }
      ]
      }

在第二个网址中,它会显示所有宠物的列表(考虑到pet_id的默认值=无,但我们以pet_id = 1的形式传递)。

这里是端点代码段:

from flask.views import MethodView
from flask import jsonify,request,abort


class PetAPI(MethodView):

    PETS=[
          {'id':1 ,'name': "Vinod"},
          {'id':2 ,'name':"Alok"}
    ]

    @classmethod
    def get(cls,pet_id):
        if pet_id:
            for pet in cls.PETS:
                if pet_id==pet.key():
                    return jsonify({"pet detail": pet})
            return jsonif({"msg":"Pet {0} not found".format(pet_id)})
        else:
            return jsonify({'pets_list':cls.PETS})

欲望输出应该是:

for URL:  http://127.0.0.1:5000/pets/  :- output= List of all pets.
for URL:   http://127.0.0.1:5000/pets/1 :- output= details of one pet with pet_id==1.

我尝试使用烧瓶0.11和1.0版本。

请帮忙。

0 个答案:

没有答案