sailormoonbs
sailormoonbs

Reputation: 9

python flask | how to store html input in a python variable

using flask in python to get html input and store it as python variable

/example.html
<form>
<input type=text name=string>  # a string value
<input type=submit>
<input type=text name=float>  # a float value
<input type=submit>  
</form>

/main.py
@app.route("/")
def get_input():
    example_string = request.args.get('search')
    example_limit = request.args.get('float')
    return render_template('example.html', example_string, example_limit)

/examplefile.py
from main import example_string, example_limit
print(example_string)
print(example_limit)

this particular approach does not seem to work, maybe its the request.args.get() not being used appropriately or something. You can probably see what I've tried to do here. Please help.

Upvotes: 0

Views: 1783

Answers (1)

Tomas Am
Tomas Am

Reputation: 503

Your question suggests that you may need to pass this or similar tutorial: https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world

For your problem there are many ways, example route:

@app.route('/test', methods=['POST', 'GET'])
def test():
    if request.method == 'POST':
        #version 1:
        opt1 = request.form.to_dict()
        for key in opt1:
            if key == "string":
                string = opt1[key]
            if key == "float": 
                floata = opt1[key]
        print(string, floata)
        #version 2:
        string2 = request.form["string"]
        float2 = request.form["float"]
        # if you need float : floatvar = float(float2)
        print(float2)
        print(string2)

        return "success"
    else:
        return render_template('example.html')

Template:

<form method="POST">
    <input type="text" name="string"/>
    <input type="text" name="float"/>
    <button type="submit">Submit</button>
</form>

Upvotes: 2

Related Questions