Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1605219
  • 博文数量: 695
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 4027
  • 用 户 组: 普通用户
  • 注册时间: 2013-11-20 21:22
文章分类

全部博文(695)

文章存档

2018年(18)

2017年(74)

2016年(170)

2015年(102)

2014年(276)

2013年(55)

分类: Python/Ruby

2015-10-13 09:58:39

python自带CGIHTTPServer服务器与htm进行CGIl交互

使用环境:

win7专业版

python 2.7.3

chrome 23.0

============

安装好python后我测试下面的内容时还没有设置全局路径,可以设置python成全局路径

============

开始:

1 进入某个你想创建为服务器的文件夹,假如文件夹名为www。从cmd进入www文件夹,运行python -m CGIHTTPServer,默认端口是8000,可能被其他程序占用(我跑程序的时候就被占用了,这个我弄了好久才发现),可以自己设置端口(最好大于 1024)。

  python -m CGIHTTPServer 端口号 例如:python -m CGIHTTPServer 8888

2 进入www文件夹,新建一个cgi-bin的文件夹,用来存放.py文件,原因看官方文件: /library/cgihttpserver.html?highlight=cgihttpserver#CGIHTTPServer

3 在www文件夹中新建一个test.html文件

点击(此处)折叠或打开

  1. <!DOCTYPE HTML>
  2. <html>
  3.     <head>
  4.         <title>
  5.             hello python cgi
  6.         </title>
  7.     </head>
  8.     <body>
  9.     <p>test for python cgi server</p>
  10.         <form action="/cgi-bin/form.py">
  11.             <label for="">text:</label><input type="text" name="text" value = "test">
  12.             <input type="submit">
  13.         </form>
  14.     </body>
  15. </html>
4 在cgi-bin文件中新建form.py文件

点击(此处)折叠或打开

  1. # -*- coding: utf-8 -*-
  2.             
  3. import cgi
  4.             
  5. header = 'Content-Type: text/html\n\n'
  6.             
  7. html = '<h3>接受处理表单数据\n</h3>'
  8. #打印返回的内容
  9. print header
  10. print html
  11. # 接受表达提交的数据
  12. form = cgi.FieldStorage()
  13.             
  14. print '接收表达get的数据 :',form
  15.             
  16. print '<p />'
  17.             
  18. # 解析处理提交的数据
  19. content = form['text'].value
  20.             
  21. formhtml = '''
  22. <label for="">you say:</label><input type="text" value="%s">
  23. '''
  24.             
  25. print formhtml % (content)
5 测试确定已启动服务器,即已经执行python -m CGIHTTPServer。端口号自定,我这里使用自己设置的8080端口。打开firefox,输入路径localhost:8080/www/text.html

测试结果



http://blog.csdn.net/dijason/article/details/8256372
阅读(1003) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~