为什么代码被标记为不工作、不工作并抛出相应的错误?什么是正确的方法呢?import *不是正确的方法。
我的routing.py
import os
from flask import Flask
from views import UserView
#App Config
app= Flask(__name__)
# ********************** NOT WORKING ****************************
# from error_handlers import auth_error ==> AssertionError: View function mapping is overwriting an existing endpoint function: user_view
# from error_handlers import * ==> AssertionError: View function mapping is overwriting an existing endpoint function: user_view
# ***************************************************************
#URLs
app.add_url_rule('/users', view_func=UserView.as_view('user_view'), methods=['GET'])
# ********************** NOT WORKING ****************************
# from error_handlers import auth_error ==> ImportError: cannot import name auth_error
# ***************************************************************
# ********************** WORKING ****************************
from error_handlers import *
# ***************************************************************
if __name__ == '__main__':
app.run(debug=True, host = '0.0.0.0', port=5050)error_handlers.py是:
from flask import render_template, jsonify
from routing import app
from myexceptions import *
#Error Handlers
@app.errorhandler(404)
def unexpected_error(error):
""" error handler for unknown error """
return render_template('error.html'), 404
@app.errorhandler(AuthenticationException)
def auth_error(error):
""" error handler user entered data exception """
return jsonify({'error': error.get_message()})views.py是:
from flask.views import View
from flask import render_template
from myexceptions import AuthenticationException
class ParentView(View):
def get_template_name(self):
raise NotImplementedError()
def render_template(self, context):
return render_template(self.get_template_name(), **context)
def dispatch_request(self):
context = self.get_objects()
return self.render_template(context)
class UserView(ParentView):
def get_template_name(self):
raise AuthenticationException('test')
return 'users.html'
def get_objects(self):
return {}而AuthenticationException只是一个在myexceptions中定义的Exception子类。
发布于 2014-07-26 17:37:21
我也读过你的代码在你的github之前,也许错误是:你导入的一些文件中的应用程序不使用应用程序
我的修改代码:
routing.py
import os
from flask import Flask
#App Config
app= Flask(__name__)
from views import UserView
app.add_url_rule('/users', view_func=UserView.as_view('user_view'), methods=['GET'])
if __name__ == '__main__':
print app.url_map
app.run(debug=True, host = '10.210.71.145', port=5050)你的error_handle.py可能是这样的:
from flask import render_template, jsonify
from myexceptions import AuthenticationException
@app.errorhandler(404)
def unexpected_error(error):
""" error handler for unknown error """
return render_template('error.html'), 404
@app.errorhandler(AuthenticationException)
def auth_error(error):
""" error handler user entered data exception """
return jsonify({'error': error.get_message()})https://stackoverflow.com/questions/24861330
复制相似问题