解析请求参数Python的最佳实践(Flask)

时间:2019-02-22 11:21:11

标签: python python-3.x rest http flask

我的控制器中有下一个功能。py:

@app.route('/api/model/train', methods=['POST'])
def create_train_model():
    """
    Create and train new model.

    """
    args = request.json

    train_booster(arg1 = 100, arg2 = True, arg3 = 'sgd')

    return jsonify(success=True)

而且,如您所见,它具有一些功能(来自service.py),带有3个参数和默认参数。

如何从请求主体参数中获取参数并将其传递给函数? 我找到了解决方案:

class ModelArguments:
    def __init__(self, args):
        self.arg1 = 100
        self.arg2 = True
        self.arg3 = 'sgd'

        self.__dict__.update(args)

@app.route('/api/model/train', methods=['POST'])
def create_train_model():
    """
    Create and train new model.

    """
    model_arguments = ModelArguments(request.json)

    train_booster(arg1 = model_arguments.arg1,
                  arg2 = model_arguments.arg2,
                  arg3 = model_arguments.arg3,)

    return jsonify(success=True)

是否有更好的(或PythonWay或更安全/有用的)实现? 例如,如果我要更改函数train_booster,现在又需要一个参数,我就需要重写项目的每一层!

1 个答案:

答案 0 :(得分:1)

我有一个想法,如下。 service.py

from flask import Flask, request, jsonify

app = Flask("aaa")


def func1(arg1, arg2, arg3):
    print arg1, arg2, arg3


def func2(arg4=1, arg5=2):
    print arg4, arg5


def func3(arg1, arg2, arg3, arg4=1, arg5=1):
    print arg1, arg2, arg3, arg4, arg5


@app.route('/api/model/args_kwargs', methods=['POST'])
def create_train_model():
    """
    Create and train new model.

    """
    args, kwargs = request.json
    func3(*args, **kwargs)

    return jsonify(success=True)

@app.route('/api/model/args', methods=['POST'])
def create_train_2():
    """
    Create and train new model.

    """
    args = request.json
    func1(*args)

    return jsonify(success=True)

@app.route('/api/model/kwargs', methods=['POST'])
def create_train_3():
    """
    Create and train new model.

    """
    kwargs = request.json
    func2(**kwargs)

    return jsonify(success=True)

app.run(host="0.0.0.0", port=9900)

client.py

import requests
import json

def test1():
    resp = requests.post("http://0.0.0.0:9900/api/model/args", json=[12,3,4])
    return None

def test2():
    resp = requests.post("http://0.0.0.0:9900/api/model/kwargs", json={"arg4":234, "arg5":678})
    return None

def test3():
    resp = requests.post("http://0.0.0.0:9900/api/model/args_kwargs", json=([12,3,4], {"arg4":234, "arg5":678}))
    return None


test1()
test2()
test3()