CGI是运行在服务器上的程序,提供客户端HTML页面的接口,它的全称是Common Gateway Interface (通用网关接口)
缺点及改进:
每次的CGI请求都要生成程序的副本来运行
FastCGI-先编译
mod_perl-将解释器作为模块集成在web服务器中
使用C等编译语言
模板引擎jkxy.py
form_type="GET"和form_type="POST"对应于get和post请求
def start_response(resp="text/html"): return 'Content-type: '+resp+ '\n\n' def start_form(the_url="",form_type="GET"): return '<form action="'+the_url+'"method="'+form_type+'">' def end_form(submit_msg="Submit"): return '<p></p><input type="submit" value="' +submit_msg+'">' def input_label(name,placeholder="",value="",readonly=None): if readonly is None: return '<input type="text" value="'+value+'" name="'+name+'" placeholder="'+placeholder+'">' else: return '<input type="text" value="'+value+'" readonly="'+readonly+'" name="'+name+'" placeholder="'+placeholder+'">' def context(word): return word def start_div(align,style): return '<div align="'+align+'"style="'+style+'">' def end_div(): return "</div>" def img(src): return '<img src="'+src+'">'
main.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import cgi, cgitb from jkxy import * form1 = cgi.FieldStorage() #声明请求参数的一个容器 num1=form1.getvalue("Num1") num2=form1.getvalue("Num2") num3=None if not num1 is None and not num2 is None: num1=int(num1) num2=int(num2) num3=num1+num2 print start_response() print start_div("center","margin-top:40px;") print img("../views/add.png") print end_div() print start_div("center","margin-top:60px;") print start_form() print input_label("Num1","adder-1") print "+" print input_label("Num2","adder-2") print "=" if num3 is None: print input_label("Num3","result","","readonly") else: print input_label("Num3","result",str(num3),"readonly") print end_form() print end_div()
使用以下命令启动web服务
python -m CGIHTTPServer 8081
本文出自 “点滴积累” 博客,请务必保留此出处http://tianxingzhe.blog.51cto.com/3390077/1727166