将Flask意外的关键字参数归为子类

时间:2019-01-07 05:00:12

标签: python

我在应用程序中将Flask子类化时遇到问题。我的类初始化中遇到了意外的关键字参数异常。

app / controller.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)

app / 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'

1 个答案:

答案 0 :(得分:1)

您正在将someValue kwarg传递给超类Flask,这在意料之外。代替get设置它,试试这个:

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

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