[Master Python in 100 days] Day47: Python network programming_Web development: web server, front-end basics and static server

Table of contents

1 Network programming and web programming

1.1 Network programming

1.2 web programming 

1.3 Basic principles of front-end and back-end interaction

2 Web development basics

2.1 HTTP protocol

2.2 Web server

2.3 Front-end basics

2.3.1 HTML (Hypertext Markup Language)

2. 3.2 CSS (Cascading Style Sheets)

2.3.3 JavaScript

2.4 Static server

2.4.1 Why use static server

2.4.2 Functions of static server

2.4.3 Python programming to implement a static server


1 Network programming and web programming

1.1 Network programming

        Network programming refers to the process of using a programming language (such as Python) to implement network communication. It covers the underlying network protocols and communication details and can be used to build various types of network applications. Network programming mainly involves socket programming, which implements network connections, sending and receiving data and other operations by creating socket objects. Network programming can be used to build various types of network applications, such as chat programs, file transfer, remote command execution, etc.

1.2 web programming 

        Web programming is more focused on developing web-based applications, that is, applications that use the HTTP protocol to communicate. Web programming focuses on developing websites, web applications, or web services. It includes two aspects: front-end development and back-end development:

- Front-end development : Front-end development involves using technologies such as HTML, CSS, and JavaScript to implement the design and interaction logic of user interfaces. Front-end developers are typically responsible for implementing the layout, styling, and user interaction aspects of web pages.

- Backend Development: Backend development involves writing server-side code that handles HTTP requests and generates responses. Back-end developers usually use programming languages ​​(such as Python, Java, PHP, etc.) and frameworks (such as Django, Flask) to build server-side logic and handle database operations, business logic, etc.

Front-end and back-end instructions 

The goal of Web programming is to build applications that can be accessed and used in a browser, including Web websites, Web applications, and Web services. It typically communicates via the HTTP protocol and uses various technologies and frameworks to simplify the development process.

To sum up, network programming is a broader category that covers all aspects of network communication; while web programming is a specific application area that focuses on developing web-based applications.

1.3 Basic principles of front-end and back-end interaction

        In front-end and back-end interaction, the basic principle is to transmit and communicate data through the HTTP protocol. The following are the basic steps for front-end and back-end interaction: 

  1. The client sends a request: the front-end sends an HTTP request to the server through the browser. Requests can be of different types, such as GET, POST, etc., and may be accompanied by request parameters or form data.

  2. The server processes the request: After receiving the request, the server finds the corresponding processing logic (back-end code) based on the requested URL path and parameters. The server may access databases, execute business logic, etc.

  3. The server returns a response: After the backend processing is completed, an HTTP response is generated and the data or results are returned to the frontend. The response can contain different content, such as HTML pages, JSON data, etc.

  4. Client processing response: After receiving the response from the server, the front end processes it according to the content and status code of the response. If it is an HTML page, the front end may render the page; if it is JSON data, the front end may parse and display the data.

During the front-end and back-end interaction process, other technologies can also be used to enhance interaction capabilities, such as:

  • Ajax: Through asynchronous JavaScript and XML (or JSON) requests, the front end can exchange data with the server without refreshing the entire page. This can achieve partial updates and improve user experience.

  • WebSocket: WebSocket provides a two-way communication mechanism, so that the server can actively push data to the client without requiring the client to initiate a request. This is useful for real-time data push and chat applications.

To sum up, the basic principle of front-end and back-end interaction is to transmit requests and responses through the HTTP protocol, and other technologies can be used to enhance interaction capabilities. The backend is responsible for processing requests, providing data or results, and the frontend is responsible for sending requests, receiving responses, and displaying them.

2 Web development basics

2.1 HTTP protocol

         HTTP (Hypertext Transfer Protocol) is a protocol used to transfer data between clients and servers. It is the basis of web communication and supports request and response models. The HTTP protocol defines the format of data, the transmission method, and how to communicate with the server.

The following is an example of a simple HTTP request and response:

HTTP request example:

GET /index.html HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0

HTTP response example:

HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 123
<html>
<head>
<title>Welcome to Example</title>
</head>
<body>
...
</body>
</html>

2.2 Web server

        A web server is a computer or software that receives HTTP requests from clients (such as browsers) and sends corresponding HTTP responses. It is responsible for hosting and serving the resources of the web application. Popular web server software includes Apache, Nginx, and Microsoft IIS.

Here is a simple Python code example to create a simple web server using the built-in HTTP server:

import http.server
import socketserver

PORT = 8000

Handler = http.server.SimpleHTTPRequestHandler

# 使用 socketserver 创建一个 TCP 服务器,并指定端口和处理程序
with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print("Serving at port", PORT)
    httpd.serve_forever()
  1. import http.server: Import a module in the Python standard library http.server, which provides an HTTP server and related functions.

  2. import socketserver: Imports a module from the Python standard library socketserver, which provides classes for creating various types of servers.

  3. PORT = 8000: Specify the port number that the server will listen on.

  4. Handler = http.server.SimpleHTTPRequestHandler: SimpleHTTPRequestHandlerAssign a class to Handlera variable. This handler class is used to handle HTTP requests and return corresponding static files.

  5. with socketserver.TCPServer(("", PORT), Handler) as httpd::Creates a TCP server using socketserverthe module's TCPServerclasses, binds to the specified host (an empty string means binding to all available network interfaces) and port, and sets the handler to Handler.

  6. print("Serving at port", PORT): Prints a message when the server starts, showing the port the server is listening on.

  7. httpd.serve_forever(): Starts a server and keeps it running, handling incoming requests indefinitely.

You can save this Python code as .pya file and run it from the command line. Once running, you will be able to access via a browser http://localhost:8000and view the static files served by the server in the browser.

2.3 Front-end basics

         Front-end development involves creating the interface that users see and interact with in a browser. Front-end basics include HTML (structure), CSS (style) and JavaScript (interaction).

2.3.1 HTML (Hypertext Markup Language)

         HTML is a markup language used to create the structure of web pages. It consists of a series of tags that define different elements in a web page, such as titles, paragraphs, images, etc. HTML provides a structured way to display content.

Here is a simple HTML example for creating a web page with headings and paragraphs:

<!DOCTYPE html>
<html>
<head>
  <title>HTML Example</title>
</head>
<body>
  <h1>Welcome to My Website</h1>
  <p>This is a sample paragraph.</p>
</body>
</html>

Use a text editor (such as Notepad, Visual Studio Code, etc.) to create a file .htmlwith the extension name. In this example, create a new test.html file in pycharm and open it with the chrome browser as follows:

2. 3.2 CSS (Cascading Style Sheets)

        CSS is used to add styles to HTML elements, such as layout, colors, fonts, etc. It allows developers to separate style from content, allowing for better maintainability and style consistency.

Here is a simple CSS example for styling headings and paragraphs:

/* 在 <head> 部分引入样式表 */
<style>
  h1 {
    color: blue;
    font-size: 24px;
  }
  p {
    font-size: 16px;
    line-height: 1.5;
  }
</style>

The above effect changes as follows:

2.3.3 JavaScript

        JavaScript is a scripting language used to add interactive and dynamic behavior. It can change the content, style and behavior of a web page, allowing users to interact with the page.

Here's a simple JavaScript example for changing the content of a title when a button is clicked:

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Example</title>
</head>
<body>
  <h1 id="title">Hello, World!</h1>
  <button onclick="changeText()">Click Me</button>

  <script>
    function changeText() {
      var titleElement = document.getElementById("title");
      titleElement.innerHTML = "Button Clicked!";
    }
  </script>
</body>
</html>

The effect is as follows:

2.4 Static server

        A static server is a web server whose main function is to provide static resources, such as HTML files, CSS style sheets, JavaScript scripts, images, videos, etc. These resources are prepared in advance on the server and sent to the client as is without any server-side processing.

        Static servers are typically used to host and serve content that does not need to be dynamically generated to improve performance and efficiency.

2.4.1 Why use a static server:

        Static servers are suitable for scenarios that do not require data processing or database queries based on user requests. Because static resources do not change on every request, they can be sent directly through a static server, improving response times and performance.

2.4.2 Functions of the static server:

  • Serving static resources : Static servers are mainly used to host and serve static resources such as HTML, CSS, JavaScript, images and other files.
  • Cache management : Static servers usually support a caching mechanism that allows the browser to reuse the local cache when requesting the same resource multiple times.
  • Compression and optimization : Static servers can compress and optimize resources to reduce file size and thereby increase loading speed.

2.4.3 Python programming to implement a static server

        When you need to create a static server to host static HTML, CSS, JavaScript files and other resources, you can use python files to implement it, or you can use Node.js and the Express framework to implement it.

The following is an example of implementing a static server using python programming:

  1. Create project directory: First, create a new folder as the project directory in the folder of your choice. In the project directory, create an index.htmlHTML file named , a styles.cssCSS file named and a script.jsJavaScript file named . as follows:



    2.  index.html: In index.htmlthe file, write a simple HTML page, referencing the CSS and JavaScript files.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="styles.css">
  <title>Static Server Example</title>
</head>
<body>
  <h1>Hello from Static Server</h1>
  <p>This is a simple example of a static server.</p>
  <script src="script.js"></script>
</body>
</html>

 3.  styles.css: In styles.cssthe file, add some simple style rules.

body {
  font-family: Arial, sans-serif;
  text-align: center;
}

h1 {
  color: #333;
}

p {
  color: #666;
}

4. script.js: In script.jsthe file, add a simple JavaScript script.

console.log("Hello from script.js");

5. Static server code: Create a Python file named in the project directory server.pyand add the following code:

import http.server
import socketserver

PORT = 8000

Handler = http.server.SimpleHTTPRequestHandler

# 使用 socketserver 创建一个 TCP 服务器,并指定端口和处理程序
with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print("Serving at port", PORT)
    httpd.serve_forever()

6. Run the server: Navigate to the project directory on the command line and run the following command to start the server.

python server.py

The output is as follows:

 7. Visit the static page: Open the browser and visit http://localhost:8000, you should be able to see the static page you created.

The effect is as follows:

        This example demonstrates how to use Python's http.servermodules to create a simple static file server and display your HTML, CSS, and JavaScript files in the browser. Please make sure all files are in the same project directory and follow the steps above to run the server. This is a very basic example, you can add more features and customization if needed.

Guess you like

Origin blog.csdn.net/qq_35831906/article/details/132503215