<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def set_lang(lang_code=None):
 """Set language in session and redirect."""

    # Check if language is available.
    lang_code = lang_code or request.values.get('lang_code')
    languages = dict(current_app.extensions['invenio-i18n'].get_languages())
    if lang_code is None or lang_code not in languages:
        abort(404 if request.method == 'GET' else 400)

    # Set language in session.
    session[current_app.config['I18N_SESSION_KEY']] = lang_code.lower()

    # Redirect user back.
    target = get_redirect_target()
    if not target:
        endpoint = current_app.config['I18N_DEFAULT_REDIRECT_ENDPOINT']
        target = url_for(endpoint) if endpoint else '/'

    return redirect(target)