将烧瓶嵌入带有装饰器的类中

时间:2018-10-21 11:06:37

标签: python flask

我正试图在一个类中使用一个烧瓶,但是我想使用装饰器

我看过这个主题 Using flask inside class

但是到目前为止,到目前为止还不错,如果没有选择,我将不使用装饰器。

目前我的代码如下:

$sDate = "2018-09-10 12:00:00";
$eDate = "2019-11-10 12:00:00";

$startDate = new DateTime($sDate);
$diff = $startDate->diff(new DateTime($eDate));

if ($diff->y > 0) 
    $diffStr = $diff->y." year";
else if ($diff->m > 0) 
    $diffStr = $diff->m." month";
else if ($diff->d > 0) 
    $diffStr = $diff->d." day";
else if ($diff->h > 0) 
    $diffStr = $diff->h." hour";
else if ($diff->i > 0) 
    $diffStr = $diff->i." minute";
else if ($diff->s > 0) 
    $diffStr = $diff->i." second";
else 
    $diffStr = "dates are same";

echo $diffStr;

但是我有这个错误:

class DM():
    def __init__(self, path=""):
        self.cors = CORS(self.app, resources={r"/*": {"origins": "*"}})
        self.host = "0.0.0.0"
        self.port = 9001

    class app(Flask):
        pass

    def PrintException(self):
        exc_type, exc_obj, tb = sys.exc_info()
        f = tb.tb_frame
        lineno = tb.tb_lineno
        filename = f.f_code.co_filename
        linecache.checkcache(filename)
        line = linecache.getline(filename, lineno, f.f_globals)
        return 'EXCEPTION IN ({}, LINE {} "{}"): {}'.format(
            filename, lineno, line.strip(), exc_obj
        )

    @app.route("/product", methods=["POST", "GET", "OPTION"])
    def addProduct(self):
        try:
            data = request.data
            document = json.loads(data.decode("utf-8"))
            return jsonify({"status":"ok","_id":str(document)})
        except Exception as e:
            return jsonify({"status": "ko", "exception": self.PrintException() + " " + str(e),"document":document})


    @app.after_request
    def after_request(self,response):
        response.headers.add("Access-Control-Allow-Origin", "*")
        response.headers.add("Access-Control-Allow-Headers", "Content-Type,Authorization")
        response.headers.add("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS")
        return response
    def run(self):
        self.app.run(self.host, self.port)

编辑:

我不能在装饰器中使用self:

    @app.route("/product", methods=["POST", "GET", "OPTION"])
TypeError: route() missing 1 required positional argument: 'rule'

致谢

1 个答案:

答案 0 :(得分:0)

我不确定您要使用继承方法究竟要实现什么,但是无论如何,这是一个有用的想法。与其在类中使用flask应用,不如考虑使用factory approach。您的示例中的代码可能如下所示:

def create_application(app_name, config_filename, host, port):

    app = Flask(app_name)
    app.config_from_pyfile(config_filename)

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

    @app.route("/product", methods=["POST", "GET", "OPTION"])
    def addProduct():
        try:
            data = request.data
            document = json.loads(data.decode("utf-8"))
            return jsonify({"status":"ok","_id":str(document)})
        except Exception as e:
            return jsonify({"status": "ko", "exception": self.PrintException() + " " + str(e),"document":document})

    @app.after_request
    def after_request(response):
        response.headers.add("Access-Control-Allow-Origin", "*")
        response.headers.add("Access-Control-Allow-Headers",
                             "Content-Type,Authorization")
        response.headers.add("Access-Control-Allow-Methods",
                             "GET,PUT,POST,DELETE,OPTIONS")
        return response

此方法将允许您进行必要的自定义,将不同的参数传递给工厂函数或不同的配置文件。而且您仍然可以在这里使用装饰器