SoFunction
Updated on 2025-03-03

Python Guide to writing a website using Flask

1. How to write a website using Flask

(I) Install Flask

First, we need to make sure that Flask is installed in our Python environment. We can use pip (Python's package manager) to install it.

pip install Flask

(II) Create Flask application

  • Create a project directory
    Create a new directory on our computer to store our Flask projects.
  • Create the main application file
    Create a name in the project directory(or whatever name we like) the file and add the following code:
# 
from flask import Flask, render_template, request
 
app = Flask(__name__)
 
# Configuration item (optional)['DEBUG'] = True  # Turn on debug mode, so that the server will automatically restart after the code changes. 
#Route and view functions@('/')
def home():
    return render_template('')  # Render template file 
@('/greet', methods=['GET', 'POST'])
def greet():
    if  == 'POST':
        name = ['name']  # Get data from the form        return f'Hello, {name}!'
    return render_template('')  # Render form template 
if __name__ == '__main__':
    (host='0.0.0.0', port=5000)  # Run on all network interfaces and listen on port 5000

(III) Create HTML template

  • Create a template directory
    Create a name in the project directorytemplatesfolder.
  • Add a template file
    existtemplatesCreate two HTML files in the folder:and

<!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" rel="external nofollow" >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) Run Flask application

  • Open the terminal
    Open our command line interface (terminal, command prompt, etc.).
  • Navigate to the project directory
    usecdCommands navigate to the project directory we created.
  • Run the application
    Run the following command in the terminal to start the Flask application:
python 
  1. Visit the website
    Open our web browser and accesshttp://localhost:5000/. We will see the page "Welcome to My Flask Website". Click on the “Greet Someone” link and we will be taken to the form page. Fill out the form and submit it and we will see a greeting message.

(V) Debugging and deployment

  • debug:If we turn on debug mode (['DEBUG'] = True), when we modify the code and save the Flask app automatically restarts so that we immediately see the effect of the changes.
  • deploy: Deploying Flask applications to production environments usually involves the use of WSGI servers (such as Gunicorn or uWSGI) and reverse proxying (such as Nginx or Apache). This is beyond the scope of this simple guide, but we can consult Flask's official documentation or search for related tutorials to learn more.

Through the above steps, we have successfully written a simple website using Flask. Now we can continue to expand our website and add more routes, templates, and logic to meet our needs.

2. 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 to add and use stylesheets in a Flask project:

(I) Create a static folder

Flask has a convention that all static files (such as CSS, JavaScript, pictures, etc.) are placed in the namestaticin the folder. If this folder is not available in our project directory, please create one.

(II) Add style sheet file

existstaticIn the folder, create a new CSS file, such as

(III) Write CSS code

existWrite our CSS code in the file. For 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) Link style sheet in HTML template

Now, we need to link this CSS file in the HTML template. use<link>Tags andhrefThe property is set to the relative path of the stylesheet (fromstaticfolder starts).

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='') }}" rel="external nofollow" >
</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 that this is used here{{ url_for('static', filename='') }}to generate the URL of the stylesheet. This is a helper function provided by Flask, which ensures that our static file path is correct, even if we deploy the app to a different URL or subpath.

(V) Run Flask application

Make sure our Flask app is running and then visit our web page. We can see the web page with CSS style applied.

(VI) Debugging and modification

If the style is not applied correctly, check the following points:

  • make surestaticFolders andThe file path is correct.
  • Make sure it is used correctly in HTML templates<link>Label.
  • Clear the browser cache to make sure we are seeing the latest CSS file.
  • Use the browser's developer tools (usually open by pressing F12 or right-clicking on the page and selecting "Check") to check for any errors or warnings.

Through the above steps, we were able to successfully add and use style sheets in our Flask project.

3. How to add pictures in Flask

Adding images in Flask is similar to adding stylesheets, we need to place the image files in the specified static folder and reference them in the HTML template. Here are the detailed steps:

(I) Create or confirm static folder

Make sure there is a name in our Flask project calledstaticfolder. This folder is used to store all static files, including pictures, CSS files, JavaScript files, etc.

(II) Add picture files

Put our image files (e.g.) Put it instaticin folder. We can create a subfolder in this folder to organize our pictures, for examplestatic/images/

(III) Quoting pictures in HTML template

In our HTML templates, use<img>Tags to quote pictures. Since the pictures are storedstaticIn folders, we need to refer to them using relative paths. Flask provides a help functionurl_forTo generate URLs for static files, but for images, it is usually easier and more intuitive to use relative paths directly.

For example, if our pictures are stored instatic/images/In the folder, we can reference it in the HTML template like this:

&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;title&gt;My Flask Website with Images&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;h1&gt;Welcome to My Flask Website&lt;/h1&gt;
    &lt;p&gt;Here is an example image:&lt;/p&gt;
    &lt;img src="{{ url_for('static', filename='images/') }}" alt="Example Image"&gt;
    &lt;!-- Or use relative paths,If the picture isstatic/images/In the folder --&gt;
    &lt;!-- &lt;img src="/static/images/" alt="Example Image"&gt; --&gt;
&lt;/body&gt;
&lt;/html&gt;

Note that there are two ways to quote pictures:

  • useurl_forFunctions, this is the way Flask recommends because it can handle path and URL changes.
  • Using relative paths, this approach is simpler, but in some cases, such as when the application is deployed on a subpath, you may experience problems.

(IV) Run Flask application

Make sure our Flask app is running and then visit our web page. We can see the referenced image displayed on the web page.

(V) Debugging and modification

If the image does not display correctly, check the following points:

  • make surestaticThe paths to folders and image files are correct.
  • Make sure it is used correctly in HTML templates<img>Tags andsrcproperty.
  • Clear the browser cache to make sure we are seeing the latest image files.
  • Check the permissions of image files to make sure that the web server can access them.
  • Use the browser's developer tools to check for any errors or warnings, especially about errors that fail to load images.

Through the above steps, we are able to successfully add and display pictures in the Flask project.

The above is the detailed content of Python's code guide for writing a website using Flask. For more information about writing a website using Python Flask, please follow my other related articles!