首页 > 解决方案 > 子类化 Flask 意外的关键字参数

问题描述

我在我的应用程序中对 Flask 进行子类化时遇到问题。我的类 init 中出现意外的关键字参数异常。

应用程序/控制器.py

from app.searchapi import SearchService

[...]

def main(args, config):
  app = SearchService(someValue=True)
  app.run(threaded=True, use_reloader=False, debug=False,
              host='127.0.0.1', port=5000)

应用程序/searchapi.py

from flask import Flask, jsonify, request, make_response, json

class SearchService(Flask):
    def __init__(self, *args, **kwargs):
        if not args:
            kwargs.setdefault('import_name',__name__)
        self.someValue = kwargs.get('someValue')
        super(SearchService, self).__init__(*args, **kwargs)

        self.route("/", methods=['GET'])(self.HelloWorld)

    def HelloWorld(self):
        return "Hello, World"

退货

Traceback (most recent call last):
  File "/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 917, in _bootstrap_inner
    self.run()
  File "/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "/Users/div/Project/app/controller.py", line 158, in main
    app = SearchService(someValue=True)
  File "/Users/div/Project/app/searchapi.py", line 15, in __init__
    super(SearchService, self).__init__(*args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'someValue'

标签: python

解决方案


您将someValuekwarg 传递给超类 Flask,这是出乎意料的。而不是getting 它,试试这个:

self.someValue = kwargs.pop('someValue')

这会将它从 kwargs 中删除,当你将它们传递给 Flask 时,它就消失了。


推荐阅读