In this lesson, you'll explore common data types in Python and how to use them in Flask apps. This builds on handling requests, focusing on strings, integers, lists, and dictionaries in a backend context.
Data types are fundamental in programming, defining the kind of data you can work with. You'll create a Flask app that processes different data types from user inputs. Here's what you'll do:
By the end, you'll understand how to manage various data types in web backends.
To start, create a folder for this lesson's project to keep things organised.
FlaskDataTypes
'.File > Open Folder
, then choose 'FlaskDataTypes
'.With your folder ready, next you'll set up the environment.
Create a virtual environment for your project.
View > Command Palette
.Python: Create Environment
' and select it.Venv
'..venv
' folder.Open a terminal in VS Code to install Flask if needed.
View > Terminal
.pip install flask
.Let's create a Flask app that handles string data from a form.
Create 'app.py
' in 'FlaskDataTypes
'.
Add this code:
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def home():
return 'Welcome to Data Types in Backend!'
@app.route('/string', methods=['GET', 'POST'])
def handle_string():
if request.method == 'POST':
text = request.form['text']
return f'You entered the string: {text}'
else:
return render_template('string_form.html')
Create a 'templates
' folder, and inside it, 'string_form.html
' with:
<!DOCTYPE html>
<html>
<head><title>String Input</title></head>
<body>
<h1>Enter a String</h1>
<form method="post" action="/string">
<input type="text" name="text">
<button type="submit">Submit</button>
</form>
</body>
</html>
action
is set to '/string
', which matches the route defined in the Flask app. This ensures the form data is sent to the correct endpoint.Run python -m flask run
.
Visit http://127.0.0.1:5000/string, enter text, submit, and see the response.
Stop with Ctrl+C
.