beautiful

漂亮吧?猜一下这图来自哪?

漂亮吧?猜一下这图来自哪?
Shell:~ >: python
Python 2.6.1 (r261:900M, Nov 18 2009, 17:55:22)
[GCC 4.3.2] on linux2
[Unladen Swallow 2009Q4]
Type "help", "copyright", "credits" or "license" for more information.
>>>
由于OpenSolaris太慢了,换成Debian,终于可以用unladen-swallow.
In Python 2, exec is actually implemented as a special language statement,
whereas Python 3 implements it as a standard library function.
在python2是语句,在python3已经是标准的库函数了。
http://code.google.com/p/mylibs/source/browse/lib/Python/MyPyLib/smtp_client.py :
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Copyright 2009 N23 <No.0023@gmail.com>
# All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__all__ = ['get_smtp_client', 'sendmail']
import os, sys
from ConfigParser import ConfigParser
from ConfigParser import NoOptionError
from smtplib import SMTP
from smtplib import SMTPAuthenticationError
from email import Encoders
from email.base64MIME import encode as encode_base64
from email.MIMEBase import MIMEBase
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
def get_smtp_client(stor):
host = stor['host']
port = stor['port']
user = stor['user']
passwd = stor['pass']
debuglevel = stor['debuglevel']
login = stor['login']
starttls = stor['starttls']
s = SMTP(host, port)
if debuglevel:
s.set_debuglevel(True)
if starttls and login:
s.ehlo()
s.starttls()
s.ehlo()
s.login(user, passwd)
elif login:
try:
s.login(user, passwd)
except SMTPAuthenticationError:
sys.stdout.write('\n------- try Auth Login again ------\n')
s = SMTP(host, port)
if debuglevel:
s.set_debuglevel(True)
s.ehlo()
(code, resp) = s.docmd('AUTH LOGIN')
if code != 334:
raise SMTPAuthenticationError(code, resp)
(code, resp) = s.docmd(encode_base64(user, eol=""))
if code != 334:
raise SMTPAuthenticationError(code, resp)
(code, resp) = s.docmd(encode_base64(passwd, eol=""))
if code != 235:
raise SMTPAuthenticationError(code, resp)
return s
def sendmail(server, msg):
address = [i for f in ('To', 'Cc', 'Bcc') if msg[f] for i in msg[f].split(',')]
server.sendmail(msg['From'], address, msg.as_string())
def fn(options, args):
cfg = ConfigParser()
cfg.read(os.path.join(os.getenv('HOME'), '.LoginAccount.txt'))
flag = 'mailClient'
keys = ('host', 'port', 'user', 'pass', 'fr', 'to', 'debuglevel', 'login', 'starttls')
stor = {}
for k in keys: stor.setdefault(k, '')
try:
stor['host'] = cfg.get(flag, 'host')
stor['port'] = cfg.getint(flag, 'port')
stor['user'] = cfg.get(flag, 'user')
stor['pass'] = cfg.get(flag, 'pass')
stor['fr'] = cfg.get(flag, 'fr')
stor['to'] = cfg.get(flag, 'to')
stor['debuglevel'] = cfg.getboolean(flag, 'debuglevel')
stor['login'] = cfg.getboolean(flag, 'login')
stor['starttls'] = cfg.getboolean(flag, 'starttls')
except NoOptionError: pass
if options.addr:
stor['to'] = options.addr
s = get_smtp_client(stor)
for arg in args:
sys.stdout.write('sending... ' + arg)
msg = MIMEMultipart()
msg['From'] = stor['fr']
msg['Subject'] = arg
msg['To'] = stor['to']
msg.set_boundary('===== Baby, I love you. no.0023@gmail.com =====')
if options.atta:
data = MIMEBase('application', 'octet-stream')
data.set_payload(open(arg, 'rb').read())
Encoders.encode_base64(data)
data.add_header('Content-Disposition', 'attachment', filename = arg)
msg.attach(data)
else:
b = '''<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head><body><pre>'''
b += open(arg, 'rb').read()
b += '''</pre></body></html>'''
body = MIMEText(b, _subtype = 'html', _charset = 'utf-8')
msg.attach(body)
sendmail(s, msg)
sys.stdout.write(' done.\n')
s.close()
if __name__ == '__main__':
from optparse import OptionParser
usage = '%prog [-e addr] [-a] args...'
parser = OptionParser(usage=usage)
parser.add_option('-e', '--addr', dest='addr',
help='receive email address', metavar='ADDR')
parser.add_option('-a', '--atta', dest='atta',
action='store_true', default=False,
help='attachment flag', metavar='atta')
(options, args) = parser.parse_args()
if not args:
parser.print_usage()
sys.exit(1)
fn(options, args)
http://code.google.com/p/mylibs/source/browse/lib/Python/MyPyLib/LoginAccount.txt :
[mailClient]
host = smtp.qq.com
port = 25
user = *** # change to your login id
pass = *** # change to your login password
fr = no.0023@qq.com
to = no.0023@gmail.com
debuglevel = True
login = True
starttls = False
#[mailClient]
#host = smtp.gmail.com
#port = 587
#user = ***@gmail.com
#pass = ***
#fr = no.0023@gmail.com
#to = no.0023@qq.com
#debuglevel = True
#login = True
#starttls = True
1. download rfcsdk on sap.com, download saprfc for python on http://pypi.python.org/pypi/saprfc/0.07
2. install rfcsdk and saprfc with docs
#! /usr/bin/env python
import pprint
import saprfc
conn = saprfc.conn(ashost='hostname', sysnr='00', client='220', lang='EN', user='xxxxx', passwd='xxxxx')
conn.connect()
print "am I connected: ", conn.is_connected()
print "sysinfo is: "
pprint.pprint(conn.sapinfo())
iface = conn.discover("RFC_READ_TABLE")
iface.query_table.setValue("TRDIR")
iface.ROWCOUNT.setValue(10)
iface.OPTIONS.setValue(["NAME LIKE 'SAPL%RFC%'"])
conn.callrfc(iface)
print "NO. PROGS: ", iface.DATA.rowCount()
#print "PROGS DATA: "
#pprint.pprint(iface.DATA.value)
# get the SAP Data Dictionary structure for TRDIR
str = conn.structure("TRDIR")
# various ways for iterating over the results in an
# interface table
for x in iface.data.value:
print "Doing: " + str.toHash(x)['NAME']
#print "PROGS HASH ROWS: "
#for i in iface.DATA.hashRows():
# print "next row: ", i
conn.close()
shell:~/python-3.0.1/bin >: python3.0
Python 3.0.1 (r301:69556, Feb 27 2009, 21:48:14)
[GCC 4.0.0] on aix5
Type "help", "copyright", "credits" or "license" for more information.
>>>
shell:~/python-3.0.1/bin >:
how to install:
shell:~/tmp/Python-3.0.1 >: configure --prefix=$u/python-3.0.1 --with-gcc
shell:~/tmp/Python-3.0.1 >: make
shell:~/tmp/Python-3.0.1 >: make install
版本資訊:
OS: Ubuntu 8.10
Python 2.5.4
Pylons 0.97rc4
Google App Engine 1.1.7
步驟:
svn checkout http://appengine-monkey.googlecode.com/svn/trunk/ appengine-monkey
python2.5 appengine-boot.py --paste-deploy my-app
## my-app 可改為你的想要的應用程式名稱,如:hellopylons)
>> Enter template_engine (mako/genshi/jinja/etc: Template language) ['mako']:
>> Enter sqlalchemy (True/False: Include SQLAlchemy 0.4 configuration) [False]:
>> Enter google_app_engine (True/False: Setup default appropriate
>> for Google App Engine) [False]:True
cd my-app
source bin/activate
easy_install Pylons
cd src
paster create --template=pylons MyApplication
## MyApplication 依樣可自訂其名稱
cd my-app/src/MyApplication
python setup.py develop
cd ../..
python -m pth_relpath_fixup
編輯 my-app/development.ini:
[app:the-app]
## Change this to whatever you name your application:
use = egg:MyApplication
到此與 appengine-monkey 上差不多,但接著要多幾個動作才能見到 Welcome:
一.
File ".../appengine-monkey/my-app/src/MyApplication/MyApplication/config/environment.py", line 34, in load_environment
module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
KeyError: 'cache_dir'
避免如上錯誤,編輯 my-app/src/MyApplication/config/environment.py,註解掉一行:
...
#module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
...
二.
VersionConflict: (WebOb 0.9 (.../google_appengine/lib/webob), Requirement.parse('WebOb>=0.9.4'))
移走 google_appengine/lib/webob 來避免這錯誤:
mv google_appengine/lib/webob/ google_appengine/webob/
即 Google Appengine 1.1.7 隨附的 webob 版本 (0.9) 未達 Pylons 0.9.7 的要求 'WebOb>=0.9.4'
註:如果你有跑其它 App Engine apps,這個 google_appengine 最好單獨就給 Pylons 使用,以免造成其它程式的問題。
好,是時候了:
/usr/bin/python2.5 google_appengine/dev_appserver.py my-app
## 我使用自己 compile 的 /usr/bin/local/python2.5 google_appengine/dev_appserver.py my-app
主要參考:
Appengine-Monkey: http://code.google.com/p/appengine-monkey/wiki/Pylons
註二:
自己 compile 的 Python 要支援 SSL 才能跑 Google App Engine,在 Ubuntu 8.10 下就是裝完 libssl-dev 後重新 make && make install。
from http://everydayquest.blogspot.com/2009/01/memo-of-pylons-on-google-app-engine.html
by gvanrossum@gmail.com (Guido van Rossum)
Python is 19 years old now. I started the design and implementation of the language on a cold Christmas break in Amsterdam, in late December 1989. It started out as a typical hobby project. Little did I know where it would all lead.
With Python's coming of age, I am going to look back on the history of the language, from the conception as a personal tool, through the the early years of community building, (If Guido was hit by a bus?), all the way through the release of Python 3000, almost 19 years later. It's been quite an adventure, for myself as well as for the users of the language.
This won't be an ordinary blog post -- it'll be an open-ended series. I may invite guest writers. I'll be touching upon many aspects of the language's history and evolution, both technical and social.
I'll start with the gradual publication of material I wrote a few years ago, when I was invited to contribute an article on Python to HOPL-III, the third installment of ACM's prestigious History of Programming Languages conference, held roughly every ten years. Unfortunately, the demands of the rather academically inclined reviewers were too much for my poor hacker's brain. Once I realized that with every round of review the amount of writing left to do seemed to increase rather than decrease, I withdrew my draft. Bless those who persevered, but I don't believe that the resulting collection of papers gives a representative overview of the developments in programming languages of the past decade.
The next destination of the draft was a book on Python to be published by Addison-Wesley. Again, the mountain of raw material that I had collected was too large and at the same time too incomplete to serve as a major section of the book, despite the editing help I received from David Beazley, a much better writer than I am.
As they tell prospective Ph.D. students, the best way to eat an elephant is one meal at a time. So today I am publishing the first bit of the elephant, perhaps still somewhat uncooked, but at least it's out there. Hopefully others who were there at the time can help clear up the inevitable omissions and mistakes. I have many more chapters, each still requiring some editing, and I expect this to be a long-running series. Therefore I am starting a separate blog title for this, unimaginatively called The History of Python. Follow the link and enjoy!
from http://neopythonic.blogspot.com/2009/01/history-of-python-introduction.html
这篇文章主要介绍了相比于python2.6,python3.0的新特性。更详细的介绍请参见python3.0的文档。
Common Stumbling Blocks
本段简单的列出容易使人出错的变动。
String and Bytes
PEP3101:字符串格式化的新方法
PEP3106:修补了dict的keys(),items(),values()方法
PEP3107:函数注解(Function Annotations)
Exception Stuff
New Class and Metaclass Stuff
其他的语言变化
这里列出大多数的python语言核心和内建函数的变化。
Optimizations
模块变动(新的,改进的和废弃的)
Build and C API Changes
Python’s build process和C API的改动包括:
其他的改动和修复
在源码里分散一系列的改进和bug修复。changes log表明,从2.6到3.0,有XXX个改动和YYY的bug修复。
from http://jjz.javaeye.com/blog/259156
Shell:~/tools/Py3k/bin >: ./python3.0
Python 3.0 (r30:67503, Dec 4 2008, 23:27:21)
[GCC 3.3.5 (propolice)] on openbsd4
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.uname()
('OpenBSD', 'obsd.org', '4.4', 'GENERIC.MP#0', 'i386')
>>> import sys
>>> for line in sys.path: print(line)
...
/home/Py3k/mylibs/lib/Python
/home/Py3k/tools/Py3k/lib/python30.zip
/home/Py3k/tools/Py3k/lib/python3.0
/home/Py3k/tools/Py3k/lib/python3.0/plat-openbsd4
/home/Py3k/tools/Py3k/lib/python3.0/lib-dynload
/home/Py3k/tools/Py3k/lib/python3.0/site-packages
>>>
Python 3.0 (a.k.a. "Python 3000" or "Py3k") is a new version of the language that is incompatible with the 2.x line of releases. The language is mostly the same, but many details, especially how built-in objects like dictionaries and strings work, have changed considerably, and a lot of deprecated features have finally been removed. Also, the standard library has been reorganized in a few prominent places.
Here are some Python 3.0 resources:
Please report bugs at http://bugs.python.org
This is a proeuction release; we currently support these formats:
MD5 checksums and sizes of the released files:
ac1d8aa55bd6d04232cd96abfa445ac4 11191348 Python-3.0.tgz
28021e4c542323b7544aace274a03bed 9474659 Python-3.0.tar.bz2
054131fb1dcaf0bc20b23711d1028099 13421056 python-3.0.amd64.msi
2b85194a040b34088b64a48fa907c0af 13168640 python-3.0.msi
本FAQ内容包含:
0.Python 资源索引
1.Python的版本和下载方式
2.推荐书籍
3.推荐站点
4.Python有什么IDE
5.哪有Python电子书
6.使用easy_install安装第三方程序包
7.Python需要编译么?如何做成.exe文件
8.如何在代码中使用中文
9.Python有哪些图形库
10.一些网址
11.filter, map, reduce, zip函数
12.访问GAE,修改hosts文件的方法
0.Python 资源索引
http://wiki.woodpecker.org.cn/mo ... on/LpyAttach2ResIdx
大多数资料都在上面了,目录如下:
1. Python 资源索引
1. Py 语言自身
2. Py 文本处理
3. Py 数据库应用
4. Py 网络应用
5. Py 嵌入系统
6. Py 多媒体支持
7. Py 应用扩展
8. Py 科学计算
9. Py 行业应用
10. Py 教育支持
11. Py 集锦资源
2. 资源回收
1.Python的版本和下载方式
A.至2008年10月,Python最新的版本为2.6。Python3000尚处于测试状态。Python的官方下载地址是:
http://www.python.org/download/
2.推荐书籍:
A.1、《A Byte of Python(简明python教程)》
http://www.byteofpython.info/language/chinese/index.html
2、《Dive into Python(Python研究)》
http://www.woodpecker.org.cn/diveintopython/index.html
3、《Learning Python》
4、《Programming Python》
第一本书非常简短,也有中文译本“简明Python教程”,是想速成(几小时)者的首选。另外在http://www.python.org/doc有
很多官方的文档和教程,非常不错。
3.推荐站点:
A.1、啄木鸟社区
http://www.woodpecker.org.cn/
2、Python@Newsmth
(wahahaha~~~)
3. 中文用户组
CPUG:
http://python.cn
[email]python-chinese@lists.python.cn[/email] (邮件列表) //已经停止服务,转CPyUG吧。
CPyUG: 华蟒用户组
https://groups.google.com/group/python-cn
PyTUG: Python 語言台灣使用者群組
https://groups.google.com/group/pythontw
4. 中文论坛:
1. Python@CU
http://bbs.chinaunix.net/forumdisplay.php?fid=55
4.Python有什么IDE
A.Python官网有一份IDE列表,很全:
http://wiki.python.org/moin/IntegratedDevelopmentEnvironments
如果看了上面的列表还是不知道自己该选哪个,推荐看置底的“Python IDE比较与推荐”
5.哪有Python电子书?
A.精华区x-5收录了一些经典的电子书。下载请用web方式。
强烈推荐开放图书计划:
http://code.google.com/p/openbookproject/ 聚集大量的Python技术图书.
另外这两个地方有很多python的电子书:
http://www.longtengwang.com/Soft/yiyong/Python/Index.html
http://www.pythonid.com/html/wendangxiazai/index.html
想看纸质书,在书店里没有找到,那么最简单的办法是去淘宝网。
6. 使用easy_install安装第三方程序包:
A.参考:http://blog.chinaunix.net/u1/42287/showart_405102.html
http://www.ibm.com/developerworks/cn/linux/l-cppeak3.html
1. 安装
wget -q http://peak.telecommunity.com/dist/ez_setup.py
sudo python ez_setup.py
2. 使用
sudo easy_install CherryPy
sudo easy_install -Z web.py-0.21.tar.gz
B. 想看看有什么第三方程序包:http://pypi.python.org/pypi
7.Python需要编译么?如何做成.exe文件?
A.Python不需要用户专门去编译它,第一次运行时,在运行过程中,Python的解析器会自动将代码编译为.pyc。一般来讲,运
行结束后不会自动删除.pyc文件。
在Windows下,可以用py2exe等工具将代码编译为.exe文件。原理是py2exe会将必要的python解析器也打包进去。所以做成的
.exe有几M,如果有图形界面,就会有十几M,而且运行速度不会有提升。
8.如何在代码中使用中文
A.在Python2.5或之前的版本中,代码里默认是不能有中文的,包括注释。解决方法是在代码一开头加上:
# -*- coding: gbk -*-
或
# -*- coding: utf-8 -*-
或
#coding=utf-8
具体选哪一种看具体情况。一般来讲,如果不是网络编程,统一用utf-8就OK了,包括与MySQL的交互也可以用utf-8搞定。如
果是网络编译,特别是与FTP打交道,推荐使用gbk,可以省去很多麻烦。
注意本法没有涉及不同编码的转换。
9.Python有哪些图形库
A.常用的有tk/tcl, PyGtk,PyQt和wxPython。都是跨平台且开源的。第一个是Python自带的,但比较难用且难看。PyQt和
wxPython都漂亮好用且文档/demo很棒,目前来看PyQt4比wxPython更胜一畴。
10. 一些网址
Python: www.python.org
ActivePython: www.activestate.com
Stackless Python: www.stackless.com
IronPython: www.ironpython.com
PyPy: pypy.org
JPython: www.jpython.org
Django: www.djangoproject.com
Mod_Python: www.modpython.org
Webware: www.webwareforpython.org
CherryPy: www.cherrypy.org
Web.py: webpy.org
Zope: www.zope.org
Turbogears: www.turbogears.org
Google AppEngine: http://code.google.com/appengine
Twisted: http://twistedmatrix.com
Beautiful Soup: http://crummy.com/software/BeautifulSoup
PythonWeb: www.pythonweb.org
JabberPy: http://jabberpy.sourceforge.net
pyGoogle: http://pygoogle.sourceforge.net
libgmail: http://libgmail.sourceforge.net
pyExpect: http://pexpect.sourceforge.net
MySQLdb: http://sourceforge.net/projects/mysql-python
PyGreSQL: www.pygresql.org
psycopg: www.initd.org/pub/software/psycopg
cx_Oracle: www.cxtools.net
SQLAlchemy: www.sqlalchemy.org
scipy: www.scipy.org
NumPy: http://numpy.scipy.org
numarray: www.stsci.edu/resources/software_hardware/numarray
matplotlib: http://matplotlib.sourceforge.net
WxPython: www.wxpython.org
PyGtk: www.pygtk.org
PyQt: http://trolltech.com/products/qt
Tkinter 3000: http://effbot.org/zone/wck.htm
PIL: www.pythonware.com/products/pil
pyOpenGL: http://pyopengl.sourceforge.net
pySoundic: http://pysonic.sourceforge.net
pyMedia: http://pymedia.org
FMOD: http://www.fmod.org
pyMIDI: http://www.cs.unc.edu/Research/assist/developer.shtml
Python Documentation Online: http://pydoc.org, http://docs.python.org
Python-cn: http://python.cn
Pythonic: http://www.woodpecker.org.cn
The Daily Python-URL: http://www.pythonware.com/daily/index.htm
Python Package Index: http://pypi.python.org
Planet Python: http://www.planetpython.org
Pythonite: http://www.pythonite.org
Useless Python: http://www.uselesspython.com
Python Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python
Python Sidebar: http://www.edgewall.org/python-sidebar
Python Source: http://pythonsource.com
11.filter, map, reduce, zip函数
1. filter(function, sequence) 返回序列,为原序列中能使function返回true的值
>>>a=[1,2,3,4]
>>>filter(lambda x:x%2, a)
[1, 3]
2. map(function, sequence, [sequence...]) 返回序列,为对原序列每个元素分别调用function获得的值.
可以传入多个序列,但function也要有相应多的参数,如
map(lambda x,y,z:x+y+z,range(1,3),range(3,5),range(5,7))
计算过程为
1+3+5=9
2+4+6=12
返回[9,12]
3. reduce(function,sequence,[init])
返回一个单值为,计算步骤为 :
* 第1个结果=function(sequence[0],sequence[1])
* 第2个结果=function(第1个结果,sequence[2])
* 返回最后一个计算得值
* 如果有init,则先调用function(init,sequence[0])
* sequence只有一个元素时,返回该元素,为空时抛出异常.
如 reduce(lambda x,y:x+y,range(3),99) 的计算为
99+0=99 => 99+1=100 => 100+2=102
返回102
注:实际使用中用内建函数sum来完成这个累加更合适,如这里等价sum(range(3),99)
4. zip用于多个sequence的循环
questions=['name', 'quest', 'favorite color']
answers=['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
print 'What is your %s ? It is %s.' % (q,a)
输出:
What is your name ? It is lancelot.
What is your quest ? It is the holy grail.
What is your favorite color ? It is blue.
12.访问GAE,修改hosts文件的方法
Shell:~/dev/AppEngine/google_appengine/n23 >: tail -n 3 /etc/hosts
209.85.171.118 n23.appspot.com
64.233.189.99 appengine.google.com
#203.208.35.100 appengine.google.com
Shell:~/dev/AppEngine/google_appengine/n23 >:
在 Ruby on Rails 的官方網站上有 15 分鐘作出一個 weblog 的 screencast,的確 demo 了 RoR 開發的快速。不過萬萬不可太迷信只有 RoR 能這麼神速,根據最近擠出一點時間看 django 的東西後,我也想先來作個「10分鐘做出 blog 的挑戰」。(由於還不太會用製作 screen cast 的軟體,所以只能用文字介紹..)這篇文章只是描述一下建構過程,所以不會介紹 django 環境的安裝設定,請讀者見諒。
稍微簡介一下 django,它是一個基於 Python 語言的 Web 開發框架(framework)。
在 django 的環境裡,一個 project 裡可以有很多個 application,如此一來同一個 project 下的 application 便能共用同一套環境設定。所以我們先在命令列下執行 django-admin.py 來建立一個 project:
先來改一下 demo/settings.py 的設定,裡面設定我們會用 sqlite3 來作資料庫的引擎,然後產生一個 demo.db 的檔案來當資料庫,再設定一些時區及 template 目錄等:
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = 'demo.db'
...
TIME_ZONE='Asia/Taipei'
LANGUAGE_CODE='zh-tw'
...
TEMPLATE_DIRS = (
...
'.',
)
INSTALLED_APPS = (
'django.contrib.admin',
..
'demo.blog', # 等一下就會產生
)
然後在 demo 目錄下建立一個 blog 的 app:
然後在 demo/blog/models.py 裡建立需要的 model(DB Table):
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=32)
def __unicode__(self):
return self.name
class Admin:
pass
class Article(models.Model):
title = models.CharField(max_length=64)
published_at = models.DateTimeField('date published')
content = models.TextField()
category = models.ForeignKey(Category)
def __unicode__(self):
return self.title
class Admin:
pass
然後可以看看 django 產生的 SQL DDL,確定的話就用 syncdb 來建立資料庫表格:
其中會要求你建立一個管理者帳號,這是為了之後進管理介面發表文章使用的帳號。完成這些動作之後,修改一下 demo/urls.py 的內容:
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^blog/', include('demo.blog.urls')),
(r'^admin/', include('django.contrib.admin.urls')),
)
先在 demo/blog/ 下建立一個 urls.py 的檔案,然後在命令列下輸入 python manage.py runserver,再打開瀏覽器輸入網址 http://localhost:8000/admin/ 馬上就有一個後台介面可以使用了呀!

登入後你就可以直接建立 Category 及 Artical 的內容,這不就是一個現成的文章發表介面了嗎?一開始操作到現在不會超過5分鐘吧!
可以發表文章之後,當然是要能夠瀏覽呀,所以我們馬上打開 demo/blog/urls.py 這個檔案,然後貼上下列的 code:
from django.conf.urls.defaults import *
from demo.blog.models import Article
info_dict = {
'queryset': Article.objects.all(),
}
urlpatterns = patterns('',
(r'^$', 'django.views.generic.list_detail.object_list', info_dict),
(r'^(?P<object_id>\d+)/$', 'django.views.generic.list_detail.object_detail', info_dict),
)
然後再分別建立 demo/blog/article_list.html 及 demo/blog/article_detail.html 這兩個檔案,分別表示文章列表及文章內容:
article_list.html:
{% if object_list %}
{% for article in object_list %}
<div class="article">
<div class="title"><a href="/blog/{{ article.id }}">{{ article.title }}</a></div>
</div>
{% endfor %}
{% else %}
<p>對不起沒有文章喔!</p>
{% endif %}
article_detail.html:
<div class="article">
<div class="title">標題: {{ object.title }}</div>
<div class="pub_date">{{ object.published_at }}</div>
<div class="content">{{ object.content }}</div>
<div class="category">發表於: {{ object.category.name }}</div>
</div>
<p><a href="/admin/blog/article/{{ object.id }}">修改</a></p>
<p><a href="/blog">BACK</a></p>
這樣很快就弄出一個很像樣的 blog (只是不能留言 XD),網址在 http://localhost:8000/blog/。
很快吧!當然我忽略了美工,也沒有客製化一下後台,不過 Web 開發愈來愈可怕了….真怕這種開發框架愈來愈多,老板都覺得寫網頁沒什麼了呢!
值得一提的是,django 在 runserver 之後,都會把程式碼 compile 成 pyc 檔,看起來效率應該還不錯,也許要等我多玩熟一點才能做些實驗囉。
from http://blog.ericsk.org/archives/815
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os
def f(his, n):
lines = open(os.path.join(os.getenv('HOME'), his)).readlines()
d = {}
for line in lines:
line = line.split()
if not line: continue
s = line[0]
if line[0] == 'sudo':
s = line[1]
d[s] = d.get(s, 0) + 1
l = sorted(d.items(), key=lambda t: t[1], reverse=True)
for t in l[:n]:
print '%s : %d' % (t[0].ljust(16), t[1])
if __name__ == '__main__':
from optparse import OptionParser
parser = OptionParser()
parser.add_option('-f', '--file', dest='f', default='.history',
help='the history file', metavar='FILE')
parser.add_option('-c', '--count', dest='c', type='int', default='30',
help='for display count', metavar='COUNT')
(options, args) = parser.parse_args()
f(options.f, options.c)
运行结果:
Shell:~ >: count_his_cmd
cd : 4895
ls : 4533
vi : 988
man : 679
hitfm : 583
cat : 532
ifconfig : 414
ant : 401
rm : 386
lt : 349
ll : 341
tmp : 340
svn : 333
tlist : 332
top : 311
my : 292
exit : 278
run : 277
unlcall : 249
pkg_list : 249
glib : 242
locate : 235
shutdown : 226
bbs.sh : 220
check : 216
ping : 215
pkill : 198
mv : 196
vpn : 190
sock : 186
Shell:~ >:
from http://code.google.com/p/mylibs/source/browse/trunk/tools/Python/count_history_cmd.py
We are pleased to announce the release of Python 2.6 (final), a new production-ready release, on October 1st, 2008.
There are a huge number of new features, modules, improvements and bug fixes. For information on what's changed, see:
- Andrew Kuchling's guide to What's New in Python 2.6.
- NEWS file contains a listing of everything that's new in each alpha, beta, and release candidate of Python 2.6.
- PEP 361.
Please report bugs at http://bugs.python.org
See also the license.
This is a production release; we currently support these formats:
MD5 checksums and sizes of the released files:
837476958702cb386c657b5dba61cdc5 10957859 Python-2.6.tar.bz2
d16d29a77db2cd3af882a591f431a403 13023860 Python-2.6.tgz
fe34764ad0027d01176eb1b321dd20c5 14503936 python-2.6.amd64.msi
6c62c123d248a48dccbaa4d3edc12680 14173184 python-2.6.msi
29a1a22f8d9fd8a4501b30d97fbee61c 23593748 python-2.6-macosx2008-10-01.dmg
The signatures for the source tarballs above were generated with GnuPG using release manager Barry Warsaw's public key which has a key id of EA5BBD71. The Windows installers was signed by Martin von Löwis' public key which has a key id of 7D9DC8D2. The signature on the Mac disk image was signed by Benjamin Peterson's public key which has a key id of A4135B38.
Administrators installing Python for all users on Windows Vista either need to be logged in as Administrator, or use the runas command, as in:
runas /user:Administrator "msiexec /i <path>\<file>.msi"
The documentation has also been updated. You can browse the HTML on-line or download the HTML
Minimal Software Transactional Memory & Simplified SOA using Kamaelia
"I love Zeppelins, and you should too" - Simon Willison's not-Python-related talk
Writing Parsers and Compilers with PLY (PDF) - Originally at PyCON'07, but presented to fill a cancellation.
Resolver One: Python Inside and Outside the Spreadsheet Grid (plus links to the slides for talks by other Resolver people)
Shell:~/tmp >: rpm -qi ipython
Name : ipython Relocations: (not relocatable)
Version : 0.8.2 Vendor: Fedora Project
Release : 1.fc9 Build Date: 2007年12月13日 星期四 09时21分06秒
Install Date: 2008年09月19日 星期五 12时11分45秒 Build Host: ppc4.fedora.phx.redhat.com
Group : Development/Libraries Source RPM: ipython-0.8.2-1.fc9.src.rpm
Size : 4124412 License: BSD
Signature : DSA/SHA1, 2008年04月11日 星期五 04时10分26秒, Key ID b44269d04f2a6fd2
Packager : Fedora Project
URL : http://ipython.scipy.org/
Summary : An enhanced interactive Python shell
Description :
IPython provides a replacement for the interactive Python interpreter with
extra functionality.
Main features:
* Comprehensive object introspection.
* Input history, persistent across sessions.
* Caching of output results during a session with automatically generated
references.
* Readline based name completion.
* Extensible system of 'magic' commands for controlling the environment and
performing many tasks related either to IPython or the operating system.
* Configuration system with easy switching between different setups (simpler
than changing $PYTHONSTARTUP environment variables every time).
* Session logging and reloading.
* Extensible syntax processing for special purpose situations.
* Access to the system shell with user-extensible alias system.
* Easily embeddable in other Python programs.
* Integrated access to the pdb debugger and the Python profiler.
一定要装上这个...