python - 子类化 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'
解决方案
您将someValue
kwarg 传递给超类 Flask,这是出乎意料的。而不是get
ting 它,试试这个:
self.someValue = kwargs.pop('someValue')
这会将它从 kwargs 中删除,当你将它们传递给 Flask 时,它就消失了。
推荐阅读
- drupal-8 - 我可以根据视图的结果生成表单吗?
- excel - 循环列表并生成报告
- pyspark - Databricks dbutils.fs.ls 显示文件。但是,读取它们会引发 IO 错误
- powershell - SCCM - 使用 PowerShell 更改现有的部署期限
- c++ - 修改程序入口点时未调用全局变量的构造函数
- go - 在 Golang 中刷新标准输入缓冲区?
- javascript - 一直在 onclick 中响应调用函数
- javascript - 如何读取 csv 文件以将其转换为 Json 对象?
- python - 使用循环导入构建模块 API 的 Pythonic 方式
- javascript - 在为参数赋值时将参数传递给函数,javascript