我已经使用Flask创建了一个简单的API,我的问题是如何使它列出已分配的所有资源或端点
from flask import Flask, request
from flask_restful import Resource, Api
from sqlalchemy import create_engine
from json import dumps
import os, random
app = Flask(__name__)
api = Api(app)
class cuddle(Resource):
def get(self):
file = random.choice(os.listdir("/path/to/dir/of/images"))
out = "https://example.com/path/" + file
return out
api.add_resource(cuddle, '/api/cuddle')
if __name__ == '__main__':
app.run(host="0.0.0.0", port=33, debug=True)
我希望能够转到example.com/api/endpoints
,并使其列出所有可用的端点,例如代码段cuddle
答案 0 :(得分:2)
您可以使用app.url_map.iter_values()
以下是一个示例
@app.route('/')
def hi():
return 'Hello World!'
@app.route('/hi')
def hi():
return 'Hi!'
@app.route('/hello')
def hello():
return 'Hello World!'
def routes():
routes = []
for route in app.url_map.iter_rules():
routes.append('%s' % route)
print(routes)
['/ hello','/ hi','/']