1. 程式人生 > 程式設計 >基於python實現簡單網頁伺服器程式碼例項

基於python實現簡單網頁伺服器程式碼例項

程式碼:

hello.py

#!/usr/bin/python
# coding: utf-8
# hello.py
def application(environ,start_response):
  start_response('200 OK',[('Content-Type','text/html')])
  return '<h1>Hello,%s!</h1>' % (environ['PATH_INFO'][1:] or 'web')

server.py

#!/usr/bin/python
# coding: utf-8

# server.py
from wsgiref.simple_server import make_server
from hello import application

# create server,ip is empty,port is 8000,handle function is application
httpd = make_server('',8000,application)
print "Serving HTTP on port 8000..."
# start listen http request
httpd.serve_forever()

使用了模組wsgiref。它實現了wsgi介面,我們只需要定一個wsgi處理函式來處理得到的請求就可以了。

用python來實現這些看似很複雜的例項程式,非常簡單,這都得益於python強大的庫。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。