简体   繁体   English

从 Flask 调用任意 Python 函数的更优雅的方式

[英]More elegant way to call arbitrary Python functions from Flask

Setting up a Flask REST API is easy.设置Flask REST API很容易。 I use the following approach:我使用以下方法:

from flask import Flask
from flask_cors import CORS

from utility import *

app = Flask(__name__)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})

@app.after_request
def add_headers(response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Headers'] =  "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
    response.headers['Access-Control-Allow-Methods']=  "POST, GET, PUT, DELETE, OPTIONS"
    return response

@app.route("/", methods=["GET"])
def call_function():
    res = request_return()
    return(res)

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)

In this example I import functions sitting inside utility.py:在此示例中,我导入位于 utility.py 中的函数:

from flask import request, jsonify

def my_function(arg):
    return(arg)

def string_to_number(str):
    if("." in str):
        try:
            res = float(str)
        except:
            res = str
    elif(str.isdigit()):
        res = int(str)
    else:
        res = str
    return(res)

def request_return():
    passed_function = request.args.get('function')
    args = dict(request.args)
    values = list(args.values())[1:]
    values = list(map(string_to_number, values))
    res = globals()[passed_function](*tuple(values))
    return(jsonify(res))

This allows me to pass any function name as an argument and get the result back.这允许我将任何 function 名称作为参数传递并返回结果。 So if I ran the following in my browser:因此,如果我在浏览器中运行以下命令:

https:localhost:5000/?function=my_function&args=hello

I would see:我会看见:

"hello"

The way I process the request is quite bloated.我处理请求的方式非常臃肿。 You can see in request_return that I must take a series of steps to move from the function name to its execution and return.您可以在request_return中看到,我必须采取一系列步骤才能从 function 名称移动到它的执行并返回。 I also use a string_to_number function to handle any numbers that might be passed.我还使用 string_to_number function 来处理可能传递的任何数字。 This ensures I can call any function inside utility AND any number of parameters to that function .这确保我可以在实用程序内部调用任何 function 以及对该 function 的任意数量的参数

Any Flask tutorial I've seen doesn't discuss how to call arbitrary functions like this.我见过的任何 Flask 教程都没有讨论如何调用这样的任意函数。 Is there a more elegant way to handle this?有没有更优雅的方法来处理这个? Specifically, without all the bloat in my request_return function.具体来说,没有我的 request_return function 中的所有膨胀。

Allowing the client to call any global function is dangerous, they could call open() to overwrite a file.允许客户端调用任何全局 function 是危险的,他们可以调用open()来覆盖文件。

Create a dictionary of the operations that should be callable in your application.创建应在您的应用程序中可调用的操作的字典。

And rather than trying to convert numbers automatically, let the individual functions decide how they want to parse their args.与其尝试自动转换数字,不如让各个函数决定他们想要如何解析他们的参数。

my_operations = {'my_function': my_function, ...}

def request_return():
    passed_function = request.args.get('function')
    try:
        args = dict(request.args)
        del args['function'] # This is processed above
        res = my_operations[passed_function](**args)
        return(jsonify(res))
    except:
        # report error to caller

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

相关问题 通过键调用函数的更优雅的方式? - more elegant way to call functions by key? Python:为方法调用添加可选参数的更优雅方式 - Python: More elegant way to add optional parameters to method call 此python装饰器的一种更优雅的方式 - A more elegant way for this python decorator 有没有更优雅的方式在Python中编写它? - Is there a more elegant way to write this in Python? Python,如何以最优雅的方式将任意变量从 function 传递给 function? - Python, how to pass arbitrary variables from function to function in the most elegant way? 在Python中以任意块分割矩阵(或数组)的绝佳方法 - Elegant way to split a matrix (or array) at arbitrary chunk in Python Python 2中具有任意长度列表的.format()格式化字符串的最优雅方法? - Most elegant way to .format() formatted string with arbitrary length list in Python 2? 在Python 3中复制属性的更优雅方法 - More elegant way to copy properties in Python 3 有没有一种更优雅的方法可以在 python 中通过替换获得排列? - Is there a more elegant way of getting permutations with replacement in python? 更优雅的方式做到这一点? 2、3或4的python倍数 - more elegant way to do this? python multiples of 2, 3 or 4
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM