T1ber1us
T1ber1us

Reputation: 161

Flask, save data from forms to json file

I can't figure out how to save data server side. Here is my route:

@app.route('/results', methods=['GET', 'POST'])
@login_required
def results():
    if request.method == 'POST':
        results = request.form
        return json.dumps(request.form)

There I convert the request form from a dictionary to a string. Here is my HTML that makes up the form:

<form action = "/results" method = "POST">
                <input type="text" placeholder="Host" name="host" value="host">
                <input type="text" placeholder="Longname" name="longname" value="longname">
                <input type="text" placeholder="Shortname" name="shortname" value="shortname">
                <p><input class="btn btn-primary" type="submit" value="send"></p>

I made a result page to see if I could convert the form to JSON. But now I'm stuck, I don't know how to save results to a file. Every time I post the form, I get back something that looks like this:

{hosts ["host": "a", "shortname": "c", "longname": "b"], ["host": "a", "shortname": "c", "longname": "b"]}

Upvotes: 3

Views: 13933

Answers (1)

Wayne Werner
Wayne Werner

Reputation: 51787

If you read the documentation on the JSON module you'll see that there's a dump method that works like dumps. You just have to feed it a file object as well:

    with open('file.json', 'w') as f:
        json.dump(request.form, f)
    return render_html('your_template.html')

That will write out your form to file.json. You probably want to set something up in your flask config to store the full path to the file that you plan to save.

Upvotes: 6

Related Questions