Python 风格指南

一个典型模块的内部结构:

  1. 起始行
  2. 模块文档(文档字符串)
  3. 模块导入
  4. (全局)变量定义
  5. 类定义(若有)
  6. 函数定义(若有)
  7. 主程序

样例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env python
#coding:utf-8
 
"this is a test module"
 
import sys
import os
 
debug = True
 
class FooClass(object):
"Foo class"
pass
 
def test():
"test function"
foo = FooClass()
if debug:
print 'ram test()'
 
if __name__ == '__main__':
test()

Hello world!

#!/usr/bin/env python
#coding:utf-8
 
def helloworld():
"Hello World! \
\nWelcome to my blog."
print 'Nice to meet you!'
if __name__ == '__main__':
helloworld()

利用 GAE同步更新饭否与TWITTER,建立你的HELLOTXT

第一次写与API有关的东西,算是一边练习Python及GAE,一边练习API接口的相关的操作。这是我做的一个利用GAE同步更新饭否与 TWITTER的DEMO,不保存帐户信息,每次需要手工填入用户名密码,再加入数据库存储等相应辅助模块即可做出与HelloTxt、Ping.fm类似的应用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#!/usr/bin/env python
#coding:utf-8 
 
import wsgiref.handlers
import urllib
import base64
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
 
class MainPage(webapp.RequestHandler):
 
def get(self):
#self.response.headers['Content-Type'] = 'text/plain'
self.response.headers.add_header("Expires", "Thu, 01 Dec 1994 16:00:00 GMT")
header(self)
self.response.out.write('''<div id="letter">
<form action="/sign" method="post">
<div>Twitter username:<input type="text" name="tusername" id="username" value="" />
password:<input type="text" name="tpassword" id="password" value="" /></div>
<div>Fanfou username:<input type="text" name="fu" id="username2" value="" />
password:<input type="text" name="fp" id="password2" value="" /></div>
<div><textarea name="content" rows="3" cols="60"></textarea></div>
<div><input type="submit" value="Post"></div>
</form></div>
''')
footer(self)
 
class PostPage(webapp.RequestHandler):
def post(self):
header(self)
msg = self.request.get('content')
page_msg=msg
msg = msg.encode('utf8')
tu = self.request.get('tusername')
tp = self.request.get('tpassword')
fu = self.request.get('fu')
fp = self.request.get('fp')
#update(tu,tp,'twitter',msg)
#update(fu,fp,'fanfou',msg)
self.response.out.write('''<div id="letter">''')
if update(tu,tp,'twitter',msg)==True:
self.response.out.write('''
<p>Twitter Post Susscessful</p>
''')
else:
self.response.out.write('''
<p>Twitter Post Faild</p>
''')
if update(fu,fp,'fanfou',msg)==True:
self.response.out.write('''
<p>Fanfou Post Susscessful</p>
''')
else:
self.response.out.write('''
<p>Fanfou Post Faild</p>
''')
 
self.response.out.write('''
<p><a href="/" >Back</></p></div>
''')
footer(self)
#self.redirect('/')
 
def header(self):
self.response.out.write('''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"/>
<link type="text/css" rel="stylesheet" href="./styles/main.css" media="screen" />
<title>Hello,World</title>
</head>
<body>''')
 
def footer(self):
self.response.out.write('''
<div id="footer"><p><img src="http://code.google.com/appengine/images/appengine-silver-120x30.gif" 
alt="Powered by Google App Engine" /></p><p>Powered by <a href="http://ioio.name/">IoIo.NaMe</a></p></div>
</body>
</html>''')
 
def update(username,password,twitter,msg):
authStr = username + ":" + password
#self.response.out.write(authStr.encode("base64")[0:-1])
if twitter=='twitter' :
url='http://twitter.com/statuses/update.json'
else:
url='http://api.fanfou.com/statuses/update.json'
#msg="Update by GAE.由GAE更新."
form_fields = {"status":msg}
form_data = urllib.urlencode(form_fields)
#self.response.out.write(form_data)
result = urlfetch.fetch(url=url,
payload=form_data,
method=urlfetch.POST,
headers={"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/xml",
"Authorization": "Basic "+authStr.encode("base64")[0:-1]})
if result.status_code == 200:
return True
else:
return False
 
def main():
application = webapp.WSGIApplication([('/', MainPage),
('/sign', PostPage)],
debug=True)
wsgiref.handlers.CGIHandler().run(application)
 
 
if __name__ == '__main__':
main()

-EOF-

Python获取IP地址

获取本机IP和Port,远程IP和Port

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# -*- coding: cp936 -*-
"""
使用socket获取更多的信息
getsocketname:获得本机的信息(IP和port)
getpeername:获得远程机器的信息(IP和port)
fileno:每一个socket对应一个fd,使用此方法可以获得fd,为一个整数
"""
import socket</code>
 
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
port = socket.getservbyname("http","tcp")
 
s.connect(("www.google.com",port))
print "Connect from",s.getsockname()
print "Connect to",s.getpeername()
print "file descriptor",s.fileno()
s.close()

直接获取远程IP

1
2
import socket
socket.gethostbyname('google.com')

直接获取本地IP

1
2
3
import socket
socket.gethostbyname(socket.gethostname())
socket.gethostbyname_ex(socket.gethostname())

-EOF-