Getting Started with Python Programming: Building Your First Web Application

Introduction

Welcome to this blog - "Introduction to Python Programming: Building Your First Web Application". Whether you are a beginner or a developer with some programming foundation, I believe you can gain knowledge and inspiration from this article.

Python is a widely used high-level programming language known for its concise syntax and powerful functions. Its application fields are very wide, from data analysis, machine learning, to network programming, web development, to system scripting, Python has important applications. Python's concise and easy-to-read syntax makes it an ideal choice for beginners, while Python's rich libraries and frameworks also enable professional developers to develop applications quickly and efficiently.

In this post, we will focus on how to use Python for web development. Our goal is to create a simple but fully functional web application. We'll start by covering the basics of Python, and then dive into how to create web applications using Python's Flask framework. We will also introduce how to extend the functionality of web applications, including database operations, form processing, user authentication, etc., and finally we will learn how to test and deploy web applications.

If you are a Python beginner, don't worry. We'll explain each step in as much detail as possible to make sure you can understand and follow along. If you already have some Python experience, I believe you can also learn new knowledge and skills through this article. Regardless of your experience, I recommend you give it a try yourself, because doing is the best way to learn.

So, let's get started!

Table of contents

Introduction

1. Python basics

1.1 Python installation and environment configuration

1.2 Python basic syntax

Two advanced Python

2.1 Lists, Dictionaries, and Sets

2.2 Functions and classes

2.3 Modules and packages

Three basics of web development

3.1 How web applications work

3.2 HTTP Protocol Basics

Four use Flask to create a web application

4.1 Introduction and installation of Flask

4.2 Hello World application

4.3 Routing and view functions

4.4 Templates and static files

Five use Flask-SQLAlchemy to process the database

5.1 Introduction and installation of Flask-SQLAlchemy

5.2 Configuration database

5.3 Defining the model

5.4 Query data

5.5 Insert, update and delete data

Six use Flask-WTF to process the form

6.1 Introduction and installation of Flask-WTF

6.2 Define the form

6.3 Rendering the form

6.4 Working with forms

Seven uses Flask-Login to handle user authentication

7.1 Introduction and installation of Flask-Login

7.2 User Model

7.3 Login and logout

7.4 Protected View

Eight Use Flask-Bootstrap to increase the aesthetics of web applications

8.1 Introduction and installation of Flask-Bootstrap

8.2 Using Bootstrap

8.3 Custom Bootstrap

Nine deployment Flask application

9.1 Introduction and installation of Gunicorn

9.2 Running a Flask application with Gunicorn

9.3 Introduction and installation of Nginx

9.4 Configure Nginx


1. Python basics

Before we start creating web applications, let's make sure you have Python installed and the proper environment set up. Below we will cover the installation and basic syntax of Python.

1.1 Python installation and environment configuration

The installation process for Python varies slightly depending on the operating system. In general, you can download the latest version of Python from the official Python website and install it. At the same time, you can also use a Python distribution like Anaconda, which includes a Python interpreter and a series of commonly used libraries and tools.

After installing Python, you can python --versioncheck whether Python has been successfully installed by typing in the command line. If you see the version number of Python, it means that Python has been successfully installed.

To manage Python libraries and dependencies, we recommend using virtual environments. You can use Python's built-in tools venv, or use pipenvthird-party tools such as Python to create and manage virtual environments.

1.2 Python basic syntax

The syntax of Python is very concise and easy to read. Below we will briefly introduce Python's variables, data types, and control structures.

  • Variables : In Python, you don't need to declare the type of a variable. You just need to use the equal sign =to assign a value, and Python will automatically infer the type of the variable. For example, x = 10, y = "Hello, world!".

  • Data types : Python has a variety of built-in data types, including integers ( int), floating point numbers ( float), strings ( str), lists ( ) list, tuples ( tuple), dictionaries ( dict), and collections ( set).

  • Control structures : Python supports common control structures, including ifconditional statements, loops, and forerror handling.whiletry/except

Here are some simple examples:

# 变量和数据类型
x = 10
y = 3.14
z = "Hello, world!"
print(x, y, z)

# if条件语句
if x > 0:
    print("x is positive")

# for循环
for i in range(5):
    print(i)

# try/except错误处理
try:
    print(10 / 0)
except ZeroDivisionError:
    print("Cannot divide by zero")

The above is the basic knowledge of Python. Next, we'll dig deeper into Python and start creating our web application.

Two advanced Python

Before we start creating web applications, let's take a deeper look at Python's advanced features, including lists, dictionaries, sets, functions, classes, modules, and packages.

2.1 Lists, Dictionaries, and Sets

Python has several built-in data structures, including lists ( list), dictionaries ( dict), and sets ( set). They are very powerful and help you organize and process data efficiently.

  • List : A list is an ordered collection of elements that can contain elements of any type, including other lists. You can access the elements in the list by index, and you can modify the list with methods such as append, insert, and so on.remove

  • Dictionary : A dictionary is a collection of key-value pairs, where the keys must be of immutable types, such as integers, strings, or tuples, and the values ​​can be of any type. You can use [key]to access the values ​​in the dictionary, or use getthe method to get a default value.

  • Set : A set is an unordered collection of elements that do not contain duplicates. You can use addand removemethods to add or remove elements, and you can also use set operations such as union, intersection, difference, etc.

2.2 Functions and classes

Functions and classes are important concepts in Python, and they are the main way to achieve code reuse and encapsulation.

  • Function : A function is a named, reusable piece of code. You can defdefine a function using keywords, and then call the function using the function name and parentheses.

  • Classes : Classes are a way of defining new types. You classdefine a class using keywords, and then use the class name and parentheses to create an instance of the class. A class can contain properties and methods, where properties are the state of the class and methods are the behavior of the class.

2.3 Modules and packages

Modules and packages are how Python organizes its code. A module is a file containing Python code, and a package is a directory containing modules and other packages.

  • Modules : You can use importkeywords to import a module, and then use the module name and dot to access functions and classes in the module.

  • Packages : Packages are a way of organizing modules. A package is a __init__.pydirectory containing files, and you can import modules within the package using the package name followed by a dot.

These are the advanced features of Python. Next, we'll start learning how to create web applications using Python's Flask framework.

Three basics of web development

Before we start creating web applications, let us understand how web applications work and the basics of the HTTP protocol.

3.1 How web applications work

A web application is a client-server application. In this model, the user sends a request to the server through the browser (client), the server processes the request and returns a response to the client, and the client displays the response to the user.

A web application usually includes the following parts:

  1. Client : The client is usually a browser, such as Chrome or Firefox. The client is responsible for sending HTTP requests and receiving HTTP responses, and then displaying the response content to the user.

  2. Server : A server is a computer that hosts a web application. The server is responsible for receiving HTTP requests, processing the requests and generating HTTP responses, and sending the responses back to the clients.

  3. Database : The database is used to store the data of the web application. The server can query the database to get or update data, and then include the data in the HTTP response.

3.2 HTTP Protocol Basics

HTTP is the abbreviation of HyperText Transfer Protocol, which is the main protocol used by Web applications. The HTTP protocol defines the format and rules for communication between clients and servers.

An HTTP request consists of the following parts:

  1. Request line : The request line includes the request method (such as GET, POST), request URI and HTTP version.

  2. Request header : The request header includes some metadata describing the request, such as Host, User-Agent, Accept, Cookie, etc.

  3. Request body : The request body contains the content of the request, such as form data, files, etc. Not all requests have a request body.

An HTTP response consists of the following parts:

  1. Status line : The status line includes HTTP version, status code and status text.

  2. Response header : The response header includes some metadata describing the response, such as Content-Type, Content-Length, Set-Cookie, etc.

  3. Response body : The response body contains the content of the response, such as HTML, JSON, images, etc.

The above is the basic knowledge of web development. Next, we'll start learning how to create web applications using Python's Flask framework.

Four use Flask to create a web application

Flask is a lightweight Python web framework that is simple and easy to use, but also powerful and flexible. Next, we'll walk through how to create a simple web application with Flask.

4.1 Introduction and installation of Flask

Flask's design philosophy is "micro-core": it only contains the most basic web functions, such as routing and request response processing, and other functions such as database operations, form processing, user authentication, etc. are implemented through extensions. This makes Flask very flexible, you can choose and combine different extensions according to your needs.

You can use pip to install Flask:

pip install flask

 

4.2 Hello World application

Creating a Flask application is very simple. First, you need to import the Flask class, then create an instance of the Flask application. Then, you can use decorators to define routes and view functions. Finally, you can use runthe method to start the Flask application.

Here's an example "Hello, World!" application:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return "Hello, World!"

if __name__ == '__main__':
    app.run()

 

In this example, we define a route /. When a user visits this URL, Flask will call helloa function and return the value as the content of the HTTP response.

4.3 Routing and view functions

In Flask, a route is a mapping of URL patterns to view functions. You can @app.routedefine routes using decorators.

View functions are functions that process HTTP requests and generate HTTP responses. The view function can return a string, which Flask will convert into an HTTP response and set the appropriate Content-Type header.

You can define multiple routes and view functions, and each route can correspond to one or more HTTP methods (such as GET, POST).

4.4 Templates and static files

Although view functions can return strings directly, in actual web applications, we usually need to return more complex HTML pages. To generate HTML more conveniently, Flask supports the use of Jinja2 templates.

A template is an HTML file that contains special syntax. You can use variables, loops, conditions, and other statements in the template. You can use render_templatefunctions to render templates and generate HTML.

Static files are files that do not need to be dynamically generated in web applications, such as CSS, JavaScript, pictures, etc. You can put the static files in the application staticdirectory, and then use url_forthe function to generate the URL of the static files.

The above are the basic steps to create a web application using Flask. Next, we will learn how to extend the functionality of Web applications, including database operations, form processing, user authentication, and more.

Five use Flask-SQLAlchemy to process the database

In web applications, we usually need to store and manipulate data, such as user information, product information, and so on. These data are usually stored in databases. Flask-SQLAlchemy is a Flask extension that provides advanced SQLAlchemy support, allowing us to more easily operate databases in Flask applications.

5.1 Introduction and installation of Flask-SQLAlchemy

Flask-SQLAlchemy is an extension that provides SQLAlchemy support for Flask. SQLAlchemy is a Python ORM framework that abstracts low-level SQL operations into high-level Python class and object operations, allowing us to operate the database in a Pythonic way.

You can install Flask-SQLAlchemy using pip:

pip install flask_sqlalchemy

 

5.2 Configuration database

Before creating a Flask-SQLAlchemy instance, you need to set the database URL in the Flask application configuration. The format of the database URL is as follows:

dialect+driver://username:password@host:port/database

 For example, if you use a PostgreSQL database, and the database is running locally on port 5432, the username and password are both postgres, and the database name is myapp, then the database URL is:

postgresql://postgres:postgres@localhost:5432/myapp

5.3 Defining the model

In Flask-SQLAlchemy, database tables are defined by Python classes, which are called model classes. The model class inherits from db.Model, and each attribute corresponds to a column of a table.

Here is an example of a model class:

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

5.4 Query data

You can use SQLAlchemy's query API to query data. The Query API provides a Pythonic way to write SQL queries.

Here are some examples of query APIs:

# 查询所有用户
users = User.query.all()

# 查询第一个用户
user = User.query.first()

# 根据ID查询用户
user = User.query.get(1)

# 根据用户名查询用户
user = User.query.filter_by(username='john').first()

5.5 Insert, update and delete data

You can create instances of model classes to insert data, modify instance properties to update data, and call db.session.deletemethods to delete data. All changes need to db.session.commitbe committed to the database by calling a method.

Here are some examples of inserting, updating and deleting data:

# 插入数据
user = User(username='john', email='[email protected]')
db.session.add(user)
db.session.commit()

# 更新数据
user.username = 'johnny'
db.session.commit()

# 删除数据
db.session.delete(user)
db.session.commit()

The above are the basic steps to use Flask-SQLAlchemy to process the database. Next, we'll learn how to handle forms with Flask-WTForms.

Six use Flask-WTF to process the form

In web applications, we often need to process forms, such as login forms, registration forms, search forms, etc. Flask-WTF is an extension that provides WTForms support for Flask, which allows us to more easily process forms in Flask applications.

6.1 Introduction and installation of Flask-WTF

Flask-WTF is an extension that provides WTForms support for Flask. WTForms is a Python form library that helps us generate and validate forms.

You can install Flask-WTF using pip:

pip install flask_wtf

6.2 Define the form

In Flask-WTF, forms are defined by Python classes, which are called form classes. The form class inherits from flask_wtf.FlaskForm, and each property corresponds to a form field.

The following is an example of a form class:

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, Email, Length

class LoginForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    submit = SubmitField('Log In')

6.3 Rendering the form

You can use the macros provided by WTForms in templates to render forms. This can help you quickly generate HTML for forms.

Here is an example template:

{% from "_formhelpers.html" import render_field %}

<form method="POST">
    {
   
   { form.hidden_tag() }}
    {
   
   { render_field(form.username) }}
    {
   
   { render_field(form.password) }}
    {
   
   { render_field(form.submit) }}
</form>

6.4 Working with forms

In view functions, you can use form.validate_on_submit()methods to check if the form was submitted and validated. This method returns True if the form is submitted and all fields are validated, otherwise it returns False.

The following is an example of a view function:

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        # TODO: 登录用户
        return redirect(url_for('index'))
    return render_template('login.html', form=form)

The above are the basic steps of using Flask-WTF to process forms. Next, we'll learn how to handle user authentication with Flask-Login.

Seven uses Flask-Login to handle user authentication

User authentication is an important function in web applications, which allows users to log in to the application and keep them logged in. Flask-Login is an extension that provides user authentication support for Flask, which allows us to more easily handle user authentication in Flask applications.

7.1 Introduction and installation of Flask-Login

Flask-Login provides a friendly way to manage user sessions, which can help us implement functions such as user login, logout, and remember me.

You can use pip to install Flask-Login:

pip install flask_login

7.2 User Model

Before using Flask-Login, you need to implement a few methods in your User model, including is_authenticated, is_active, is_anonymousand get_id.

The following is an example of a User model:

from flask_login import UserMixin

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, nullable=False)
    password_hash = db.Column(db.String(128))

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

7.3 Login and logout

You can use login_usera function to log a user in and logout_usera function to log a user out.

Here are examples of login and logout view functions:

from flask_login import login_user, logout_user

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('Invalid username or password')
            return redirect(url_for('login'))
        login_user(user, remember=form.remember_me.data)
        return redirect(url_for('index'))
    return render_template('login.html', form=form)

@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('index'))

7.4 Protected View

You can use login_requireddecorators to protect views so that only logged in users can access them.

The following is an example of a protected view function:

from flask_login import login_required

@app.route('/edit_profile')
@login_required
def edit_profile():
    # ...

The above are the basic steps to handle user authentication with Flask-Login. Next, we'll learn how to use Flask-Bootstrap to enhance the aesthetics of web applications.

Eight Use Flask-Bootstrap to increase the aesthetics of web applications

Bootstrap is a popular front-end framework, which includes a variety of pre-made CSS styles and JavaScript plug-ins, which can help us quickly build beautiful web interfaces. Flask-Bootstrap is an extension that provides Bootstrap support for Flask. It embeds all the static files of Bootstrap into the Flask application.

8.1 Introduction and installation of Flask-Bootstrap

Flask-Bootstrap allows you to easily use Bootstrap in your Flask application. It not only provides all the static files of Bootstrap, but also provides some Jinja2 template macros, which can help you quickly generate Bootstrap HTML.

You can install Flask-Bootstrap using pip:

pip install flask_bootstrap

8.2 Using Bootstrap

After installing Flask-Bootstrap, you can use bootstrap.load_css()and in your templates bootstrap.load_js()to load Bootstrap's CSS and JavaScript. You can also use bootstrap.quick_form()macros to quickly generate Bootstrap-style forms.

Here is an example template using Bootstrap:

{% extends "bootstrap/base.html" %}

{% block title %}My App{% endblock %}

{% block navbar %}
<div class="navbar navbar-inverse" role="navigation">
    <div class="container">
        <div class="navbar-header">
            <a class="navbar-brand" href="{
   
   { url_for('index') }}">My App</a>
        </div>
    </div>
</div>
{% endblock %}

{% block content %}
<div class="container">
    <h1>Welcome to My App!</h1>
    <form method="POST">
        {
   
   { bootstrap.quick_form(form) }}
    </form>
</div>
{% endblock %}

8.3 Custom Bootstrap

Although Bootstrap provides preset styles, you may need to customize some styles to meet your needs. You can create your own CSS file and then load this CSS file in the template.

You can use url_forfunctions to generate URLs for static files. For example, if your CSS file is located static/cssin a directory, you can generate the URL of the CSS file like this:

<link rel="stylesheet" href="{
   
   { url_for('static', filename='css/my.css') }}">

The above are the basic steps to increase the aesthetics of web applications using Flask-Bootstrap. Next, we'll learn how to deploy a Flask application.

Nine deployment Flask application

So far, we have completed the development of the web application, and the next step is to deploy it to the server so that more users can access it. In this section, we will briefly introduce how to use Gunicorn and Nginx to deploy Flask applications.

9.1 Introduction and installation of Gunicorn

Gunicorn is a Python WSGI HTTP server, which has excellent concurrency capabilities and is very suitable for hosting Python web applications.

You can install Gunicorn using pip:

pip install gunicorn

9.2 Running a Flask application with Gunicorn

You can use Gunicorn's command line interface to run your Flask application. You need to provide the import path and port number of the application.

Here is an example of running a Flask application:

gunicorn -w 4 -b 127.0.0.1:5000 myapp:app

In this example, -w 4it means to use 4 worker processes, -b 127.0.0.1:5000means to listen to the local port 5000, which myapp:appis the import path of the application.

9.3 Introduction and installation of Nginx

Nginx is a high-performance HTTP and reverse proxy server, which can act as a load balancer and HTTP cache. Here, we use Nginx as a reverse proxy server to forward user requests to Gunicorn.

You can use your package manager to install Nginx, for example on Ubuntu you can use apt to install Nginx:

 

sudo apt update
sudo apt install nginx

9.4 Configure Nginx

You need to create an Nginx configuration file to tell Nginx how to forward requests. The following is an example configuration file:

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://127.0.0.1:5000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

In this configuration file, listen 80;it means listening on port 80, server_name example.com;means the name of the server is example.com, proxy_pass http://127.0.0.1:5000;and means forwarding the request to the local port 5000.

The above are the basic steps to deploy Flask application using Gunicorn and Nginx. In the actual production environment, you may also need to configure HTTPS, use the process manager to manage the Gunicorn process, and so on.

So far, we have completed the whole process from development to deployment.

Guess you like

Origin blog.csdn.net/a871923942/article/details/130577692