Writing a website with Flask is a relatively simple and fun process.Flask is a lightweight web application framework written in Python. It's easy to get started with, but also very powerful and suitable for building a wide range of projects from simple blogs to complex web applications. Here's a guide to writing a simple website using Flask, including code samples.
I. How to use Flask to write a website
(i) Install Flask
First, we need to make sure we have Flask installed in our Python environment. we can use pip (Python's package manager) to install it.
bash copy code
pip install Flask
(ii) Creating a Flask application
-
Creating a project directory:
Create a new directory on our computer to hold our Flask project. -
Creating the master application file:
Create a file in the project directory called(or whatever name we like) file and add the following code:
#from flask import Flask, render_template, request_template
from flask import Flask, render_template, request
app = Flask(__name__)
# Configuration items (optional)
['DEBUG'] = True # Enable debug mode so that the server will restart automatically after code changes.
# Routing and view functions
@('/')
def home().
return render_template('') # Render the template file.
@('/greet', methods=['GET', 'POST'])
def greet(): if == 'POST': if == 'GET', 'POST']
if == 'POST'.
name = ['name'] # Get the data from the form.
return f'Hello, {name}!'
return render_template('') # render the form template
if __name__ == '__main__'.
(host='0.0.0.0', port=5000) # Run on all network interfaces, listening on port 5000
(iii) Creation of HTML templates
-
Creating a template catalog:
Create a file in the project directory calledtemplates
of the folder. -
Adding a template file:
existtemplates
folder to create two HTML files:cap (a poem)
。
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
</head>
<body>
<h1>Welcome to My Flask Website</h1>
<a href="/greet">Greet Someone</a>
</body>
</html>
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Greet</title>
</head>
<body>
<h1>Greet Someone</h1>
<form method="post">
<label for="name">Name:</label>
<input type="text" name="name">
<button type="submit">Submit</button>
</form>
</body>
</html>
(iv) Running a Flask application
-
Open a terminal:
Open our command line interface (terminal, command prompt, etc.). -
Navigate to the project directory:
utilizationcd
command navigates to the project directory we created. -
Running the application:
Run the following command in the terminal to start the Flask application:
bash copy code
python
-
Access to the website:
Open our web browser and visithttp://localhost:5000/
We will see the "Welcome to My Flask Website" page. We will see "Welcome to My Flask Website" page. Click on the "Greet Someone" link and we will be taken to the form page. Fill the form and submit it and we will see the greeting message.
(v) Commissioning and deployment
-
adjust components during testing: If we turn on debug mode (
['DEBUG'] = True
), when we change the code and save it, the Flask app is automatically restarted so that we can see the effect of the changes immediately. - deployments: Deploying a Flask application to a production environment usually involves using a WSGI server (such as Gunicorn or uWSGI) and a reverse proxy (such as Nginx or Apache). This is beyond the scope of this simple guide, but we can consult the official Flask documentation or search for related tutorials for more information.
With the above steps, we have successfully written a simple website using Flask. Now, we can go ahead and extend our website by adding more routes, templates, and logic to suit our needs.
Second, how to add style sheets in Flask
Adding style sheets (CSS) in Flask is a common requirement that allows us to customize the look and feel of a web page. Here are the steps on how to add and use style sheets in Flask projects:
(i) Creation of static folders
Flask has a convention that all static files (e.g. CSS, JavaScript, images, etc.) are placed in a file namedstatic
folder in our project directory. If we don't already have this folder in our project directory, create one.
(ii) Adding style sheet files
existstatic
folder, create a new CSS file like this。
(iii) Writing CSS code
existfile to write our CSS code. Example:
/* */
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
margin: 0;
padding: 0;
}
h1 {
color: #333;
}
.container {
width: 80%;
margin: 0 auto;
padding: 20px;
background-color: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
(iv) Linking style sheets in HTML templates
Now, we need to link this CSS file in the HTML template. Use the<link>
tags, and willhref
attribute is set to the relative path of the stylesheet (from thestatic
(folder start).
For example, in ourIn the template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Flask Website</title>
<link rel="stylesheet" href="{{ url_for('static', filename='') }}">
</head>
<body>
<div class="container">
<h1>Welcome to My Flask Website</h1>
<p>This is a simple Flask web application with a custom stylesheet.</p>
</div>
</body>
</html>
Note the use of{{ url_for('static', filename='') }}
This is a helper function provided by Flask to ensure that our static file paths are correct, even if we deploy the application to a different URL or subpath.
(v) Running a Flask application
Make sure our Flask app is running and then visit our web page. We can see the web page with CSS styles applied.
(vi) Commissioning and modifications
If the style is not applied correctly, check the following points:
- assure
static
folders andThe path to the file is correct.
- Ensure that the HTML template is correctly using the
<link>
Tags. - Clear your browser cache to make sure we are seeing the latest CSS file.
- Use your browser's developer tools (which can usually be opened by pressing F12 or right-clicking on a page and selecting "Inspect") to check for any errors or warnings.
With the above steps, we were able to successfully add and use stylesheets in our Flask project.
Three, how to add images in Flask
Adding images in Flask is similar to adding a stylesheet, we need to place the image files in a specified static folder and reference them in the HTML template. Below are the detailed steps:
(i) Creation or validation of static folders
Make sure we have a Flask project namedstatic
folder. This folder is used to store all the static files, including images, CSS files, JavaScript files, and so on.
(ii) Adding image files
Putting our image files (e.g.(computing) put (sth) into (the)
static
folder. We can create a subfolder within this folder to organize our images, for examplestatic/images/
。
(iii) Referencing images in HTML templates
In our HTML templates, using the<img>
tag to reference the image. Since images are stored in thestatic
folder, we need to refer to them using relative paths.Flask provides a helper functionurl_for
to generate URLs for static files, but for images it's often simpler and more intuitive to just use relative paths.
For example, if our image is stored in thestatic/images/
folder, we can refer to it like this in the HTML template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Flask Website with Images</title>
</head>
<body>
<h1>Welcome to My Flask Website</h1>
<p>Here is an example image:</p>
<img src="{{ url_for('static', filename='images/') }}" alt="Example Image">
<!-- Or use a relative path,If the image is in thestatic/images/file -->
<!-- <img src="/static/images/" alt="Example Image"> -->
</body>
</html>
Note that two methods of referencing images are shown here:
- utilization
url_for
function, which is the recommended way for Flask to handle path and URL changes. - Using relative paths, this approach is simpler, but in some cases (e.g., when the application is deployed on a subpath) you may encounter problems.
(iv) Running a Flask application
Make sure our Flask app is running and then visit our web page. We can see the referenced image displayed on the webpage.
(v) Commissioning and modifications
If the image is not displayed correctly, check the following points:
- assure
static
The paths to the folders and image files are correct. - Ensure that the HTML template is correctly using the
<img>
labels andsrc
Properties. - Clear your browser cache to make sure we're seeing the latest image files.
- Check the permissions of the image files to make sure the web server can access them.
- Use your browser's developer tools to check for any errors or warnings, especially about image loading failures.
With the above steps, we were able to successfully add and display images in our Flask project.