How does flask-wtforms get the value of csrf_token

how to get the value of csrf_token on the backend using flask-wtforms

May.27,2022

it depends on where your token is stored.

< H2 > example 1. Put it in the form < / H2 >
<form method="post">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
</form>

then the back end can be obtained using request.form ['csrf_token'] .

< H2 > example 2. Put it in Ajax Header < / H2 >
<script type="text/javascript">
    var csrf_token = "{{ csrf_token() }}";

    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrf_token);
            }
        }
    });
</script>

then the backend is available request.headers ['Xmuri CSRFToken'] .

< hr >

or refer to the flask CSRF source code to implement
https://github.com/lepture/fl...

    def _get_csrf_token(self):
        -sharp find the token in the form data
        field_name = current_app.config['WTF_CSRF_FIELD_NAME']
        base_token = request.form.get(field_name)

        if base_token:
            return base_token

        -sharp if the form has a prefix, the name will be {prefix}-csrf_token
        for key in request.form:
            if key.endswith(field_name):
                csrf_token = request.form[key]

                if csrf_token:
                    return csrf_token

        -sharp find the token in the headers
        for header_name in current_app.config['WTF_CSRF_HEADERS']:
            csrf_token = request.headers.get(header_name)

            if csrf_token:
                return csrf_token

        return None
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3e8e1-2c40a.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3e8e1-2c40a.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?