Welcome to our comprehensive guide on Flask Installation! By the end of this tutorial, you'll be ready to dive into the world of Flask web development.
Flask is a micro web framework written in Python, perfect for building small to medium web applications. It's easy to use, lightweight, and a great choice for beginners and intermediates.
To follow along, ensure you have Python installed on your machine. You can download it from here.
Now let's install Flask. Open your terminal and run:
pip install flaskš” Pro Tip: If you encounter an error, try using pip3 instead of pip.
To confirm Flask is installed correctly, create a new Python file, name it app.py, and add the following code:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)Save the file and run it in your terminal:
python app.pyNavigate to http://127.0.0.1:5000/ in your web browser. If everything went well, you should see "Hello, World!" displayed.
Now let's create a simple Flask application that takes user input. Update your app.py file with the following code:
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def home():
if request.method == 'POST':
name = request.form.get('name')
return f'Hello, {name}!'
return render_template('home.html')
if __name__ == '__main__':
app.run(debug=True)Create a new folder named templates in the same directory as your app.py. Inside the templates folder, create a new file named home.html with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flask Example</title>
</head>
<body>
<form method="post">
<label for="name">Enter your name:</label>
<input type="text" name="name" id="name">
<input type="submit" value="Submit">
</form>
</body>
</html>Now, refresh your web browser at http://127.0.0.1:5000/. You should see a simple form to enter your name. Type your name and click "Submit". The browser will display "Hello, [Your Name]!".
Which command is used to install Flask?
With this, you've completed our Flask Installation tutorial! You're now ready to dive deeper into Flask web development. Stay tuned for our upcoming tutorials on creating routes, templates, and more! š” Pro Tip: Check out our other tutorials on CodeYourCraft for more resources.