@Kostas Pelelis 答案的旁注/补充(抱歉目前无法发表评论):
对于所有想知道如何集成端点路由的方法的人:查看 app.add_url_rule 的函数描述。
如上所述,您可以使用“methods”参数来更改默认的“GET”方法。
Kostas Pelelis 代码更改为“POST”类型的方法如下所示:
(集成方法的示例 + 端点类返回您的操作函数返回的任何内容 [例如 html]
from flask import Flask, Response, render_template
class EndpointAction(object):
def __init__(self, action):
self.action = action
self.response = Response(status=200, headers={})
def __call__(self, *args):
response = self.action()
if response != None:
return response
else
return self.response
class FlaskAppWrapper(object):
app = None
def __init__(self, name):
self.app = Flask(name)
def run(self):
self.app.run()
def add_endpoint(self, endpoint=None, endpoint_name=None, handler=None, t_methods=None):
self.app.add_url_rule(endpoint, endpoint_name, EndpointAction(handler), methods=t_methods)
def action():
# Execute anything
print('i did something')
def returning_action():
# Returning for example an index hello world page
return render_template('index.html')
a = FlaskAppWrapper('wrap')
a.add_endpoint(endpoint='/ad', endpoint_name='ad', handler=action, req_methods=['POST'])
#just a little addition for handling of a returning actionhandler method
#-> i added another endpoint but for a returning method
a.add_endpoint(endpoint='/', endpoint_name='index_page', handler=returning_action, req_methods=['GET']
a.run()
虽然 templates/index.html 可能看起来像这样(注意 render_templates 需要一个模板文件夹与您的 py 文件位于同一位置,其中包含指定的 html):
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index Page</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
当索引路由 'ip-address-of-the-webapp/' 被访问(通过通常的浏览器访问 -> GET 请求)时,会调用此索引页面添加。
*编辑:显示如果你的动作方法有参数(例如来自路由参数)的样子,这里是端点类和动作类的更新版本
class EndpointAction(object):
def __init__(self, action):
self.action = action
self.response = Response(status=200, headers={})
def __call__(self, *args, **kwargs):
response = self.action(**kwargs)
if response != None:
return response
else
return self.response
def param_action(param):
# Execute something (print param)
print(f'i did {param}')
[...]
a.add_endpoint(endpoint='/<param>', endpoint_name='parametric_action', handler=param_action, req_methods=['GET']
[...]