简体   繁体   English

Python Flask-restful多个api端点

[英]Python Flask-restful multiple api endpoints

How to check what route has been used? 如何查看已使用的路线?

Using @api with Flask-restful and Python at the moment I'm not doing it in a clean way by checking api.endpoint value. 目前,我无法将@api与Flask-restful和Python结合使用,因此我无法通过检查api.endpoint值来实现整洁。

How do I do it correctly? 如何正确执行?

@api.route('/form', endpoint='form')
@api.route('/data', endpoint='data')
class Foobar(Resource):
    def post(self):
        if api.endpoint == 'api.form':
            print('form')
        elif api.endpoint == 'api.data':
            print('data')

EDIT: 编辑:

Should I split it into two classes? 我应该将其分为两类吗?

I am in no way a professional with flask so please do take my answer with a grain of salt. 我绝对不是专业的烧瓶专家,所以请一言以蔽之。 First of all I would definitely split it into 2 different classes just to have a better overview of what you are doing. 首先,我绝对会将其分为2个不同的类,以更好地概述您的工作。 Also as a rule of thumb I would always split the apis and write its own logic for a higher degree of granularity. 同样,根据经验,我将始终拆分api并编写自己的逻辑以实现更高的粒度。

Second if you want to have a look at https://flask-restful.readthedocs.io/en/latest/api.html#flask_restful.Api.owns_endpoint . 其次,如果您想看看https://flask-restful.readthedocs.io/en/latest/api.html#flask_restful.Api.owns_endpoint This might be of assistance for you. 这可能对您有帮助。

I am new with python and flask. 我是python和flask的新手。

I think something like the following should work for you: 我认为类似以下的内容应该适合您:

from flask import Flask, request
from flask_restful import Api, Resource

app = Flask(__name__)
api = Api(app)


class Data(Resource):
    def post(self):
        print("data")
        return{"type": "data"}


class Form(Resource):
    def post(self):
        print("form")
        return{"type": "form"}


api.add_resource(Form, '/form')
api.add_resource(Data, '/data')

if __name__ == "__main__":
    app.run(port=8080)

Also you have use seperate files for the classes for a cleaner code like: 另外,您还为类使用了单独的文件,以获得更简洁的代码,例如:

form.py 表格

from flask_restful import Resource


class Form(Resource):
    def post(self):
        print("form")
        return{"type": "form"}

data.py data.py

from flask_restful import Resource


class Data(Resource):
    def post(self):
        print("data")
        return{"type": "data"}

services.py services.py

from flask import Flask, request
from flask_restful import Api
from data import Data
from form import Form

app = Flask(__name__)
api = Api(app)


api.add_resource(Form, '/form')
api.add_resource(Data, '/data')

if __name__ == "__main__":
    app.run(port=8080)

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM