[Xiao Mu learns Python] Summary of various web servers (Python, Node.js, PHP, httpd, Nginx)

1. Web server

The term web server can refer to hardware or software, or the entirety of them working together.

Insert image description here
Basically, when the browser needs a file hosted on a web server, the browser requests the file via HTTP. When the request reaches the correct web server (hardware), the HTTP server (software) receives the request, finds the requested document (if the document does not exist, a 404 response will be returned), and sends the document through HTTP sent to the browser.

The web server provides HTTP (Hypertext Transfer Protocol, Hypertext Transfer Protocol) support. As its name implies, HTTP explicitly proposes how to transfer hypertext (linked web documents) between two computers.

A protocol is a set of rules for communication between two computers. HTTP is a textual, stateless protocol.

2、Python

2.1 Introduction

https://www.python.org/

Python is an interpreted, object-oriented, high-level programming language with dynamic data types.

  • Python is an interpreted language: this means there is no compilation part of the development process. Similar to PHP and Perl languages.
  • Python is an interactive language: this means that you can execute code directly after a Python prompt >>>.
  • Python is an object-oriented language: This means that Python supports object-oriented style or programming techniques in which code is encapsulated in objects.
    Insert image description here

2.2 Installation

https://www.python.org/downloads/windows/

Insert image description here

2.3 Use

2.3.1 http.server (command)

Python comes with a simple server program that can easily open the service.
In python3, change the original SimpleHTTPServer command to http.server. The usage method is as follows:

cd test
python -m http.server

# 如果不使用默认端口,可在开启时附带端口参数
python -m http.server 8001

# (-b 绑定ip,不指定的话默认是本机ip)
python -m http.server -b 127.0.0.1 

# 下面的命令使用一个特定的目录:
python -m http.server --directory /tmp/

The command line execution is as follows:

http://127.0.0.1:8000

If it is successfully enabled, "Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ..." will be output, indicating that the service is enabled on port 8000 of the local machine.
Insert image description here

Browser access is as follows:
You can use http://127.0.0.1:8000/ to view the web page files in the www directory. If there is no index.html, the files in the directory will be displayed.

http://127.0.0.1:8000

Insert image description here
If you need to run in the background, you can add the "&" symbol after the command. Ctrl+C will not close the service, as follows:

python -m http.server &

If you want to maintain the service, add nohup before the command to ignore all hangup signals, as follows:

nohup python -m http.server 8001

2.3.2 socketserver

import http.server
import socketserver

PORT = 8000

Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print("serving at port", PORT)
    httpd.serve_forever()
  • The code is executed as follows:
    Insert image description here
  • Browser access is as follows:
http://127.0.0.1:8000

Insert image description here

2.3.3 flask

Flask is a lightweight web application framework written in Python. Its WSGI toolbox uses Werkzeug and its template engine uses Jinja2. Flask uses the BSD license.
Flask is also called a "microframework" because it uses a simple core and uses extensions to add other functionality. Flask does not have a default database or form validation tool.

https://flask.net.cn/
Insert image description here

  • Installation library
pip install flask
  • app.py
from flask import Flask
app = Flask(__name__)

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

if __name__ == '__main__':
	app.run()
  • The script code is executed as follows:

Insert image description here

  • Browser access is as follows:
http://127.0.0.1:5000

Insert image description here
Or execute the script file app.py through the following command.

flask run

Insert image description here

2.3.4 in the fastener

FastAPI is a modern, fast (high-performance) web framework for building APIs using Python 3.6+ and based on standard Python type hints.
FastAPI is extremely performant on par with NodeJS and Go (thanks to Starlette and Pydantic).
FastAPI framework, high performance, easy to learn, efficient coding, production-ready

https://fastapi.tiangolo.com/zh/
Insert image description here

  • Installation library
pip install fastapi
pip install fastapi[all]
pip install uvicorn 
  • main.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {
    
    "Hello": "World"}

Execute the script file through the following command:

uvicorn main:app --reload

The running results are as follows:
Insert image description here
Browser access is as follows:

http://127.0.0.1:8000

Insert image description here

3、NodeJS

Insert image description here

3.1 Introduction

https://nodejs.org/zh-cn

Node.js was released in May 2009 and developed by Ryan Dahl. It is a JavaScript running environment based on the Chrome V8 engine. It uses an event-driven, non-blocking I/O model to allow JavaScript to run on the server-side development platform. It Let JavaScript become a scripting language on par with server-side languages ​​such as PHP, Python, Perl, and Ruby.

Node.js optimizes some special use cases and provides alternative APIs to make V8 run better in non-browser environments. The V8 engine executes Javascript very quickly and has very good performance. It is a platform built on the Chrome JavaScript runtime. Used to easily build network applications with fast response and easy expansion.
Insert image description here

3.2 Installation

https://nodejs.org/zh-cn
Insert image description here

3.3 Use

3.3.1 http-server (command)

http server is a simple, zero-configuration command line static http server. It's powerful enough for production use, yet simple and hackable enough for testing, local development, and learning.

Advantages of http-server: You can make any directory of static resource files into the directory of the server, completely throwing away the heavy work in the background and directly running the desired code.

  • Check the node version
node -v
npm -v

Insert image description here

  • Install http-server library
npm install -g http-server
# npm install --global http-server

Insert image description here

cd test
http-server -p 8081
# http-server -a 0.0.0.0 -p 8000

Insert image description here
You can see that the local server has been started, and you can terminate the server by typing Ctrl + C on the cmd window.
After global installation, you can view its information in cmd:

npm view http-server
npm info http-server
// or 
npm -v hs

Insert image description here

  • Available parameters for http-server:
-p 要使用的端口(默认为8080)
-a 要使用的地址(默认为0.0.0.0)
-d 显示目录列表(默认为“True”)   true / false
-i 显示autoIndex(默认为“True”)
-g或--gzip启用时(默认为“False”),它将用于./public/some-file.js.gz代替./public/some-file.jsgzip压缩版本的文件,并且该请求接受gzip编码。
-e或--ext默认文件扩展名(如果没有提供)(默认为'html'-o 启动服务器后打开浏览器窗口
-c设置缓存控制max-age头的缓存时间(以秒为单位),例如-c10  10秒(默认为'3600')。要禁用缓存,请使用-c-1。

You can also start the http-server server through npm run.
npm init -y generates the default package.json file in the folder:

npm init -y

Modify package.json as follows:

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "awesome.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js",
    "start2": "http-server -a 0.0.0.0 -p 8888",
	"serve": "http-server -p 9090 dist/"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Then enter npm start or npm run start2 in the command box:

npm run start2

Insert image description here

3.3.2 http

const http = require('http')

const PORT = 3000
const HOST = '127.0.0.1'

const server = http.createServer((req, res) => {
    
    
  res.statusCode = 200
  res.setHeader('Content-Type', 'text/plain')
  res.end('hello world, yxy!\n')
})

server.listen(PORT, () => {
    
    
  console.log(`服务器运行在 http://${
      
      HOST}:${
      
      PORT}/`)
})

or

const http = require('http');
http.createServer(function (request, response) {
    
    
    response.writeHead(200, {
    
    'Content-Type': 'text/plain; charset=UTF-8'});
    response.end('Hello World, yxy!\n');
}).listen(3000);
console.log('Server running at http://127.0.0.1:3000/');
//方式 1:
const http = require("http");
const server = http.createServer(function(req, res) {
    
    
  // ......
});
 
server.listen(3000);

//方式 2:
const http = require("http");
const server = http.createServer();
server.on("request", function(req, res) {
    
    
  // ......
});

server.listen(3000);
  • The code is executed as follows:
    Insert image description here
  • Browser access is as follows:
http://127.0.0.1:3000/

Insert image description here

3.3.3 express

var express = require('express');
var app = express();
 
app.get('/', function (req, res) {
    
    
   res.send('Hello World, yxy!');
})
 
var server = app.listen(8081, function () {
    
    
 
  var host = server.address().address
  var port = server.address().port
 
  console.log("应用实例,访问地址为 http://%s:%s", host, port)
 
})
  • The code is executed as follows:
    Insert image description here
  • Browser access is as follows:
    Insert image description here

4、PHP

4.1 Introduction

A popular general-purpose scripting language especially suitable for web development.
PHP is fast, flexible and practical, powering everything from your blog to the world's most popular websites.

PHP is a powerful server-side scripting language for creating dynamic, interactive sites.

PHP is free and widely used. At the same time, for competitors like Microsoft ASP, PHP is undoubtedly another efficient option.
Insert image description here

4.2 Installation

https://www.php.net/downloads
https://windows.php.net/downloads/releases/archives/
Insert image description here

4.3 Use

https://www.php.net/manual/zh/features.commandline.webserver.php

This built-in web server is mainly used for local development and cannot be used in online product environments.

URI requests will be sent to the working directory (Working Directory) where PHP is located for processing, unless you use the -t parameter to customize a different directory.

If the request does not specify which PHP file to execute, index.php or index.html in the directory will be executed by default. If neither file exists, the server returns a 404 error.

  • Start the web server
php -S localhost:8000

# 启动时指定根目录
php -S localhost:8000 -t foo/
  • The command line execution is as follows:
    Insert image description here
    the browser access is as follows:
http://localhost:8000/

Insert image description here

5、Apache httpd

Apache HTTP server is a modular web server that can run on almost all widely used computer platforms. Apache supports many modules and has stable performance. Apache itself is static parsing, suitable for static HTML, pictures, etc., but it can be extended through scripts , modules, etc. support dynamic pages, etc.

Currently, the three most mainstream web servers are Apache, Nginx, and IIS.
Insert image description here

5.1 Introduction

https://httpd.apache.org/

Insert image description here
The Apache HTTP Server project aims to develop and maintain a server standard for modern operating systems, including UNIX and Windows. The project's goal is to provide a secure, efficient, and extensible server standard that provides HTTP services that are synchronized with current HTTP.

The Apache HTTP server ("httpd") was launched in 1995, and since then it has been the most popular web server on the Internet. 25.1996.

Apache HTTP Server is a project foundation of the Apache software.

5.2 Installation

https://httpd.apache.org/download.cgi
Insert image description here
Insert image description here
Insert image description here
is decompressed as follows:
Insert image description here

5.3 Use

  • (1) Directly execute the command line as follows:
httpd

Insert image description here
An error is reported when running. This is due to the inconsistency between the path configured by ServerRoot in the httpd.conf file and the actual path. After determining the problem, open httpd.conf, search for Define SRVROOT, and change the path in the double quotes behind it to the actual path of Apache. Just decompress the path and save it.

  • httpd.conf
Define SRVROOT "C:\Users\tomcat\Desktop\httpd-2.4.55-o111s-x64-vs17\Apache24"
ServerRoot "${SRVROOT}"

Insert image description here
Browser access is as follows:

http://127.0.0.1:80

Insert image description here

  • (2) It can also be run as a service.
    Enter the bin directory under Apache24 on the command line and run the command httpd -k install -n "service name".
#安装apache服务
#注:若不使用特殊参数(如httpd.exe -k install),服务名称为Apache2.X,配置文件为conf\httpd.conf
httpd.exe -k install

#指定要安装的服务的名称(适用于电脑上有几个不同的Apache服务设施)
httpd.exe -k install -n "MyServiceName"

#指定服务配置文件的路径和名称
httpd.exe -k install -n "MyServiceName" -f "c:\files\my.conf"

#移除一个Apache服务
httpd.exe -k uninstall

#移除特定的Apache服务
httpd.exe -k uninstall -n "MyServiceName"

#启动已安装的apache服务
httpd.exe -k start

#停止已安装的Apache服务
httpd.exe -k stop || httpd.exe -k shutdown

#重启已安装的Apache服务(迫使服务重读配置文件,适用于修改配置文件后)
httpd.exe -k restart

#测试该服务的配置文件
httpd.exe -n "MyServiceName" –t

Execute the following command to see which process occupies port 443

netstat -ano|findstr "443"
tasklist|findstr "17208"
  • Configure the default site folder
    Modify the DocumentRoot in the httpd.conf file
    Insert image description here


  • Modify Listen in the http port \Apache24\conf\httpd.conf file, the default is 80.

  • Modify the https port
    \Apache24\conf\extra\httpd-ahssl.conf file and replace 443 with the specified port.

  • Set cross-domain
    \Apache24\conf\httpd.conf file and add: Header set Access-Control-Allow-Origin *

<Directory />
    AllowOverride none
    Require all denied
	Header set Access-Control-Allow-Origin *
</Directory>

Uncomment the LoadModule headers_module modules/mod_headers.so in the \Apache24\conf\httpd.conf file.

6、Nginx

Nginx is a free, open source, high-performance HTTP server and reverse proxy server. It is also an IMAP, POP3, and SMTP proxy server, mostly used for high connection concurrency.

6.1 Introduction

https://nginx.org/en/
Nginx was designed and developed by lgor Sysoev for the rambler.ru site, the second most visited site in Russia. Since its release in 2004, it has become nearly mature and perfect with the power of open source.

Nginx is rich in functions and can be used as an HTTP server, a reverse proxy server, and a mail server. Supports FastCGI, SSL, Virtual Host, URL Rewrite, Gzip and other functions. And supports many third-party module extensions.
Insert image description here

6.2 Installation


Insert image description here
The folder after https://nginx.org/en/download.html is decompressed is as follows:
Insert image description here

6.3 Use

Directly execute the command line as follows:

nginx
# start nginx

Browser access is as follows:

http://localhost:80

Insert image description here
Insert image description here

# 启动
nginx -s start
# 重新启动,热启动,修改配置重启不影响线上
nginx -s reload
# 关闭
nginx -s stop
nginx -s quit
taskkill /f /t /im nginx.exe
# 修改配置后,可以通过下面的命令测试是否有语法错误
nginx -t

Check whether nginx starts successfully.

tasklist /fi “imagename eq nginx.exe

Insert image description here

  • Modify the configuration nginx.conf file
    . Modify the server and root default html to: html/dist. Nginx will find index.html in dist and open it.
    Insert image description here

After the modification is completed, nginx -s reload restarts
and enters: localhost:8090 in the browser to check whether it is successful;

7、Microsoft IIS

Microsoft IIS (Internet Information Services)
IIS is the English abbreviation of "Internet Information Services", that is, "Internet Information Services". It is a basic Internet service provided by Microsoft Corporation based on running the "Microsoft Windows operating system".
Insert image description here

  • Click Start, then click Control Panel.
  • In Control Panel, click Programs.
  • Under Programs and Features, click Turn Windows features on or off.
  • In the Windows Features dialog box, expand Internet Information Services and select All Features.
  • You may need to expand some categories to select all features in that category.
  • Click OK.

Insert image description here

8、Apache Tomcat

Tomcat is a Java application server. It is just a Servlet container and can be considered an extension of Apache, but it can run independently of Apache.

8.1 Introduction

https://tomcat.apache.org/

Insert image description here
Tomcat server is a free and open source Web application server. It is a lightweight application server and is commonly used in small and medium-sized systems and situations where there are not many concurrent access users. It is the first choice for developing and debugging JSP programs. For a beginner, you can think of it this way: when the Apache server is configured on a machine, it can be used to respond to HTML page access requests. In fact, Tomcat is an extension of the Apache server, but it runs independently when running, so when you run tomcat, it actually runs as a separate process from Apache.

Insert image description here

8.2 Installation


Insert image description here
The folder after decompressing https://tomcat.apache.org/download-10.cgi is as follows:
Insert image description here

Insert image description here
In the system variables column, configure Tomcat's environment variables:

CATALINA_BASE=C:\Users\tomcat\Desktop\apache-tomcat-10.1.13
CATALINA_HOME=C:\Users\tomcat\Desktop\apache-tomcat-10.1.13
CATALINA_TMPDIR=C:\Users\tomcat\Desktop\apache-tomcat-10.1.13\temp
Path+=%CATALINA_HOME%\bin;%CATALINA_HOME%\lib;%JAVA_HOME%\bin;

Enter "cmd" in the pop-up dialog box and press Enter. Enter "startup" in the command prompt interface and press Enter to open Tomcat, as shown in the figure below.
Insert image description here
An error was reported when running, and it was found that the environment variables of java sdk were not configured.

JAVA_HOME=C:\Program Files\Java\jdk1.8.0_221

Open a command line window with administrator privileges and execute the command:

startup.bat

Insert image description here
The tomcat service started successfully.
Browser access is as follows:

http://127.0.0.1:8080/

Insert image description here

9、Lighttpd

Lighttpd is a free, open-source web server designed for speed-critical applications. Unlike Apache and Nginx, it has a very small footprint (less than 1 MB) and is very economical in terms of server resources (such as CPU utilization).

9.1 Introduction

https://www.lighttpd.net/

Lighttpd is an open source WEB server software developed under the leadership of German Jan Kneschke and is based on BSD license. Its fundamental purpose is to provide a secure, fast, compatible and flexible web server environment specifically for high-performance websites. It has the characteristics of very low memory overhead, low CPU usage, good performance, and rich modules. Lighttpd is one of the better ones among the many OpenSource lightweight web servers. Supports FastCGI, CGI, Auth, output compression, URL rewriting, Alias ​​and other important functions.

Lighttpd is distributed under the BSD license and it runs natively on Linux/Unix systems but can also be installed in Microsoft Windows. It is popular for its simplicity, ease of setup, performance and module support.

Lighttpd's architecture is optimized to handle large numbers of parallel connections, which is critical for high-performance web applications. The web server supports FastCGI, CGI, and SCGI for interfacing programs with the web server. It also supports web applications written in multiple programming languages, with special attention to PHP, Python, Perl, and Ruby.

9.2 Installation

sudo apt-get update
sudo apt-get install lighttpd

Insert image description here

Conclusion

如果您觉得该方法或代码有一点点用处,可以给作者点个赞,或打赏杯咖啡;╮( ̄▽ ̄)╭
如果您感觉方法或代码不咋地//(ㄒoㄒ)// ,就在评论处留言,作者继续改进;o_O???
如果您需要相关功能的代码定制化开发,可以留言私信作者;(✿◡‿◡)
感谢各位大佬童鞋们的支持!( ´ ▽´ )ノ ( ´ ▽´)! ! !

Guess you like

Origin blog.csdn.net/hhy321/article/details/133468841