类型错误:%d 格式:需要一个数字,而不是 Dash
Posted
技术标签:
【中文标题】类型错误:%d 格式:需要一个数字,而不是 Dash【英文标题】:TypeError: %d format: a number is required, not Dash 【发布时间】:2020-09-24 22:40:14 【问题描述】:我正在创建一个带有令牌身份验证的烧瓶 Dash 应用程序。如果令牌经过身份验证,那么我想将 dash.Dash() 传递到烧瓶应用程序中,否则想要返回一个虚拟的破折号布局。但是当我点击路线“仪表板”时出现以下错误。请帮我解决这个问题。
错误:
__init.py
"""
Initialize app
"""
from flask import Flask, make_response, request, redirect, jsonify, url_for, session
import jwt
import urllib.parse
from functools import wraps
from datetime import timedelta
import os
print("__init__.py location", os.getcwd())
path = os.path.join("application", "dash_application")
#os.chdir(path)
print("directory after init", os.getcwd())
def create_app():
"""
construct the flask core application
:return: Complete app
"""
app = Flask(__name__)
app.config.from_object('config.Config')
"""
auth_request decorator is validating the token, if token is genuine then it returning to next method else
sending invalid token response to use
"""
def auth_request(f):
@wraps(f)
def wrapper(*args, **kwargs):
authorization = request.args.get('access_token') or request.headers.get('authorization')
if not authorization:
return make_response(jsonify(
"message": "Invalid request",
"token": "null",
"status": False,
"error":
"message": "Invalid token or token missing"
), 400)
try:
if request.method == "POST":
authorization = authorization[7:] # Removed first Bearer OR bearer from token
data = jwt.decode(authorization, app.config.get('SECRET_KEY'), audience=app.config.get('AUDIENCE'))
return f(data, *args, **kwargs)
authorization = urllib.parse.unquote(authorization) # Removed first Bearer OR bearer from token
data = jwt.decode(authorization, app.config.get('SECRET_KEY'), audience=app.config.get('AUDIENCE'))
return f(data, *args, **kwargs)
except Exception as e:
print(e)
return make_response(jsonify(
"message": "Invalid request",
"token": "null",
"status": False,
"error":
"message": "Invalid token or token missing"
), 400)
return wrapper
@app.route('/', methods=['GET'])
def index():
return make_response(jsonify(
"message": "Success",
"status": True,
"error":
), 200)
@app.route('/authenticate', methods=['POST'])
@auth_request
def authenticate(data):
return make_response(jsonify(
"message": "successfully authenticated!",
"status": True,
"error":
), 200)
@app.route('/twc-admin-panel-integration', methods=['GET'])
@auth_request
def twc_admin_panel_integration(data):
if int(data['corporateId']) > 0:
session['isAuthenticated'] = 'yes'
session['corporateId'] = 9 # data.get('corporateId')
return redirect('/dashboard/')
return make_response(jsonify(
"message": "required property is missing in token",
"status": False,
"error":
"message": "invalid token"
), 400)
@app.route('/dashboard/')
def mypage():
app = Flask(__name__)
app.config.from_object('config.Config')
# session.permanent = True
# app.permanent_session_lifetime = timedelta(minutes=app.config.get('SESSION_EXPIRY_TIME'))
# app.secret_key = app.config.get('SESSION_SECRET')
with app.app_context():
print("reached at line 109")
from application.dash_application.dashapp import add_dash
dashapp = add_dash(app, 179) # add_dash returning the dash.Dash instance
#
# if session.get('isAuthenticated') is not None:
# if 'yes' in session['isAuthenticated']:
return app, dashapp
# return redirect(app.config.get('TWC_ADMIN_URL'))
# return redirect(app.config.get('TWC_ADMIN_URL'))
with app.app_context():
from application.dash_application.dashapp import add_dash
dashapp = add_dash(app, 179)
return app, dashapp
并使用 WSGI DispatcherMiddleware 运行此应用程序文件
app.py
"""
Application entry point
"""
from application import create_app
from flask_cors import CORS
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from werkzeug.serving import run_simple
def main():
flask, dash = create_app()
CORS(flask, resources=r"/*": "origins": "*")
if dash:
app = DispatcherMiddleware(flask,
'dashboard': dash.server
)
run_simple(hostname="127.0.0.1", port=8080, application=app, use_reloader=True, use_debugger=True)
if __name__=="__main__":
main()
完整的错误回溯是:
[2020-06-05 21:54:43,860] ERROR in app: Exception on /dashboard/ [GET]
Traceback (most recent call last):
File "D:\TWC\DashApp\crazy_corner\lib\site-packages\werkzeug\wrappers\base_response.py", line 298, in status_code
self._status = "%d %s" % (code, HTTP_STATUS_CODES[code].upper())
KeyError: <dash.dash.Dash object at 0x0000020514B01390>
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\TWC\DashApp\crazy_corner\lib\site-packages\flask\app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "D:\TWC\DashApp\crazy_corner\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
return self.finalize_request(rv)
File "D:\TWC\DashApp\crazy_corner\lib\site-packages\flask\app.py", line 1967, in finalize_request
response = self.make_response(rv)
File "D:\TWC\DashApp\crazy_corner\lib\site-packages\flask\app.py", line 2138, in make_response
rv.status_code = status
File "D:\TWC\DashApp\crazy_corner\lib\site-packages\werkzeug\wrappers\base_response.py", line 300, in status_code
self._status = "%d UNKNOWN" % code
TypeError: %d format: a number is required, not Dash
【问题讨论】:
请提供完整的错误回溯。 嗨,我添加了回溯错误。 任何查看此内容的人也可能对有关 Dash 和 JWT 的相关对话感兴趣:***.com/q/57629586/320399 【参考方案1】:我不太明白你想做什么,但在这个视图中函数mypage
:
def create_app():
# ...
@app.route('/dashboard/')
def mypage():
# ...
with app.app_context():
# ...
return app, dashapp
# ...
当你返回一个包含两个元素的元组时,Flask 会假定它是(body, status_code)
,并且 status_code 必须是一个数字。但是在您的情况下,元组的第二个元素是 Dash 对象(dashapp
),这会导致错误。此外,您作为元组的第一个元素返回的 Flask 应用程序实例 (app
) 不是视图函数的有效响应体。
【讨论】:
现在我遇到了问题。但是如何在仪表板应用程序中集成或更新特定于用户的布局?实际上,我正在为客户端创建一个破折号应用程序,其中布局是根据 clientID 表单请求创建的。 另外,如果我的回答解决了当前的问题,请采纳:)以上是关于类型错误:%d 格式:需要一个数字,而不是 Dash的主要内容,如果未能解决你的问题,请参考以下文章
需要 %d 格式,而不是 tkinter python 到 mysql 数据库中的 str 错误
有没有办法只接受字母而不是数字?如果给出数字,它应该显示验证错误,因为它只需要字母