もあるけれども、 range を使うのがわかりやすいか。
| [2007] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] |
| [2007] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] |
from google.appengine.api import urlfetch
from elementtree.ElementTree import *
import re
rss1 = 'http://movies.go.com/xml/rss/intheaters.xml'
url = rss1
rss = urlfetch.Fetch(url)
print rss
tree = ElementTree(fromstring(rss.content))
img_re = re.compile('<img src="([a-zA-Z0-9/:._\-]+)" ')
for item in tree.findall('.//item'):
title = item.find('title').text.strip()
description = item.find('description').text.strip()
imageMatch = img_re.search(description)
if (imageMatch):
picture_url = imageMatch.groups()[0]
print title
print picture_url
---
Speed Racer
http://movies.go.com/i/movies/895881/895881.jpg
from google.appengine.api import urlfetch
from elementtree.ElementTree import *
import re
url = 'http://webdba.blogspot.com/2008/05/urlfetch-rss-img.html'
content = urlfetch.Fetch(url).content
img_re = re.compile('<img src="([a-zA-Z0-9/:._\-]+)" ',re.I)
img_re = re.compile('src="([a-zA-Z0-9/:._\-]+).jpg" ',re.I)
img_re = re.compile('src="([a-zA-Z0-9/:._\-]+[jpg|gif|png])" ',re.I)
imageMatch = img_re.search(content)
imageMatch = img_re.findall(content)
print imageMatch
for i in imageMatch:
print i
---
['http://code.google.com/appengine/images/appengine_lowres.jpg']
http://code.google.com/appengine/images/appengine_lowres.jpg
--------------------------------------
import string
str1 = "http://localhost"
str2 = string.replace(str1, 'http', 'file')
print str1
print str2
---
http://localhost
file://localhost
'\\\\'
p = re.compile(r'([^"])\b((http|https)://[^ \t\n\r<>\(\)&"]+' \
r'[^ \t\n\r<>\(\)&"\.])')
-------------------------------------------------------------
import re
p = re.compile("ab.", re.I)
result = p.findall("AbdABCAAbb")
print result
p = re.compile("ab.")
print p.sub("xxx", "abcdeaabcde")
print p.sub("xxx", "Abcdeaabcde")
p = re.compile("ab.", re.I)
print p.sub("xxx", "Abcdeaabcde")
print "------------"
url = "aa https://aa.com/ bb"
p = re.compile(r'([^"])\b((http|https)://[^ \t\n\r<>\(\)&"]+' \
r'[^ \t\n\r<>\(\)&"\.])')
m = p.match('aa http://aa.com/ bb' + url + url )
print m
m = p.sub('XXX','aa http://aa.com/ bb' + url + url )
print m
print "------------"
# print m.group(0)
print "-- " + url + " --"
print "->"
print p.sub("xxx", url )
p = re.compile('[a-z]+')
m = p.match('tempo')
print m
print m.group(0)
-----
from google.appengine.api import urlfetch
from elementtree.ElementTree import *
import re
url = 'http://blog.goo.ne.jp/xxxxxx/m/200803'
#content = urlfetch.Fetch(url).content.decode("euc-jp")
content = url.split('/')
print content[0]
print content[1]
print content[2]
print content[3]
content = url.split('/')[2]
print content
import os
from google.appengine.api import datastore
from google.appengine.api import datastore_types
name = 'test'
entity = datastore.Entity('Page')
entity['name'] = name
query = datastore.Query('Page')
query['name ='] = name
entities = query.Get(1)
print >> sys.stdout, len(entities)
print >> sys.stdout, entities[0]
print >> sys.stdout, entities[0]['user']
print >> sys.stdout, entities[0].key()
print >> sys.stdout, entities[0].key().id()
------
1
{u'content': u'<h1>test</h1>', u'user': users.User(email='test@example.com'), u'modified': datetime.datetime(2008, 5, 9, 14, 41, 30, 62000), u'name': u'test', u'created': datetime.datetime(2008, 5, 9, 14, 41, 30, 62000)}
test@example.com
agpoZWxsb3dvcmxkcgsLEgRQYWdlGJQBDA
148
import sys #import sys module for printing to stdout
from google.appengine.ext import db
class Car(db.Model):
brand = db.StringProperty(required=True)
wheels = db.ListProperty(db.Key)
mercedes = Car(brand="Mercedes", key_name ="b")
# mercedes.put()
print >> sys.stdout, mercedes.brand
select = mercedes.get_by_id( 130 )
print >> sys.stdout, select.brand
select = mercedes.get_by_key_name( "b" )
print >> sys.stdout, select.brand
id = 130
select = Car.get(db.Key.from_path('Car', id))
print >> sys.stdout, select.brand
key_name = "b"
select = Car.get(db.Key.from_path('Car', key_name))
print >> sys.stdout, select.brand
print >> sys.stdout, select.key()
print >> sys.stdout, select.key().id()
print >> sys.stdout, select.key().name()
Tip: Key names and IDs cannot be used like property values in queries. However, you can use a named key, then store the name as a property. You could do something similar with numeric IDs by storing the object to assign the ID, getting the ID value using obj.key().id(), setting the property with the ID, then storing the object again.
OK
greetings = db.GqlQuery("SELECT * FROM Greeting where content >= :1 and content < :2 ",
search_key, search_key + u"\uFFFD" )
NG
# greetings = db.GqlQuery("SELECT * FROM Greeting where content >= :1 and content < :2 ", # search_key, urllib.unquote(search_key).decode("utf8") + u"\uFFFD" )
Tip: Query filters do not have an explicit way to match just part of a string value, but you can fake a prefix match using inequality filters:db.GqlQuery("SELECT * FROM MyModel WHERE prop >= :1 AND prop < :2", "abc", "abc" + "\xEF\xBF\xBD")
Next problem is that I can't search the datastore with a parameter
from the query string, something like this:
import urllib
q = "Ambj%C3%B6" # Url encoded u"Ambjö"
fsgs = db.GqlQuery("SELECT * FROM Fsg WHERE fsg >= :1 AND fsg < :2", urllib.unquote(q), urllib.unquote(q) + u'\uFFFD')
Works perfect if I only have ascii characters. Is urllib.unquote wrong#!-*- coding:utf-8 -*-
# import the webapp module
from google.appengine.ext import webapp
import datetime
# get registry, we need it to register our filter later.
register = webapp.template.create_template_register()
def truncate(value,maxsize,stopper = '...'):
""" truncates a string to a given maximum
size and appends the stopper if needed """
stoplen = len(stopper)
if len(value) > maxsize and maxsize > stoplen:
return value[:(maxsize-stoplen)] + stopper
else:
return value[:maxsize]
def timeJST (value):
# return value - datetime.timedelta(hours=18)
return value + datetime.timedelta(hours=9)
# SDK102 にしたら動作がかわった???
register.filter(truncate)
register.filter(timeJST)
-- index.html
{{ greeting.date|timeJST|date:"Y/m/d H:i:s" }}
-- helloworld.py
webapp.template.register_template_library( 'templatefilters')
参照元
│ app.yaml
│ flickr.html
│ flickr.py
│ index.yaml
│ webSimple.py
│ webSimple.pyc
│
└─elementtree
ElementInclude.py
ElementPath.py
ElementPath.pyc
ElementTree.py
ElementTree.pyc
HTMLTreeBuilder.py
SgmlopXMLTreeBuilder.py
SimpleXMLTreeBuilder.py
SimpleXMLTreeBuilder.pyc
SimpleXMLWriter.py
TidyHTMLTreeBuilder.py
TidyTools.py
XMLTreeBuilder.py
__init__.py
__init__.pyc
--
SDK102 にしたところ、下記のエラーで動作しなくなる
'photos' : res.parse_xml().find("photos").getchildren(),
AttributeError: 'NoneType' object has no attribute 'getchildren'
# from xml.etree import ElementTree
from xml.etree import ElementTree, SimpleXMLTreeBuilder
ElementTree.XMLTreeBuilder = SimpleXMLTreeBuilder.TreeBuilder
except ImportError:
# from elementtree import ElementTree
from xml.etree import ElementTre
起動
C:\google>dev_appserver.py muvmuv/
これはOK
実行
http://localhost:8080/build
しかし、これが NG
http://groups.google.com/group/google-appengine/browse_thread/thread/634e7b9a2e584dd3?hl=en
How to use simplejson with GqlQuary object for example how to convert
marker_list to JSON for format
marker_list = db.GqlQuery('SELECT * FROM Marker')
def dumprow(r):
import datetime
a = {}
for k in r.fields().keys():
v = getattr(r, k)
a['id'] = r.key().id()
a['key'] = str(r.key())
if isinstance(v, str):
a[k] = str(v)
elif isinstance(v, unicode):
a[k] = unicode(v)
elif isinstance(v, datetime.datetime):
a[k] = v.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(v, datetime.date):
a[k] = v.strftime('%Y-%m-%d')
elif isinstance(v, datetime.time):
a[k] = v.strftime('%H:%M:%S')
elif isinstance(v, (int, float, list)):
a[k] = v
else:
a[k] = str(v)
return a
def dumpquery(query):
s = []
for r in query:
s.append(dumprow(r))
return s
When the application creates an entity, it can assign another entity as the parent of the new entity. Assigning a parent to a new entity puts the new entity in the same entity group as the parent entity.
An entity without a parent is a root entity. An entity that is a parent for another entity can also have a parent. A chain of parent entities from an entity up to the root is the path for the entity, and members of the path are the entity's ancestors. The parent of an entity is defined when the entity is created, and cannot be changed later.
・データモデルについてはgoogle-appengine groupでも議論が行われている 1:1,1:n
Small tutorial on ER-modeling with GAE - 6 new
http://groups.google.com/group
I wrote a small tutorial about ER-modeling with Google App Engine:
http://daily.profeth.de/2008/04/er-modeling-with-google-app-engine.html
Docs > Datastore API > GqlQuery を参考
* bind()
* get()
* fetch()
* count()
greetings = Greeting.all().order('-date')で件数をカウントすることができました。
row_cnt = greetings.count()
greetings = Greeting.all().order('-date')これは素直に動作しました。
greetings.filter('content =', 'Foo') # 追加
key = greeting.key()なるほど、key がわかれば、 get(key) でたどって実際の値もわかるということです。
self.response.out.write('%s' % str(key) )
self.response.out.write('%s' % greeting.get(key) )
↓ このような値が返ってきていました。
agpoZWxsb3dvcmxkcg4LEghHcmVldGluZxgTDA
<__main__.Greeting object at 0x02600B30>
INFO 2008-04-16 16:24:10,546 dev_appserver.py] "GET / HTTP/1.1" 500 -発生するようになったタイミングはこの部分の追加以降
Traceback (most recent call last):
File "C:\Python25\lib\wsgiref\handlers.py", line 92, in run
self.result = application(self.environ, self.start_response)
File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__i
nit__.py", line 504, in __call__
response.wsgi_write(start_response)
File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__i
nit__.py", line 223, in wsgi_write
body = self.out.getvalue()
File "C:\Python25\lib\StringIO.py", line 270, in getvalue
self.buf += ''.join(self.buflist)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 13: ordinal
not in range(128)
greetings = db.GqlQuery("SELECT * FROM Greeting ORDER BY date DESC LIMIT 10")困ったものです
for greeting in greetings:
if greeting.author:
self.response.out.write('wrote:' )
self.response.out.write('%s wrote:' % greeting.author.nickname())
else:
self.response.out.write('An anonymous person wrote:')
self.response.out.write('%s' %
cgi.escape(greeting.content))
self.response.headers['Content-Type'] = 'text/html'では効果なし。
self.response.headers['charset'] = 'UTF-8'
C:\google\helloworld>set TZ=
C:\google\helloworld>python
Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)]
>>> import datetime
>>> print datetime.datetime.now()
2008-04-14 13:17:36.953000
>>>
C:\google\helloworld>set TZ=JST
C:\google\helloworld>python
Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)]
>>> import datetime
>>> print datetime.datetime.now()
2008-04-14 04:21:32.015000
>>>
Ctl+Z で終了-- test scrit tt.py
import datetime
class JST(datetime.tzinfo):
def utcoffset(self, dt):
return datetime.timedelta(hours=9)
def dst(self, dt):
return datetime.timedelta(0)
def tzname(self, dt):
return "JST"
print datetime.datetime.now().isoformat()
print datetime.datetime.now(JST()).isoformat()
実行結果C:\google\helloworld>python tt.py
2008-04-14T04:28:33.468000
2008-04-14T13:28:33.468000+09:00
for greeting in greetings:
・・・
d = greeting.date + datetime.timedelta(hours=9)
self.response.out.write('%s
' % d.strftime("%Y/%m/%d %H:%M:%S") )
として対応することにしました。class Pet(db.Model):のように Entiy を定義し、値をセットして
name = db.StringProperty(required=True)
pet = Pet(name="Fluffy",
pet.Put()のようにデータベース( datastore ) に保存する。
{{ greeting.datedate:"Y/m/d H:m:s" }}を追加して、時間を表示するようにしたところ自動的に登録される時間がJST(日本標準時)でなくUTCとなっているのをなんとかしたい。
author = db.UserProperty()テンプレートで対応できれば、ベストなのですが
content = db.StringProperty(multiline=True)
date = db.DateTimeProperty(auto_now_add=True)
{{gdateadd:"-2"}}このような感じでテンプレート側で対応できますが・・・ 日付の場合、どうするかは次回の検討事項とします。
C:\google>dev_appserver.py --clear_datastore helloworld/6. Using Templates
INFO 2008-04-11 16:43:28,375 appcfg.py] Checking for updates to the SDK.
INFO 2008-04-11 16:43:28,780 appcfg.py] The SDK is up to date.
INFO 2008-04-11 16:43:28,780 dev_appserver.py] Attempting to remove file at
c:\docume~1\user\locals~1\temp\dev_appserver.datastore
windows 環境では bug 対応が必要上記も含めいろいろやったが
app.yaml と \google\appengine\tools\dev_appserver.py を修正する。
see -> http://d.hatena.ne.jp/Aoba/20080410/1207842114
link type="text/css" rel="stylesheet" href="c:/google/helloworld/stylesheets/main.css"- index.html 内に当面、記述
のように絶対パスで書くとエラーは止まるが、cssは適用されていない様子。
dev_appserver.py は修正した状態。
結局、このファイルは元に戻して、 css ファイルは分けるのをやめた。
<head>
<style type="text/css">
body {
font-family: Verdana, Helvetica, sans-serif;
background-color: #DDDDDD;
}
</style>
</head>
- url: /css/(.*\.css)
static_files: css/\1
upload: css/(.*\.css)
Python 2.5.2: C:\Python25\python.exeFri Apr 11 13:01:06 2008・ main.css ファイルの文字コードが sjis になっていた時のエラー
A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred.
C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.p in _HandleRequest(self=)
2243 infile,
2244 outfile,
2245 base_env_dict=env_dict)
2246 finally:
2247 self.module_manager.UpdateModuleFileModificationTimes()
base_env_dict undefined, env_dict = {'REMOTE_ADDR': '127.0.0.1', 'REQUEST_METHOD': 'GET', 'SERVER_NAME': 'localhost', 'SERVER_PORT': '8080', 'SERVER_PROTOCOL': 'HTTP/1.0', 'SERVER_SOFTWARE': 'Development/1.0'}
・
ERROR 2008-04-11 14:59:53,453 __init__.py] Traceback (most recent call last):----------------------------------------------------
File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 486, in __call__ handler.post(*groups) File "C:\Documents and Settings\kt\My Documents\google\helloworld\helloworld.py", line 39, in post greeting.put() File "C:\Program Files\Google\google_appengine\google\appengine\ext\db\__init__.py", line 602, in put self._save_to_entity() File "C:\Program Files\Google\google_appengine\google\appengine\ext\db\__init__.py", line 621, in _save_to_entity self._store_to_entity(self._entity) File "C:\Program Files\Google\google_appengine\google\appengine\ext\db\__init__.py", line 587, in _store_to_entity entity[prop.name] = datastore_value File "C:\Program Files\Google\google_appengine\google\appengine\api\datastore.py", line 341, in __setitem__ datastore_types.ToPropertyPb(name, value) File "C:\Program Files\Google\google_appengine\google\appengine\api\datastore_types.py", line 976, in ToPropertyPb pbvalue.mutable_uservalue().set_email(v.email().encode('utf-8'))UnicodeDecodeError: 'ascii' codec can't decode byte 0x82 in position 3: ordinalnot in range(128)
-helloworld.py- #!-*- coding:utf-8 -*- |
6. ブラウザデアクセスしてみる
7. DOS prompt の出力の様子
C:\Documents and Settings\user\My Documents\google>dev_appserver.py helloworld/
Allow dev_appserver to check for updates on startup? (Y/n): y
dev_appserver will check for updates on startup. To change this setting, edit C:\Documents and Settings\user/.appcfg_nag
INFO 2008-04-11 11:28:02,328 appcfg.py] Checking for updates to the SDK.
INFO 2008-04-11 11:28:02,733 appcfg.py] The SDK is up to date.
WARNING 2008-04-11 11:28:02,733 datastore_file_stub.py] Could not read datastore data from c:\docume~1\user\locals~1\temp\dev_appserver.datastore
WARNING 2008-04-11 11:28:02,733 datastore_file_stub.py] Could not read datastore data from c:\docume~1\user\locals~1\temp\dev_appserver.datastore.history
INFO 2008-04-11 11:28:02,750 dev_appserver_main.py] Running application helloworld on port 8080: http://localhost:8080
INFO 2008-04-11 11:31:28,092 dev_appserver.py] "GET / HTTP/1.1" 200 -
INFO 2008-04-11 11:31:28,108 dev_appserver_index.py] Updating C:\Documents and Settings\user\My Documents\google\helloworld\index.yaml
INFO 2008-04-11 11:31:28,171 dev_appserver.py] "GET /favicon.ico HTTP/1.1" 200 -
INFO 2008-04-11 11:31:41,296 dev_appserver.py] "GET / HTTP/1.1" 200 -
INFO 2008-04-11 11:31:42,217 dev_appserver.py] "GET / HTTP/1.1" 200 -
INFO 2008-04-11 11:31:45,296 dev_appserver.py] "GET / HTTP/1.1" 200 -
http://code.google.com/appengine/
Announcing Google App Engine at Campfire One on April 7, 2008
Mac Mini M2 の Unity で Sketchup のデータを復元したつづき。 以前、苦労して作成したドアの開閉が動作しないので修復する。 どうやって動かしていたのか、また忘れそうなので記録しておく。 Animator 左右のドア PlaneL,...