Flask flash message is only displayed after reloading the page

Viewed 508

I've been trying to display a message using flash extension. It does works, but only after realoding (F5) the page.

I've added a button on my proposals page, which calls the login function:

@app.route('/login', methods=['POST', 'GET'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('submit_proposal'))
    w3 = Web3(Web3.HTTPProvider('https://smartbch.greyh.at'))
    if not w3.isConnected():
        w3 = Web3(Web3.HTTPProvider('https://smartbch.fountainhead.cash/mainnet'))

    public_address = request.json[0]
    signature = request.json[1]

    domain = "127.0.0.1"

    rightnow = int(time.time())
    sortanow = rightnow - rightnow % 600

    original_message = 'Signing in to {} at {}'.format(domain, sortanow)
    message_hash = defunct_hash_message(text=original_message)
    signer = w3.eth.account.recoverHash(message_hash, signature=signature)

    if signer == public_address:
        print("[+] this is fine " + str(signer))
        ABI = open("/home/administrador/Descargas/BCH/transparency_portal/ABIs/ERC20-ABI.json", "r")  # Standard ABI for ERC20 tokens
        abi = json.loads(ABI.read())
        contract = w3.eth.contract(address="0xF05bD3d7709980f60CD5206BddFFA8553176dd29", abi=abi)
        SIDX_balance = contract.functions.balanceOf(signer).call() / 10 ** 18
        if SIDX_balance < 5000:
            flash('You need at least 5000 SIDX token to submit a proposal')
            return url_for('proposals')
        else:
            user = User.query.get(signer)
            if user == None:
                user = User(public_address=signer)
                db.session.add(user)
                db.session.commit()
            login_user(user)
            return redirect(url_for('submit_proposal'))
    else:
        abort(401, 'could not authenticate signature')

This is the code on the proposals.html template to show the button and the flash message:

<div class="container">
  Some text here
  <br><button onclick='login()'>Submit a proposal</button>
</div>

{% with messages=get_flashed_messages() %}
    {% if messages %}
            {% for message in messages %}
             <div class="alert alert-error">{{ message|safe }}</div>
            {% endfor %}
    {% endif %}
{% endwith %}

The Flask app only displays this bahaviour using return url_for('proposals'). If I use instead return redirect(url_for('proposals')), nothing happens before and after reloading the page.

Is there anyway to force url_for() to refresh the page?

0 Answers
Related