TypeError: %d format: a number is required, not Dash
TypeError: %d format: a number is required, not Dash
我正在创建一个带有令牌身份验证的 flask-Dash 应用程序。如果令牌经过身份验证,那么我想将 dash.Dash() 传递到 Flask 应用程序中,否则我想 return 一个虚拟破折号布局。但是当我到达路线 'dashboard' 时出现以下错误。请帮我解决这个问题。
错误:类型错误:%d 格式:需要数字,而不是短划线
__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
我不太明白你想做什么,但是在这个视图函数中mypage
:
def create_app():
# ...
@app.route('/dashboard/')
def mypage():
# ...
with app.app_context():
# ...
return app, dashapp
# ...
当你 return 一个二元素元组时,Flask 会假定它是 (body, status_code)
,并且 status_code 必须是一个数字。但在您的情况下,元组的第二个元素是 Dash 对象 (dashapp
),这会导致错误。此外,您 return 作为元组的第一个元素编辑的 Flask 应用程序实例 (app
) 不是视图函数的有效响应主体。
我正在创建一个带有令牌身份验证的 flask-Dash 应用程序。如果令牌经过身份验证,那么我想将 dash.Dash() 传递到 Flask 应用程序中,否则我想 return 一个虚拟破折号布局。但是当我到达路线 'dashboard' 时出现以下错误。请帮我解决这个问题。
错误:类型错误:%d 格式:需要数字,而不是短划线
__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
我不太明白你想做什么,但是在这个视图函数中mypage
:
def create_app():
# ...
@app.route('/dashboard/')
def mypage():
# ...
with app.app_context():
# ...
return app, dashapp
# ...
当你 return 一个二元素元组时,Flask 会假定它是 (body, status_code)
,并且 status_code 必须是一个数字。但在您的情况下,元组的第二个元素是 Dash 对象 (dashapp
),这会导致错误。此外,您 return 作为元组的第一个元素编辑的 Flask 应用程序实例 (app
) 不是视图函数的有效响应主体。