前文:用 flask 如何做配置不同的子站比较优雅?( http://www.v2ex.com/t/296370 )
问题:如何才能把 bluepront.py 文件中的 g.user_url_slug 变量放到 models.py 文件中使用?
from flask import Blueprint, render_template, g
from app import models
site = Blueprint('site', __name__, url_prefix='/<user_url_slug>')
@site.url_defaults
def add_user_url_slug(endpoint, values):
values.setdefault('user_url_slug', g.user_url_slug)
@site.url_value_preprocessor
def pull_user_url_slug(endpoint, values):
g.user_url_slug = values.pop('user_url_slug')
@site.route('/')
def index():
return g.user_url_slug + ' home'
from flask import g
from app import db
class User(db.Model):
# 如何才能把 blueprint.py 中的 g.user_url_slug 放到这里,生成不同的子站数据库表前缀
__tablename__ = g.user_url_slug + '_users'
id = db.Column(db.Integer, primary_key = True)
nickname = db.Column(db.String(64), index = True, unique = True)
email = db.Column(db.String(120), index = True, unique = True)
def __repr__(self):
return '<User %r>' % (self.nickname)