Smarty基础知识学习

Smarty学习
1 基本语法
1.1 注释
{* this is a comment *}
1.2 函数
{funcname attr1="val" attr2="val"}.
1.3 双引号
{include file="subdir/$tpl_name.tpl"} <-- will replace $tpl_name with value {cycle values="one,two,`$smarty.config.myval`"} <-- must have backticks 1.4 数学计算 可以直接进行, {$foo|truncate:"`$fooTruncCount/$barTruncFactor-1`"} {assign var="foo" value="`$foo+$bar`"} 2 变量 2.1 简单变量 .php中assign的变量可以直接如下方式调用: Hello {$firstname}, glad to see you could make it. 也可以如下方式进行打印: {$Name} {$Contacts[row].Phone}

2.2 关联数组
利用关键字arry来定义关联数组。
index.php:

$smarty = new Smarty;
$smarty->assign('Contacts',
array('fax' => '555-222-9876',
'email' => 'zaphod@slartibartfast.com',
'phone' => array('home' => '555-444-3333',
'cell' => '555-111-1234')));
$smarty->display('index.tpl');

index.tpl:

{$Contacts.fax}
{$Contacts.email}
{* you can print arrays of arrays as well *}
{$Contacts.phone.home}
{$Contacts.phone.cell}

输出结果:

555-222-9876
zaphod@slartibartfast.com
555-444-3333
555-111-1234

也可以利用关联数组的索引来访问:
{$Contacts[0]}
{$Contacts[1]}
{* you can print arrays of arrays as well *}
{$Contacts[2][0]}
{$Contacts[2][1]}

2.3 从配置文件中读取的变量
{config_load file="foo.conf"}
这种方式导入的配置文件中的变量可以通过如下两种方式调用:
利用$smarty.config.调用或者{#pageTitle#}

2.4 Smarty保留变量
请求信息
比如:
{* display value of page from URL (GET) http://www.domain.com/index.php?page=foo *}
{$smarty.get.page}

{* display the variable "page" from a form (POST) *}
{$smarty.post.page}

{* display the value of the cookie "username" *}
{$smarty.cookies.username}

{* display the server variable "SERVER_NAME" *}
{$smarty.server.SERVER_NAME}

{* display the system environment variable "PATH" *}
{$smarty.env.PATH}

{* display the php session variable "id" *}
{$smarty.session.id}

{* display the variable "username" from merged get/post/cookies/server/env *}
{$smarty.request.username}

当前时间
{$smarty.now|date_format:"%Y-%m-%d %H:%M:%S"}

{$smarty.const._MY_CONST_VAL}
{$smarty.capture}
{$smarty.config}
{$smarty.section}, {$smarty.foreach}
{$smarty.template}
3 变量调节器
举例
{* Uppercase the title *}

{$title|upper}

{* Truncate the topic to 40 characters use ... at the end *}
Topic: {$topic|truncate:40:"..."}

{* format a literal string *}
{"now"|date_format:"%Y/%m/%d"}

{* apply modifier to a custom function *}
{mailto|upper address="me@domain.dom"}

{$articleTitle|@count}:返回article数组的个数。
而{$articleTitle|count}标示对数组中的每个元素进行count操作。

Capitalize:首字大写
{$articleTitle|count_characters}:不计算空格计数
{$articleTitle|count_characters:true}:计算空格计数

{$articleTitle|cat:" yesterday."}:将yesterday链接到变量后面。
count_paragraphs[计算段数]
count_sentences[计算句数]
count_words[计算词数]
{$smarty.now|date_format:"%A, %B %e, %Y"},具体含义参考strftime()
default[默认值]:变量为空时的默认值

escape[编码],html,htmlall,url,quotes,hex,hexentity,javascript
举例:
{$articleTitle|escape}
{$articleTitle|escape:"html"} {* escapes & " ' < > *}
{$articleTitle|escape:"htmlall"} {* escapes ALL html entities *}
{$articleTitle|escape:"url"}
{$articleTitle|escape:"quotes"}

indent[缩进]
lower
nl2br
regex_replace
{$articleTitle|regex_replace:"/[\r\t\n]/":" "}
replace
{$articleTitle|replace:"Garden":"Vineyard"}
{$articleTitle|replace:" ":" "}
spacify——插空
在字符串的每个字符之间插入空格或者其他的字符(串)
{$articleTitle}
{$articleTitle|spacify}
{$articleTitle|spacify:"^^"}

string_format
{$number|string_format:"%.2f"}
{$number|string_format:"%d"}
参考sprintf.

strip
{$articleTitle|strip}
{$articleTitle|strip:" "}:将空格替换为 
strip_tags
去除html标签
truncate
{$articleTitle|truncate}
{$articleTitle|truncate:30}
{$articleTitle|truncate:30:""}
{$articleTitle|truncate:30:"---"}
{$articleTitle|truncate:30:"":true}
{$articleTitle|truncate:30:"...":true}
默认情况下,smarty会截取到一个词的末尾。
如果你想要精确的截取多少个字符,把第三个参数改为"true"

upper
大写
wordwrap
行宽约束
{$articleTitle|wordwrap:30}
{$articleTitle|wordwrap:20}
{$articleTitle|wordwrap:30:"
\n"}
{$articleTitle|wordwrap:30:"\n":true}

Posted in 2696 | Tagged , , , | Leave a comment

python_python_cheatsheet.png

python_cheatsheet.png

python_cheatsheet.png

Posted in 2696 | Tagged , , | Leave a comment

python写的ftp上传脚本

具体代码如下,

用法为:


import os, re
from os.path import join, abspath, isfile, isdir, exists, basename
from shutil import copyfile, copytree, rmtree
from time import strftime, strptime, localtime
import sys
import ftplib
import socket
import urllib


def usage(): print "Usage : %s file_to_upload ftp://user:pass@host:port/dir/path" % os.path.basename(sys.argv[0]) sys.exit(0)


def parseOption(): '''传来的参数示例为:


./ftpupload ./file ftp://帐号:密码@主机:端口/路径/文件 将ftp地址归一化,统一加上ftp:// 然后利用正则去匹配 ''' if len(sys.argv)!=3: usage() FILENAME=sys.argv[1] ftpUrl=sys.argv[2].split("://",2)[1] if not re.search('://',ftpUrl): realUrl='ftp://%s'%ftpUrl


if not re.search('^ftp://.*?:.*?@.*',realUrl): USERNAME="" PASSWORD="" endPart=re.search('^ftp://(.*)',realUrl).groups()[0] else: (USERNAME,PASSWORD,endPart)=re.match('^ftp://(.*?) :( .*?)@(.*)',realUrl).groups()


temp=re.search('(.*?) :( [0-9]*)(.*)',endPart) if temp: (HOST,PORT,DIRN)=temp.groups() else: PORT=21 temp=re.search('(.*?)(\/.*)',endPart).groups() if temp: (HOST,DIRN)=temp else: HOST=hostPath DIRN=''


if not os.path.isfile(FILENAME): print "No such File :%s"%FILENAME usage() try: if (int(PORT)<0 or int(PORT)>65535): print "Port %s error:%s"%PORT except ValueError,e: print "Error:Url format error:[%s]"%sys.argv[2]


return (FILENAME,HOST,PORT,DIRN,USERNAME,PASSWORD)


class MyFtp(object): def __init__(self,uploadFileName,host,port,dirn="",username="",password=""): self.HOST=host self.USERNAME=username self.PASSWORD=password self.DIRN=dirn self.FILENAME=uploadFileName


def upload(self): '用来上传文件' try: self.ftp=ftplib.FTP(self.HOST) except (socket.error,socket.gaierror),e: print "Error:connect %s error"%self.HOST return -1


try: self.ftp.login(self.USERNAME,self.PASSWORD) except (ftplib.error_perm): self.ftp.quit() print "Error:permission error" return -1


try: self.ftp.cwd(self.DIRN) except ftplib.error_perm: self.ftp.quit print "Erro:can't cwd to %s"%self.DIRN return -1


try: myFile=open(self.FILENAME,'rb') self.ftp.storbinary('STOR %s'%self.FILENAME,myFile) except ftplib.error_perm: self.ftp.quit() print "Error:can't upload %s"%self.FILENAME return print "upload done."


def get(self): '''用来下载文件'''


if __name__=="__main__": myArg=parseOption() myFtp=MyFtp(*myArg) myFtp.upload()
Posted in 2696 | Tagged , , | Leave a comment

python学习笔记——socket相关

socket相关:

SOCK_STREAM:TCP
SCOK_DGRAM:UDP

from socket import *

tcpsock=socket.socket(socket.AF_INET,socket.SOCK_STREAM,protocol=0);

twisted:

基于时间驱动的网络框架,允许使用和开发完全异步的网络应该用程序和协议。

多线程:

io密集型的程序会有更多的收益。

thread.exit()

不建议使用thread模块,而改用更加高级的threading模块。

Posted in 2696 | Tagged , , | Leave a comment

python学习笔记——执行其他程序

执行其他程序:

python -m CGIHTTPServer,将启动一个server。

result=os.system(cmd):result为system的返回值。

fork():

exec*():因为用对应的程序替代了python解释器,所以一般没有返回值,除非发生了异常。

spawn*():恩,需要跟进这里的先进之处。

popen():为system()和file对象的结合,f=popen('cmd'),然后f就为cmd的标准输出组成的一个文件。

startfile(path):windows专用,用关联的程序执行路径。
这个很有用呀,比如启动另外一个程序来检查测试结果,
比如将一系列操作流程连贯起来。

subprocess模块。可以代替上述命令,
包含call(),Popen(),而且更加灵活,可以指定stdout,stderr等。

>>> a=Popen('dir',stdout=PIPE).stdout
>>> for x in a:
print x

退出执行:

sys.exit():退出首选

os.exit():不清理直接退出。

os.kill():杀掉。

Posted in 2696 | Leave a comment

python——新特性、内建函数

metaclass:用来生成新的class的class.

需要在子类中定义:

__metaclass__=Metac(Metac为定义的metaclass,而metaclass继承自type)

其他相关模块

UserDict

UserList

UserString

types

operator

让实例可以被调用:

__call__()

代码对象==封装==》函数对象==封装==》方法。

compile(string,file,type):
compile预编译有助于提高性能。
file一般为''
type为[eval,single(单一可执行语句),exec(可执行语句组)],分别对应[eval(),exec,exec]

eval('3+4')可以,不过eval('h=3')是不行的,必须用exec('h=3').

利用exec执行python文件

f=open('./file.py','r')
exec f

input(prompt):

相当于eval(raw_input(prompt))

Posted in 2696 | Leave a comment

python学习笔记——Object-Oriented面向对象

类和实例。

如果无同名,则类属性会覆盖实例属性。

>>> class C(object):
version=1.2

>>> c=C()
>>> print C.__dict__
{'__dict__': <attribute '__dict__' of 'C' objects>, '__module__': '__main__', 'version': 1.2, '__weakref__': <attribute '__weakref__' of 'C' objects>, '__doc__': None}
>>> c.__dict__
{}

对类来说,version是不可变的,对实例的操作不会影响到version。

而list ,dict等是可变的,对实例的操作会影响到类。

@staticmethod

@classmethod

可以定义静态方法和类方法。而不用以前的foo=staticmethod(foo)这种很ugly的语法了。

绑定和非绑定:

class C(P):

def __init__(self):

P.__init__(self)  #P为类名,所以需要显示传入self参数。

#do my own initialization...

继承

C.__class__:当前类名

C.__bases__:父类名。

__init__等函数也是会被继承的。

__new__和__init__的区别是什么?不知道。

从标准类派生:

比如自动四舍五入的float.

比如自动按key排序的词典。

class sDcit(dict):

def keys(self):

return sorted(super(sDict,self).keys())

多重继承以及MRO

__slots__:__dict__就会失去作用,用以防止内存占用过大,防止属性被动态的添加。

__getattr__:当属性不能在局部变量以及全局变量被找到的时候,调用此函数。

__getattribute__:查找属性的时候,直接调用此函数。

描述符:

__get__/__set__/__delete__:

描述符是对象属性的一个代理。

后续再深入阅读吧。

Posted in 2696 | Tagged , , | Leave a comment

python核心编程里面有不少错误

比如306页的示例,

[code=python]

from random import *

def randomGen(aList):
'用来从给定的列表或者元组中返回随机的元素'
from random import *

def randomGen(aList):
'用来从给定的列表或者元组中返回随机的元素'
while len(aList) > 0:
yield aList.pop(randint(0,len(aList)-1))

if __name__=="__main__":
testList=[x for x in range(10)]
for i in randomGen(testList):
print i

[/code]

少了一个-1。

啊哈,还有一些缩进的错误。

不过,这并不影响python核心编程成为一本好书,强烈推荐之。

Posted in 2696 | Tagged , , , , | 1 Comment

python学习笔记——functions函数

函数支持:

func(*tuple_or_list_args,**dict_args)

装饰器:

非常好用的功能,java的next generation testing 就采用了这个理念,称为testNG.

@deco2
@deco1
def foo()

等同于:

foo=deco2(deco1(foo)).
所以,deco2必须返回一个func.

一个时间戳的封装函数:

def  newfunc(func):
def wrapFunc():
print '[%s] %s() called' %(ctime(),func.__name__)
return func()
return wrapFunc

@newfunc

def foo():
#....

利用装饰器,实现一套python的自动化测试方案。
python调用c++,
python的case用@deco装饰,
运行的时候,……。

传递函数:

def convert(func,seq):
return [func(one) for one in seq]
print convert(long,myseq)
print convert(int,myseq)

测试函数testit.py
将结果封装成一个列表

def testit(func,*nkwargs,**kwargs):
try:

retval=func(*nkwargs,**kwargs)
result=[True,retval]

except exception,e:

result=[False,str(e)]

retrun result

函数式编程

lambda[arg1[,args2....argN]]:expression
其中expression是这个匿名函数的返回值。

内建函数:

apply():已经废弃。

filter(func,seq):如果seq[n]使func返回为真,则将seq[n]append到结果队列中去。比如filter(lambda n:n%2,seq),为获得seq中所有的奇数。
重构一下:
[n for n in seq if n%2]

map():
可以考虑利用map,reduce对比测试结果。
比如map(lambda x :x **2,range(10)):返回0-9的平方组成的列表。
map(lambda x,y :x +y,[1,2,3],[7,10,100])
返回:[8,12,103]

reduce():
也叫做折叠。
比如reduce(func,[1,2,3])等同于:func(func(1,2),3)
而reduce(lambda x,y :x +y,range(100)) ,则返回0+1+2+3..+99的值。

偏函数partial function application,PFA:

from functools import partial
baseTwo=partial(int,base=2)   #此处base是必须的
就定义了一个偏函数,将给定的二进制的数字转化为十进制的数字。

工具自动化:
提供一个功能超级强大的函数,包括N多的参数,
同时,利用偏函数,将一些参数固定,开放一批更加易于使用的接口。

啊哈,很好的方法。

利用Tkinter来开发一批工具,易于使用,具有ui界面。哈哈,易用性。

闭包:

A函数中定义了B函数,
然后B函数引用了A函数作用范围内的变量,
最后A函数返回B函数,则构成了一个闭包。

啊哈,有点绕,不过这个闭包的作用域是封闭的.

Posted in 技术 | Tagged , , , , | Leave a comment

python学习笔记——exception 以及sys

一个原则:不要处理并忽略所有错误,只处理你知道原因的错误,比如ctrl+C信号的处理等。

try

except# try段发生错误执行except部分。

else   # try段没有发生错误执行else部分。

finally#始终执行finally部分。

with语句

with open('path/file','r') as f
for line in f:
#do something.
这个f不需要显示的关闭,哈哈,with已经做了处理了。

raise exclass(args)

assert 1==1

一个通用的处理异常的方法:

try:
.....
except:
import sys
exc_tupl=sys.exc_info()
for i in exc_tupl:

print i

Posted in 2696 | Tagged , , , | Leave a comment