Python 实现一个简单的http服务器

深碍√TFBOYSˉ_ 2022-08-03 15:46 285阅读 0赞

背景

原文链接:http://blog.csdn.net/ordeder/article/details/22490373

写一个python脚本,实现简单的http服务器功能:

1.浏览器中输入网站地址:172.20.52.163:20014

2.server接到浏览器的请求后,读取本地的index.html文件的内容,回发给浏览器

代码实现

server.py

  1. #!/usr/bin/python
  2. import socket
  3. import signal
  4. import errno
  5. from time import sleep
  6. def HttpResponse(header,whtml):
  7. f = file(whtml)
  8. contxtlist = f.readlines()
  9. context = ‘’.join(contxtlist)
  10. response = “%s %d\n\n%s\n\n” % (header,len(context),context)
  11. return response
  12. def sigIntHander(signo,frame):
  13. print‘get signo# ‘,signo
  14. global runflag
  15. runflag = False
  16. global lisfd
  17. lisfd.shutdown(socket.SHUT_RD)
  18. strHost = “172.20.52.163”
  19. HOST = strHost #socket.inet_pton(socket.AF_INET,strHost)
  20. PORT = 20014
  21. httpheader = ‘’’\
  22. HTTP/1.1 200 OK
  23. Context-Type: text/html
  24. Server: Python-slp version 1.0
  25. Context-Length: ‘’’
  26. lisfd = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  27. lisfd.bind((HOST, PORT))
  28. lisfd.listen(2)
  29. signal.signal(signal.SIGINT,sigIntHander)
  30. runflag = True
  31. while runflag:
  32. try:
  33. confd,addr = lisfd.accept()
  34. except socket.error as e:
  35. if e.errno == errno.EINTR:
  36. print‘get a except EINTR’
  37. else:
  38. raise
  39. continue
  40. if runflag == False:
  41. break;
  42. print“connect by “,addr
  43. data = confd.recv(1024)
  44. if**not** data:
  45. break
  46. print data
  47. confd.send(HttpResponse(httpheader,’index.html’))
  48. confd.close()
  49. else:
  50. print‘runflag#‘,runflag
  51. print‘Done’

index.html

[html] view plain copy 在CODE上查看代码片 派生到我的代码片

  1. <**html**>
  2. <**head**>
  3. <**title**>Python Server</**title**>
  4. </**head**>
  5. <**body**>
  6. <**h1**>Hello python</**h1**>
  7. <**p**>Welcom to the python world</**br**>
  8. </**body**>
  9. </**html**>

测试

测试结果:

root@cloud2:~/slp/pythonLearning/socket# ./server_v1.py
connect by (‘172.20.52.110’, 6096)
GET / HTTP/1.1
Host: 172.20.52.163:20014
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: zh-CN,zh;q=0.8,en;q=0.6

浏览器

SouthEast

BUG:

TypeError: view must be a callable or a list/tuple in the case of include() ,加上include又说没blog.views这个包 这到底是为啥

解决办法:

from django.conf.urls import url

from django.contrib import admin

from blogapp import views

urlpatterns = [

url(r’^admin/‘, admin.site.urls),

url(r’helloworld’,views.hello)

]

发表评论

表情:
评论列表 (有 0 条评论,285人围观)

还没有评论,来说两句吧...

相关阅读