0

Ребят, подскажите пожалуйста, как унаследовать от def index, чтобы не повторять лишний код в def menu?

@app.route('/')
def index():
    name = 'Вхід'
    if login.current_user.is_authenticated:
        name = 'Кабінет' + ' ' + current_user.login
    return render_template('index.html', name=name)

@app.route('/menu')
def menu():
    name = 'Вхід'
    if login.current_user.is_authenticated:
        name = 'Кабінет' + ' ' + current_user.login
    return  render_template('project_templates/menu.html', name=name)
1
  • 2
    Вынести в отдельную функцию и вызывать её
    – andreymal
    10 мар 2017 в 11:42

4 ответа 4

1
def common_args():
    name = 'Вхід'
    if login.current_user.is_authenticated:
        name = 'Кабінет' + ' ' + current_user.login
    return {'name': name}

@app.route('/')
def index():
    return render_template('index.html', **common_args())

@app.route('/menu')
def menu():
    return render_template('project_templates/menu.html', **common_args())
1
  • Спасибо,разобрался)
    – Dmitriy
    10 мар 2017 в 12:20
0

Можно сделать функцию index с параметром и таким образом её можно будет использовать вместо menu

def index(my_html):
    name = 'Вхід'
    if login.current_user.is_authenticated:
        name = 'Кабінет' + ' ' + current_user.login
    return render_template(my_html, name=name)
2
  • Боюсь, такое решение будет очень плохо расширяться и кроме как в этом примере не поможет
    – andreymal
    10 мар 2017 в 11:52
  • Это простое "в лоб". Думаете стоит удалить?
    – nick_gabpe
    10 мар 2017 в 11:55
0
def current_name(fn):
    def wrap(*args, **kwargs):
        kwargs['name'] = 'Кабінет %s' % current_user.login if login.current_user.is_authenticated else 'Вхід'
        return fn(*args, **kwargs)
    return wrap

@current_name
@app.route('/')
def index(name):
    return render_template('index.html', name=name)

# или
@app.route('/menu')
def menu():
    return current_name(render_template)('project_templates/menu.html')
0

Вот такую сделал функцию,думаю нормальная, как думаете?

def repeat():
    name = 'Вхід'
    if login.current_user.is_authenticated:
        name = 'Кабінет' + ' ' + current_user.login
    return (name)

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.