python實現web服務器

本想寫一篇關於http->nginx->php這個過程當中數據是怎麼傳輸的文章,想了半天,實在沒有心情去寫。恰好看了一下python,就想着用python實現一下web服務器的過程。這個很簡單,目前只支持靜態文件的加載,動態語言就要接入fastcgi了(目前還在看fastcgi,下一版本更新吧)。之前沒寫過python也是邊寫邊查,好多東西用的不是特別好,還有,能夠在這個基礎上改動,能夠支持access.log,多server配置。這裏就不寫了。php

其實過程很簡單,nginx大致也是這個邏輯(可是,nginx內部就複雜多了)。python

  1. 建立socket,監聽80端口(能夠自設)nginx

  2. 解析http協議中的request(獲取你想要的參數)web

  3. 經過獲取的參數取服務器上找到相應的靜態資源(這裏只說靜態資源,動態的下一篇再說)服務器

  4. 組織http協議的responsesocket

  5. 經過80端口返回給客服端code

#/usr/bin/python
import socket
import sys
import os
from thread import *

HOST = '';PORT = 8887

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

try:
    s.bind((HOST, PORT))
except socket.error , msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'

s.listen(10)

print 'Socket now listening'

def assces_log(request):
    fp = open('http.log', "aw")
    fp.write(request+"\r\n")
    fp.close()

def parse_request(request):
    request = request.splitlines()
    line = request[0]
    line = line.split();
    dict_request = {'method':line[0], 'path':line[1], 'version':line[2]}
    return dict_request

while True:
    conn, addr = s.accept()
    request = conn.recv(1024)
    print request
    print "\r\n"

    dist_request = parse_request(request)
    path = dist_request['path']
    path = os.getcwd() + path

    if os.path.isfile(path):
        if os.path.exists(path):
            fp = open(path, "r")
            reply = fp.read()
            fp.close()
            response_errno = 200
            response_msg = 'OK'
        else:
            reply = 'Not found page'
            response_errno = 404
            response_msg = 'Not found'
    else:
        reply = 'Forbidden'
        response_errno = 403
        response_msg = 'Forbidden'

    response = "HTTP/1.1 " + str(response_errno) + " " + response_msg + "\r\n"
    response += "\r\n"
    response += reply
    print response

    assces_log(request)

    conn.sendall(response)
    conn.close()

s.close()
相關文章
相關標籤/搜索