Creating website with Flask (Python) – Part 2
In Part 1 of this tutorial, we learned how to set up a basic Flask application and create a simple web page. In Part 2, we will dive deeper into creating a more complex website with Flask.
Creating Routes
In Flask, routes are used to map URLs to particular functions. We can create routes for different pages of our website by using the @app.route
decorator. For example, to create a route for the homepage, we can do the following:
@app.route('/')
def index():
return 'Welcome to my website!'
Rendering Templates
Instead of returning plain text from our routes, we can render HTML templates using the render_template
function. First, we need to create a templates
directory in our project and place our HTML files inside it. Then, we can use the following code in our route to render a template:
from flask import render_template
@app.route('/about')
def about():
return render_template('about.html')
Working with Forms
Flask provides a powerful and flexible way to handle web forms. We can create a form using the FlaskForm
class from the flask_wtf
module. We can then render the form in our template and handle form submissions in our routes. Here is an example of creating a simple contact form:
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
class ContactForm(FlaskForm):
name = StringField('Name', validators=[DataRequired()])
email = StringField('Email', validators=[DataRequired()])
message = StringField('Message', validators=[DataRequired()])
submit = SubmitField('Send')
Conclusion
Creating a website with Flask can be a rewarding experience. In this article, we have covered the basics of creating routes, rendering templates, and working with forms. With these tools, you can build a fully functional and interactive website using Python and Flask. In the next part of this series, we will explore more advanced topics such as database integration and user authentication. Stay tuned!