Customizing your Web server with a Python script

Source: Internet
Author: User
Tags bind socket python script

The first thing to say is that this is an impossible task, at least not a blog post can do. Avoid wasting time looking at the headlines and expecting the same fellow.

The main is to take Apache as the blueprint, through the Python script step-by-step to achieve the core functions of Apache. Learn about Python network programming and all aspects related to Web service energy.

Gossip less, directly on the code!

Import socket

Server=socket.socket (Socket.af_inet,socket. SOCK_STREAM)

Server.bind ((', 1234))

Server.listen (5)

While True:

Client,addr=server.accept ()

DATA=CLIENT.RECV (1024)

Client.send ("My WebServer")

Client.close ()

Test this server with the AB command:

ab-n500-c500 http://127.0.0.1:1234/

The test results are as follows:

By printing data, you get the information that the client agent submits to webserver.

get/http/1.1

user-agent:curl/7.12.1 (I686-REDHAT-LINUX-GNU) libcurl/7.12.1 openssl/0.9.7a zlib/1.2.1.2 libidn/0.5.6

host:127.0.0.1:1234

Pragma:no-cache

Accept: */*

We only care about the contents of the GET request here, and then return it to the client after the user's getting request is parsed to obtain the contents of the file in the specified directory.

Import socket

Import re

documentroot= "/root/"

Server=socket.socket (Socket.af_inet,socket. SOCK_STREAM)

Server.bind ((', 1235))

Server.listen (5)

While True:

Client,addr=server.accept ()

DATA=CLIENT.RECV (1024)

M=re.match (' Get/(. *) ', data) #由于ab使用的是http1.0 so it's different from the previous example.

Try: #为应对在进行ab测试时候可能的异常

Index=documentroot+m.group (1)

Html=open (Index, "R")

Client.send (Html.read ())

Client.close ()

Except

Client.close ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.