2008年6月29日 星期日

DiigoAPI

一直想把Diigo上的书签保存下来。Diigo本身提供API,那好,我就想用用看。找到示例代码:


var API_URL = 'http://api2.diigo.com/bookmarks';

var xmlHttp = false;
if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject){// code for IE5 and IE6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}

function onResponse() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200){
alert(xmlHttp.responseText);
}
}
}

/* GET: query bookmarks */

function queryBookmarks() {

if(xmlHttp){
try {
xmlHttp.onreadystatechange = onResponse;
xmlHttp.open("GET", "http://api2.diigo.com/bookmarks?rows=1&users=shengyan", true);
xmlHttp.send(null);
} catch (e) {
alert("Error:"+e)
}
}else{
alert('test')
}
}
非常奇怪的,分别在firefox3.0出现:
[Exception... "Access to restricted URI denied" code: "1012" nsresult: "0x805303f4 (NS_ERROR_DOM_BAD_URI)" location: "file:///J:/test.html Line: 35"]
这个找了很多地方,有个地方说是firefox的bug。不懂了。
但在IE下输入帐号和密码后,倒是可以争取取出来。

上述代码中使用了XMLHttpRequest(firefox或其他浏览器)或ActiveXObject(IE),从代码中可以看到XMLHttpRequest可以发送请求给服务器并得到responseText,具体可参见这里很详细的介绍了使用方法。

XMLHttpRequest更多资料:http://www.w3schools.com/XML/xml_http.asp

另外,关于User Agent。现在连上那个网址,要进行帐户验证。怎样才能让请求直接加上帐户信息呢。说是关于User Agent的,但是不知道如何加这个头。

2008年6月24日 星期二

Delta Goodrem

Lost Without You----Delta Goodrem

I know I can be a little stubborn sometimes
A little righteous and too proud
I just want to find a way to compromise
Cos I believe that we can work things out

I thought I had all the answers never giving in
But baby since you've gone I admit that I was wrong

All I know is I'm lost without you I'm not gonna lie
How am I going to be strong without you I need you by my side
If we ever say we'll never be together and we ended with goodbye don't know what I'd do ...I'm lost without you
I keep trying to find my way but all I know is I'm lost without you
I keep trying to face the day I'm lost without you

How am I ever gonna get rid of these blues
Baby I'm so lonely all the time
Everywhere I go I get so confused
You're the only thing that's on my mind

Oh my beds so cold at night and I miss you more each day
Only you can make it right no I'm not too proud to say

All I know is I'm lost without you I'm not gonna lie
How am I going to be strong without you I need you by my side
If we ever say we'll never be together and we ended with goodbye don't know what I'd do ...I'm lost without you
I keep trying to find my way but all I know is I'm lost without you
I keep trying to face the day I'm lost without you

If I could only hold you now and make the pain just go away
Can't stop the tears from running down my face
Oh

All I know is I'm lost without you I'm not gonna lie
How am I going to be strong without you I need you by my side
If we ever say we'll never be together and we ended with goodbye don't know what I'd do ...I'm lost without you
I keep trying to find my way but all I know is I'm lost without you
I keep trying to face the day I'm lost without you

Born to try----Delta Goodrem

Doing everything that I believe in
Going by the rules that I've been taught
More understanding of what's around me
And protected from the walls of love

All that you see is me
And all I truly believe

That I was born to try
I've learned to love
Be understanding
And believe in life
But you've got to make choices
Be wrong or right
Sometimes you've got to sacrifice the things you like

But I was born to try

No point in talking what you should have been
And regretting the things that went on
Life's full of mistakes, destinies and fate
Remove the clouds look at the bigger picture

And all that you see is me
And all I truly believe

That I was born to try
I've learned to love
Be understanding
And believe in life
But you've got to make choices
Be wrong or right
Sometimes you've got to sacrifice the things you like

But I was born to try

All that you see is me
All I truly believe
All that you see is me
And all I truly believe

That I was born to try

I've learned to love
Be understanding
And believe in life
But you've got to make choices
Be wrong or right
Sometimes you've got to sacrifice the things you like

But I was born to try

But you've got to make choices
Be wrong or right
Sometimes you've got to sacrifice the things you like

But I was born to try


Butterfly----Delta Goodrem

2008年6月23日 星期一

PT

今天第一次去做家教,没进门之前还是有点小紧张的,毕竟是第一次真正当老师。

是个很文静的女孩子,成绩还是不错的。主要教她数学和物理,数学应该没问题,但是物理对于我这个当初就没学好的家伙来说,真是个问题!

不过如果碰到不会的问题,尽量去寻找答案。毕竟经过了这么多年的学习,通过各种方法去寻找答案还是有一手的。

鱼还是渔?呵呵,当然是后者。

开端不错,希望接下来也能继续加油!

好了,开始做自己的事~

2008年6月22日 星期日

AWN


一直想安装个上图的这个东西——Avant Window Navigator(中文名叫停靠坞,呵呵,比较少见的名字)。今天终于忍不住安装上了。本来想完整安装Mac4Lin主题包,但应用了下,外观还不如现在的黑色主题好看。所以就仅仅安装AWN了。下载及安装方法参考这里。自定义设置后,最终效果如上图,有点花哨。

贴图:第一次扫描进来的图案。还是不怎么清晰。经过点ps后成为下面这幅模样。具体当时画的是什么东西,自己也不知道。纯粹按着手来,怎么顺怎么画。

2008年6月21日 星期六

MASS

  1. 世界真小。才发现4G Spaces原来是Yixin Chen的学生。厉害导师带的厉害博士。怎个“牛”字了得!理论研究加很棒的应用实践,这才叫研究。
  2. 而我自己,理论方面,至今还是杂七杂八的,什么都看。在别人看来,可能会觉得我好认真好努力,各个方面都涉及到。但自个儿好好想想,是因为时间太多,周围信息太丰富,知道的太少,导致对什么都感兴趣,仅仅留在表面的东西。哎。。。继续糊涂下去吧。
  3. 技术。今天看了篇我为什么鼓吹facebook,为什么唱衰OpenSocial?牛人真是n多,自己知道的太少太少太少。而在学校这个小小小圈子当中,很多人认为我很厉害,但我从一开始就不认为自己有多厉害,一切只因兴趣。昨天和一个真正非常厉害的同学聊了会,今天又去bj开会,他真是很厉害,参加sun校园大使,为期一年。之前也参加acm,不久前也参加“百度之星”,也去了好多地方。
  4. 而我自己真是什么都不懂。虽然我现在很讨厌说自己不懂。但是事实确实是我不懂。不懂学习,不懂生活,不懂处世,不懂做人。再一次,哎。。。好好练习编程,约好一起参加明年百度之星。
  5. 老了老了,一年之间真是变化超级大。师兄师姐们毕业了。自己从第一次进实验室时怯生生的小女生变成现在的敢和导师顶嘴,直接说出不满,直接争取机会,变得我行我素的一个家伙。有时感叹很多。这似乎不是真正的我。以前我憧憬未来,进知名IT企业或白手起家,成为一女强人,空闲时还搞点艺术,四处旅游。第三次,哎。。。现实,让我有点不知所措。
  6. 不知怎么搞的,一颗牙齿上突然掉了一小块牙齿骨头,这让我非常不习惯,一直去舔那个缺口,不知道是不是担心会掉,这样一下使我的舌头都添的麻木了。
  7. 终于看电影了,《人工智能》——让我觉得人类太恐怖。
  8. 昨晚下大雨,电闪雷鸣,睡的很晚,今天一天都一直困困的。充分体现生物钟的重要性。
  9. 这些天天气真是奇怪,下雨。打雷闪电。下雨天,尤其是有闪电,非常怕走在路上。担心自己倒霉被雷劈。真是这种感觉。一点都不好笑。

2008年6月19日 星期四

唯一

现在用了好多google的服务,越发觉得google帐号有多么重要,因为里面有太多属于我个人的东西。

之前刚试了下google日历简易版,使用了google calendar api,同时需要授予访问权(Grant Access),所以想到这个google密码太重要了,想着想着,觉得以前那密码太简单了,所以立刻去改密码。改完后,又更改安全设置,希望我的google帐号不会丢掉。还是那句,里面有太多的东西。

现在网络各种各样的东西一大堆,许多重复,许多共享,许多相似,许多许多东西,那么,有什么是唯一的呢?马上想到的是,邮箱、各种各样的帐号,这些是不能不唯一的了。想起自己在很多网站都申请了很多帐号,有些经常用,有些则注册完了早忘在脑后。到了几百年之后,会变成什么样呢,无法想象,或者说,不敢想象,网络唯一标识会如何做呢?

另外今天做了个google的favicon,几个idea,打了下手稿,但ps或illustrator之后,就变了样了,最终选了,哎。。。也没想到还有几小时就是deadline了。所以以后得把手稿保存起来扫描进去,或者自己写个图形软件专门符合自己风格。

好久没到这废话了,因为这两天主要是在弄GAE上的相关:域名(google apps,申请了,但还是不懂),另一个blog(基本差不多了),里面也学到很多东西,比如,正则式贪婪和非贪婪,自定义filter,pygments,Models中的等等了。调整页面显示太太太太太太麻烦了。

2008年6月13日 星期五

Pythonic

算起来,接触Python也有一段时间了。从2007年10月开始到现在,经常听到xxx是Pythonic,xxx太不Pythonic。同样刚才有听到了,猛的发现真不知道什么是Pythonic!惭愧~

google下,找到

主要思想是简单,易懂

其核心The Zen of Python,在Python shell中import this就可以看到如下:
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch. #为什么Dutch?
Now is better than never.
Although never is often better than *right* now.#绕!
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

其中文翻译

ok,知道Pythonic了,那么。。。

2008年6月12日 星期四

GAE errthing

整理下在GAE中编写web app时出现的错误:

  1. str vs unicode
    出现错误:UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)
    原因:混淆了 python2 里边的 str 和 unicode 数据类型。。。
    解决方法:
    * 对需要 str->unicode 的代码,可以在前边写上
    import sys
    reload(sys)
    sys.setdefaultencoding('utf8')
    把 str 编码由 ascii 改为 utf8 (或 gb18030)
    * 把文本(尤其是中文)进行编码,如unicode(keywords.strip(), 'utf-8'),db.Text(post_body, encoding="utf-8")
    ps: python3 区分了 unicode str 和 byte arrary,并且默认编码不再是ascii

    参考链接:http://groups.google.com/group/python-cn/browse_thread/thread/f48ef745452740f6
    http://mail.python.org/pipermail/python-list/2005-May/321512.html
  2. 利用appcfg.py上传web app时,出现错误:

    Error 400: --- begin server output ---
    Creating a composite index failed: An index may not be comprised of a single repeated property. Your query probably doesn't need this index. Try without it!

    解决方法:直接把index.yaml中自动产生的些models信息删除,就能上传正确。

  3. GAE提供的Model中property没有自动增1的选项,因此想自定义id,而不是利用key.id,似乎麻烦比较大。
  4. 修改models,会把原来已存记录因为BadValue Exception而无法显示,所以改models结构得想想清楚了
  5. GAE上不能新建文件,所以保存东西就不能不使用数据库。做如下测试:
    import os
    import pickle
    try:
    #pickle.dump(request, open('test.dump', 'w'))不能用w,即不支持创建新文件
    #if not os.system('date'): 不支持system和popen
    # return HttpResponse("os.system return not 0!")
    #md5sum = os.popen('md5sum '+__file__).readlines()[0].split(' ')[0]
    cwd = os.getcwd()
    return HttpResponse("cwd:%s" % (cwd))#md5:%s md5sum,
    except Exception, e:
    return HttpResponse("Test Error: %s" % e)

    结果cwd:/base/data/home/apps/lizziesky/1.46,咔咔,可以看到工程路径呢。

  6. request中知道当前访问的url,使用request.get_full_path(),这样就可以在跳转url时使用HttpResponseRedirect(users.create_login_url(request.get_full_path()))。另外,新版本django的request对象还有build_absolute_uri(location)和get_host()

  7. 数据库不支持多对多关系,那么Entry和Tag就不能直接保存关系。我把他们分开来,然后Entry加个tags = db.ListProperty(db.Category),这样相当于保存了两遍tag数据。现在只能做到这边了。
  8. 还有一个缺点是,非常重要之每次打开lizziesky.appspot.com非常。并在控制台下cpu使用率高,warning不断。
现在基本完成了,以后要做的:
  1. CSS调整真是比较麻烦,还有Ajax效果。由于没有firebug的帮助,实在受不了。所以期待赶快安装。
  2. 对于每个entry.body的输出格式,现在只是利用django中的filter只显示普通文本。以后将利用自定义tag,自己编写语法规则然后自己解析,就像moinmoin那种格式。
  3. GAE不支持django的feed,想能否自己写个rssfeed?

2008年6月6日 星期五

整理

今天终于把本体映射的论文写好了,实验做了一半。尝试做了,时间太紧,问题多多,以后得继续弄完,包括本体构建的,其实本体自动生成,未经人工参与的肯定很多不对。哎。。。
一般过程为:数据源(网页或现有数据集)->提取信息(关键、特征)->构建(利用现有工具或自个儿写)->最终分析。

接着想做的事:

  1. GAE上的lizziesky完善——95%
  2. ll的并行算法——6月08日完成
  3. LovelyPython...——95%
  4. 概念格的算法优化,好好写写,为以后论文中可能用到的实验打下基础。找个应用,一个博客上讲的信息系统的组织——标签。后GAE上的liz.appspot.com——20%
  5. 粗糙集,别忘了这里还有一篇论文要写——95%
  6. 玩Linux,Apache+MoinMoin,借的书还有很多——1%
  7. 自然辩证法,背书!——6月15日完成

2008年6月3日 星期二

Optimization for Conditional Random Fields

条件随机场及其优化
——陈一新

keywords:隐变量,观察变量,联合概率,条件概率
主要用于从一些列随机数中找到隐含的规律。预测。

1、HMM 隐马尔可夫模型,two assumption indepence,隐变量只和前一个隐变量有关,某个观察变量只和对应的隐变量有关。虽然HMM便于优化。。。但因为很多情况下不满足以上两个假设,所以有很大限制。
maxP(X,Y)

2、CRFs
随意的indepence,general model。。。
maxP(Y|X)
。。。。

3、forward-backward algorithm
伪牛顿函数,优化一个非线性函数。

报告感受:
两字——不懂,因为很多都是涉及到数学公式,数值优化,求收敛解等等。但主要是弥补了HMM的不足之处。也就是突破了HMM的两个限制,即可以是观察变量可以和多个隐变量有依赖关系,同样隐变量之间又有多种依赖,其中引入了一个叫feture的东西。

几点:
1、在例子掷骰子问题上,两个骰子0和1,0号骰子的6个数概率均为1/6,1号骰子的出现6的概率为1/2,其他数为1/10,那么0号骰子在掷完一次后90%的概率还是使用0号,10%的概率转入1号,同样,1号80%是转入自身,而20%的是转入1号,这个描述成一个状态图。只是每条边上加入了概率即权值。每个这样的状态图都有初态和终态等等了。是不是和自动机相似呢,只是状态转换的条件变成了概率值??
2、股票预测的例子,每天的股价相对于前一天来说要么升要么降,这样就可以看成是升降序列,要从这个很长很长很长的序列中找到隐含的规律。
3、基因预测,判断一条多条基因中的某段DNA序列是否是突变的,或者是有效的。。。
唉。。。

2008年6月1日 星期日

GAE oth

2、使用Django,将Django项目部署到GAE上


  • 将Django项目拷贝到GAE sdk工程目录下,工程名字和应用名字一样,即是同一层目录
  • 修改app.yaml
    application: lizziesky
    version: 1
    runtime: python
    api_version: 1

    handlers:
    - url: /site_media #和之前一样,注意要把静态文件加入就好
    static_dir: media

    - url: /.*
    script: main.py


  • 修改main.py
    import logging, os
    #import sys

    # Google App Engine imports.
    from google.appengine.ext.webapp import util

    # Remove the standard version of Django. # 这里如果使用自己的django,需要删除原来的,添加自己的django路径
    #for k in [k for k in sys.modules if k.startswith('django')]:
    # del sys.modules[k]

    # Force sys.path to have our own directory first, in case we want to import
    # from it.
    #sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))

    from django.conf import settings #这边未设置对,出现错误ROOT_URLCONF is not found.
    settings._target = None

    # Must set this env var *before* importing any part of Django
    os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

    import django.core.handlers.wsgi
    import django.core.signals
    import django.db
    import django.dispatch.dispatcher

    def log_exception(*args, **kwds):
    logging.exception('Exception in request:')

    # Log errors.
    django.dispatch.dispatcher.connect(
    log_exception, django.core.signals.got_request_exception)

    # Unregister the rollback event handler.
    django.dispatch.dispatcher.disconnect(
    django.db._rollback_on_exception,
    django.core.signals.got_request_exception)

    def main():
    # Create a Django application for WSGI.
    application = django.core.handlers.wsgi.WSGIHandler()

    # Run the WSGI CGI handler with that application.
    util.run_wsgi_app(application)
  • 修改settings.py
    # Django settings for lizziesky project.
    import os

    DEBUG = True
    TEMPLATE_DEBUG = DEBUG

    ADMINS = (
    # ('Your Name', 'your_email@domain.com'),
    )

    MANAGERS = ADMINS

    #DATABASE_ENGINE = 'appengine' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'ado_mssql'. #这里是不需要设置的
    #DATABASE_NAME = 'lizzieskydb' # Or path to database file if using sqlite3.
    #DATABASE_USER = '' # Not used with sqlite3.
    #DATABASE_PASSWORD = '' # Not used with sqlite3.
    #DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
    #DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.

    # Local time zone for this installation. Choices can be found here:
    # http://www.postgresql.org/docs/8.1/static/datetime-keywords.html#DATETIME-TIMEZONE-SET-TABLE
    # although not all variations may be possible on all operating systems.
    # If running in a Windows environment this must be set to the same as your
    # system time zone.
    TIME_ZONE = 'UTC'

    # Language code for this installation. All choices can be found here:
    # http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes
    # http://blogs.law.harvard.edu/tech/stories/storyReader$15
    LANGUAGE_CODE = 'en-us'

    SITE_ID = 1

    # If you set this to False, Django will make some optimizations so as not
    # to load the internationalization machinery.
    USE_I18N = True

    # Absolute path to the directory that holds media.
    # Example: "/home/media/media.lawrence.com/"
    MEDIA_ROOT = ''

    # URL that handles the media served from MEDIA_ROOT.
    # Example: "http://media.lawrence.com"
    MEDIA_URL = ''

    # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
    # trailing slash.
    # Examples: "http://foo.com/media/", "/media/".
    ADMIN_MEDIA_PREFIX = '/media/'

    # Make this unique, and don't share it with anybody.
    SECRET_KEY = 'o_@ehh+&p#-8fiil(_x6(5#6yuy%_j=sq14_zi8p*p0!+i(1'

    # List of callables that know how to import templates from various sources.
    TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.load_template_source',
    'django.template.loaders.app_directories.load_template_source',
    # 'django.template.loaders.eggs.load_template_source',
    )

    MIDDLEWARE_CLASSES = ( #去掉不支持的模块
    'django.middleware.common.CommonMiddleware',
    # 'django.contrib.sessions.middleware.SessionMiddleware',
    # 'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.middleware.doc.XViewMiddleware',
    )

    TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    # 'django.core.context_processors.media', # 0.97 only.
    # 'django.core.context_processors.request',
    )

    ROOT_URLCONF = 'urls' #这里不是工程名字.urls

    ROOT_PATH = os.path.dirname(__file__)
    TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(ROOT_PATH, 'templates') #模板路径
    )

    INSTALLED_APPS = (
    # 'django.contrib.auth', #不支持admin
    'django.contrib.contenttypes',
    # 'django.contrib.sessions',
    'django.contrib.sites',
    # 'django.contrib.admin',
    'myblog',
    )

    STATIC_PATH = os.path.join(ROOT_PATH, 'media')
  • 把所有的urls.py、views.py、models.py中的,涉及到不和谐的地方,全部改掉!超级多!主要是import路径(是不要工程名字的)、model的一些方法,还有就是template的页面上修改。
  • 在本地OK后,上传后,还是很多问题。
  • Settings中ROOT_URLCONF
  • 不需要工程名字,直接urls
  • 中文问题
  • DATABASE_ENGINE不需要
  • 同时也发现GAE提供的admin非常好,调试错误还有自定义信息都能显示
  • feed不能用,是因为django该部分用到数据库的模块了......20081105 feed实现
  • 总能找到替代方法,对于很多问题。
  • 本地SDK和实际的google环境不一样!
  • 还有so many的问题。所以看来有这么长改的时间,还不如直接从零开始。
  • 现在基本功能已经实现,接下来,重新开始!

GAE sth

今天学了下GAE的使用,总结如下:

1、HelloWorld——自带webapp

  • app.yaml
    application: lizziesky
    version: 1
    runtime: python
    api_version: 1

    handlers: #处理路径问题,对应路径用哪个pr脚本来处理,先精确到模糊,
    - url: /site_media #还有就是静态文件。url是符合正则式语法
    static_dir: site_media

    - url: /blog/.*
    script: blog.py

    - url: /django/.*
    script: test.py

    - url: /.*
    script: index.py

  • py脚本helloworld.py
    #coding:utf-8 #脚本文件编码
    import cgi
    import wsgiref.handlers
    #导入webapp
    from google.appengine.ext import webapp
    #google用户api;UsersAPI,是google帐户
    from google.appengine.api import users
    # 数据库api
    from google.appengine.ext import db
    import os
    # 支持模板,也支持模板中的嵌套,过滤器似乎不行。找不到路径?
    from google.appengine.ext.webapp import template

    #记录日志api,主要是工程提交后有个控制台,这边的logging若记录后可以显示在这个控制台中
    import logging

    class MainPage(webapp.RequestHandler):
    def get1(self):
    """
    """
    #获得当前用户,没有的话则为None
    user = users.get_current_user()

    if user:
    self.response.headers['Content-Type'] = 'text/plain'
    self.response.out.write('Hello, ' + user.nickname() + 'World!')
    self.response.out.write(self.request.uri)
    else:
    #跳转到用户登录界面;
    self.redirect(users.create_login_url(self.request.uri))

    def get2(self):
    self.response.out.write('')
    #Gql查询,很类似其他的
    greetings = db.GqlQuery('SELECT * FROM Greeting ORDER BY date DESC LIMIT 10')

    # if users.get_current_user():
    # greetings = Greeting.gql("WHERE author = :1 ORDER BY date DESC", users.get_current_user())
    # greetings = Greeting.gql("WHERE author = :author ORDER BY date DESC", author=users.get_current_user())
    # greetings = Greeting.all()
    # greetings.filter("author =", users.get_current_user())
    # greetings.order("-date")
    #在本地清空数据库命令 dev_appserver.py --clear_datastore helloworld/

    for greeting in greetings:
    if greeting.author:
    self.response.out.write('《b》%s《/b》 wrote:' % greeting.author.nickname())
    else:
    self.response.out.write('An anonymous person wrote.')
    self.response.out.write('《blockquote》%s《/blockquote》' % cgi.escape(greeting.content))

    self.response.out.write("""
    《form action="/sign" method="post"》
    《div》《textarea name="content" rows="3" cols="60"》《/textarea》《/div》
    《div》《input value="Sign Guestbook" type="submit"》《/div》
    《/form》
    """)

    def get(self):
    greetings_query = Greeting.all().order('-date')
    greetings = greetings_query.fetch(10)

    if users.get_current_user():
    url = users.create_logout_url(self.request.uri)
    url_linktext = "Logout"
    else:
    url = users.create_login_url(self.request.uri)
    url_linktext = "Login"

    template_values = {
    'greetings':greetings,
    'url':url,
    'url_linktext':url_linktext,
    }
    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))

    #Model,数据库表,只能用定义好的Progerty
    class Greeting(db.Model):
    author = db.UserProperty()
    content = db.StringProperty(multiline=True)
    date = db.DateTimeProperty(auto_now_add=True)

    class GuestBook(webapp.RequestHandler):
    def post(self):
    # post,get方法
    greeting = Greeting()
    if users.get_current_user():
    greeting.author = users.get_current_user()
    greeting.content = self.request.get('content')
    greeting.put()
    logging.debug("add a item")
    self.redirect('/')

    def main():
    #这里又有url匹配,app.yaml中的进一步。
    application = webapp.WSGIApplication(
    [('/', MainPage),
    ('/sign', GuestBook)],
    debug=True)
    wsgiref.handlers.CGIHandler().run(application)

    if __name__ == "__main__":
    main()

  • 数据库 models.py

    #coding:utf-8
    # 数据库api
    from google.appengine.ext import db

    #和Django的Model类似,但功能缩减了很多。不支持很多,如自定义方法,无__str__、
    #get_absolute_url、无meta、admin等等,
    #对于外键使用ReferenceProperty,无1对多或多对多关系。
    # 使用ReferenceProperty后,非常奇怪倒是能用类似Django中的entry.comment_set的这种东西。
    #真不知道她是怎么弄的~
    #1对多替代方法:GAE提供StringList和其他,这个可以作为1对多,List中储存另一表中记录的id或key
    #多对多替代方法:有个CategoryProperty不知道可否利用,但是非常奇怪的这个
    #CategoryProperty只能支持特定的类型。
    class Tag(db.Model):
    slug=db.StringProperty()
    title=db.TextProperty()

    class Entry(db.Model):
    title=db.TextProperty() #这样子不支持中文,因为默认是ascii码,需要这样做
    body=db.TextProperty() #unicode(comment_author, encoding="utf-8") or
    pub_date=db.DateTimeProperty(auto_now_add=True) #db.Text(post_body, encoding="utf-8")
    #?能否直接申明时指定encoding
    tags = db.ReferenceProperty(Tag)

    class Comment(db.Model):
    post = db.ReferenceProperty(Entry)

    author = db.TextProperty()
    email = db.EmailProperty()
    website = db.LinkProperty()

    body = db.TextProperty()
    date = db.DateTimeProperty(auto_now_add=True)
    order = db.IntegerProperty()

  • index.yaml

    indexes:
    # AUTOGENERATED

    # This index.yaml is automatically updated whenever the dev_appserver 默认是自动更新的,
    # detects that a new type of query is run. If you want to manage the 可以不用考虑;
    # index.yaml file manually, remove the above marker line (the line 记录一些index。
    # saying "# AUTOGENERATED"). If you want to manage some indexes
    # manually, move them above the marker line. The index.yaml file is
    # automatically uploaded to the admin console when you next deploy
    # your application using appcfg.py.

    # Used 4 times in query history.
    - kind: Entry
    properties:
    - name: pub_date
    direction: desc

I just don't feel like doing this today, but I will do it anyway!