簡體   English   中英

在flask API中的flask-restful端點之間進行調用的正確方法是什么?

[英]What is the correct way to make calls among flask-restful endpoints in a flask API?

我正在使用flask-restful設置API REST。 我沒有找到任何文檔,也沒有找到如何在端點之間進行內部調用的示例。 換句話說,我想從其他端點的實現內部使用其中一個端點。

我可以將其視為對另一個API的常規外部調用,但是我覺得我將以某種方式違背良好做法

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

app = Flask(__name__)
api = Api(app, version='1.0', title='FooTitle',
          description='FooDescription', )
ns_conf = api.namespace('FooName', description='FooDescription')


# Endpoint 1
@ns_conf.route('/endpoint1')
class MyResource(Resource):
    def get(self):
        return 'Hello '


# Endpoint 2
@ns_conf.route('/endpoint2')
@api.doc(params={'your_name': 'Your name'})
class greeting(Resource):
    def get(self):
        # Transfer request parameters to variables:
        your_name= request.args.get('your_name')
        # I WOULD LIKE TO GET THE OUTPUT OF ENDPOINT 1 here:
        hello = call_endpoint_1()
        return hello + str(your_name)

實現“ call_endpoint_1()”的正確方法是什么?

很簡單:將公共部分分解為一個普通函數,然后從兩個端點調用它:

def say_hello():
    return "Hello "

@ns_conf.route('/endpoint1')
class MyResource(Resource):
    def get(self):
        return say_hello()


# Endpoint 2
@ns_conf.route('/endpoint2')
@api.doc(params={'your_name': 'Your name'})
class greeting(Resource):
    def get(self):
        # Transfer request parameters to variables:
        your_name= request.args.get('your_name')
        # I WOULD LIKE TO GET THE OUTPUT OF ENDPOINT 1 here:
        hello = say_hello()
        return hello + str(your_name)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM