Python学习(三):Web开发

  •  启动Python web server

from http.server import HTTPServer, CGIHTTPRequestHandler

port = 8080

httpd = HTTPServer(('', port), CGIHTTPRequestHandler)
print("Starting simple_httpd on port: " + str(httpd.server_port))
httpd.serve_forever()
  • 客户端访问:localhost:8080, 这是会访问(index.html)。html里使用href,调用python CGI脚本
<html>
<head>
<title>Welcome to Coach Kelly's Website</title>
<link type="text/css" rel="stylesheet" href="coach.css" />
</head>
<body>
<img src="images/coach-head.jpg">
<h1>Welcome to Coach Kelly's Website.</h1>
<p>
For now, all that you'll find here is my athlete's <a href="cgi-bin/generate_list.py">timing data</a>. Enjoy!
</p>
<p>
<strong>See you on the track!</strong>
</p>
</body>
</html>
  • python利用print函数,创建html脚本。这里使用yate对创建html做了封装。感觉这种方式很好 (generate_list.py) 

注意start_form和end_form的使用,当点击Select后,会调用generate_timing_data.py,并且将which_athlete的session值作为参数传了过去。

另外注意下glob的用法,根据文件名取得文件List

#! /usr/local/bin/python3

import glob

import athletemodel
import yate

data_files = glob.glob("data/*.txt")
athletes = athletemodel.put_to_store(data_files)

print(yate.start_response())
print(yate.include_header("Coach Kelly's List of Athletes"))
print(yate.start_form("generate_timing_data.py"))
print(yate.para("Select an athlete from the list to work with:"))
for each_athlete in athletes:
    print(yate.radio_button("which_athlete", athletes[each_athlete].name))
print(yate.end_form("Select"))
print(yate.include_footer({"Home": "/index.html"}))
  • (generate_timing_data.py)里使用 form_data = cgi.FieldStorage() 得到session值。

import cgitb 和 cgitb.enable()可以查看CGI的错误信息

#! /usr/local/bin/python3

import cgi

import cgitb
cgitb.enable()

import athletemodel
import yate

athletes = athletemodel.get_from_store()

form_data = cgi.FieldStorage()
athlete_name = form_data['which_athlete'].value

print(yate.start_response())
print(yate.include_header("Coach Kelly's Timing Data"))    
print(yate.header("Athlete: " + athlete_name + ", DOB: " +
                      athletes[athlete_name].dob + "."))
print(yate.para("The top times for this athlete are:"))
print(yate.u_list(athletes[athlete_name].top3))
print(yate.include_footer({"Home": "/index.html",
                           "Select another athlete": "generate_list.py"}))

关于Python CGI编程,可以参考下面。(后面有例子)

http://www.runoob.com/python/python-cgi.html

补充:

  1. 浏览器客户端通过两种方法向服务器传递信息,这两种方法就是 GET 方法和 POST 方法。Post可以隐藏一些敏感信息,例如密码等
  2. Template的用法:
    s1 = Template('$who likes $what')
    print(s1.substitute(who='tim', what='kung pao'))
    
    输出:tim likes kung pao
    

猜你喜欢

转载自blog.csdn.net/jfyy/article/details/82684206
今日推荐