我正在使用flask蓝图来创建动态路由。我遵循了这个Example。
这是我的示例代码,
demo = Blueprint('demo', __name__)
@demo.route('/')
def home():
return 'here'
def add_subdomain_to_global(endpoint, values):
g.subdomain = values.pop('subdomain', None)
def add_subdomain_to_url_params(endpoint, values):
if not 'subdomain' in values:
values['subdomain'] = g.subdomain
def add_subdomain_support(app):
app.url_value_preprocessor(add_subdomain_to_global)
app.url_defaults(add_subdomain_to_url_params)
app = Flask(__name__)
app.config['SERVER_NAME']= 'lingam.com'
add_subdomain_support(app)
@app.before_request
def add_user_to_global():
userdb = {'x':'sorna','y':'lingam'}
g.user = None
if g.subdomain:
g.user = userdb[g.subdomiain]
app.register_blueprint(demo, subdomain='<subdomain>')
if __name__ == "__main__":
app.run()
当我提供“.localhost:5000”时,我收到错误,当我调试并发现def add_subdomain_to_global(endpoint, values)
:在此行{'subdomain':<invalid>}
时。出了什么问题,我怎么能动态使用子域名。
错误跟踪
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\flask\app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python34\lib\site-packages\flask\app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python34\lib\site-packages\flask\app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python34\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Python34\lib\site-packages\flask\app.py", line 1637, in full_dispatch_request
rv = self.preprocess_request()
File "C:\Python34\lib\site-packages\flask\app.py", line 1837, in preprocess_request
rv = func()
File "E:/Work/Python1/work/So/flasksubdomain.py", line 25, in add_user_to_global
g.user = userdb[g.subdomain]
KeyError: '<invalid>'
127.0.0.1 - - [07/Oct/2017 17:09:04] "GET / HTTP/1.1" 500 -