User:Kim/Stations, Skills, Resources/Flask: Difference between revisions
No edit summary |
(→JSON) |
||
| Line 12: | Line 12: | ||
=== JSON === | === JSON === | ||
''objective: submit multiple inputs, store and retrieve them from json'' | ''objective: submit multiple inputs, store and retrieve them from json'' | ||
<syntaxhighlight lang="python"> | |||
from flask import Flask, render_template, request | |||
app = Flask(__name__) | |||
# define route | |||
# when the route is being accessed, run function main with get and post request | |||
@app.route("/", methods=["GET", "POST"]) | |||
# function main gets form input and renders a template (render and request are methods imported from flask) | |||
def main(): | |||
# is request is post | |||
if request.method == "POST": | |||
# request the form (in the html template) | |||
observation = request.form["observation"] | |||
# append the form input to observations | |||
observations.append(observation) | |||
# append observation to txt file | |||
# make txt file | |||
with open("database.txt", "a") as database: | |||
# we are only wiriting on post requests | |||
database.write("\n"+ observation) | |||
# reading is for opening the app, when we dont write first (code is not entirely running linearly) | |||
database = open("database.txt", "r").readlines() | |||
# or output to database.txt: | |||
return render_template("observations.html", database=database) | |||
</syntaxhighlight> | |||
Revision as of 14:08, 13 April 2026
pad with collective notes: https://pad.xpub.nl/p/FLASK-OMG-itshappening
Examples
txt
objective: website with textarea saves input to txt file and publishes entries on the page
JSON
objective: submit multiple inputs, store and retrieve them from json
from flask import Flask, render_template, request
app = Flask(__name__)
# define route
# when the route is being accessed, run function main with get and post request
@app.route("/", methods=["GET", "POST"])
# function main gets form input and renders a template (render and request are methods imported from flask)
def main():
# is request is post
if request.method == "POST":
# request the form (in the html template)
observation = request.form["observation"]
# append the form input to observations
observations.append(observation)
# append observation to txt file
# make txt file
with open("database.txt", "a") as database:
# we are only wiriting on post requests
database.write("\n"+ observation)
# reading is for opening the app, when we dont write first (code is not entirely running linearly)
database = open("database.txt", "r").readlines()
# or output to database.txt:
return render_template("observations.html", database=database)