顯示具有 google app engine 標籤的文章。 顯示所有文章
顯示具有 google app engine 標籤的文章。 顯示所有文章

2008年9月4日 星期四

URL mapping in app engine

defined in app.yaml

app.yaml defines which handler script will  handle the request(URL)

2008年8月29日 星期五

using django with app engine

1. create django project
   django-admin.py startproject Test

2. add main.py in project:
# Google App Engine imports.
from google.appengine.ext.webapp import util

from django.core.management import setup_environ
import settings

setup_environ(settings)

# Force Django to reload its settings.
from django.conf import settings
settings._target = None

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


# 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)

if __name__ == '__main__':
  main()

3. add app.yaml in project
application: test
version: 1
runtime: python
api_version: 1

handlers:
- url: /.*
  script: main.py

4. dev_appserver.py  Test

2008年8月28日 星期四

webpage about django & app engine

http://www.42topics.com/dumps/django/docs.html

create application on app engine

1. create an application from http://appengine.google.com/
    application identifier must be the same as application in app.yaml

2. upload application
    appcfg.py  update helloworld

3. by default,
    the application url is  http://helloworld.appspot.com/

using static files

using css:
add  following lines in yaml
- url: /stylesheets
  static_dir: stylesheets

add a directory stylesheets under project directory 
css files are in this directory

add following lines in html
<head>
   <link type="text/css" rel="stylesheet" href="/stylesheets/main.css" />
 </head>

2008年8月26日 星期二

template in webapp

helloworld.py
import cgi

from google.appengine.ext import db

import os
from google.appengine.ext.webapp import template

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users

class Greeting(db.Model):
  author = db.UserProperty()
  content = db.StringProperty(multiline=True)
  date = db.DateTimeProperty(auto_now_add=True)

class MainPage(webapp.RequestHandler):
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))
class Guestbook(webapp.RequestHandler):
def post(self):
greeting = Greeting()
if users.get_current_user():
greeting.author = users.get_current_user()
greeting.content = self.request.get('content')
greeting.put()
self.redirect('/')
application = webapp.WSGIApplication( [('/', MainPage), ('/sign', Guestbook)], debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()

index.html:
<html>
  <body>
    {% for greeting in greetings %}
      {% if greeting.author %}
        <b>{{ greeting.author.nickname }}</b> wrote:
      {% else %}
       An anonymous person wrote:
      {% endif %}
      <blockquote>{{ greeting.content|escape }}</blockquote>
    {% endfor %}

    <form action="/sign" method="post">
 <div><textarea name="content" rows="3" cols="60"></textarea></div>
      <div><input type="submit" value="Sign Guestbook"></div>
    </form>

    <a href="{{ url }}">{{ url_linktext }}</a>

  </body>
</html>     

datastore api

define a model & create an entity

example :

# import db & users
from google.appengine.ext import db
from google.appengine.api import users

# define a model, inherit from db.Model
class Pet(db.Model):
  name = db.StringProperty(required=True)
  type = db.StringProperty(required=True, choices=set(["cat", "dog", "bird"]))
  birthdate = db.DateProperty()
  weight_in_pounds = db.IntegerProperty()
  spayed_or_neutered = db.BooleanProperty()
  owner = db.UserProperty()

# create an entity 
pet = Pet(name="Fluffy",
          type="cat",
          owner=users.get_current_user())
pet.weight_in_pounds = 24

# store the entity
pet.put()

_____________________________________________________________

get entity from datastore
1. using db.GqlQuery
ex:
user_pets = db.GqlQuery("SELECT * FROM Pet WHERE pet.owner = :1",
                          users.get_current_user())


db's property:
1. db.StringProperty
2.db.DateProperty



import cgi

from google.appengine.ext import db

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users

class Greeting(db.Model):
  author = db.UserProperty()
  content = db.StringProperty(multiline=True)
  date = db.DateTimeProperty(auto_now_add=True)

class MainPage(webapp.RequestHandler):
def get(self):
self.response.out.write('<html><body>')
greetings = db.GqlQuery("SELECT * FROM Greeting ORDER BY date DESC LIMIT 10")
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))

   # Write the submission form and the footer of the page
self.response.out.write("""
          <form action="/sign" method="post">
            <div><textarea name="content" rows="3" cols="60"></textarea></div>
            <div><input type="submit" value="Sign Guestbook"></div>
          </form> </body></html>
       
     """)
class Guestbook(webapp.RequestHandler):
def post(self):
greeting = Greeting()
if users.get_current_user():
greeting.author = users.get_current_user()
greeting.content = self.request.get('content')
greeting.put()
self.redirect('/')
application = webapp.WSGIApplication( [('/', MainPage), ('/sign', Guestbook)], debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
     main()

get data from datastore:
method 1:
db.GqlQuery("SELECT * FROM Greeting ORDER BY date DESC LIMIT 10")  

method 2:
Greeting.gql("ORDER BY date DESC LIMIT 10")

method 3:
Greeting.gql("WHERE author = :1 ORDER BY date DESC",
                               users.get_current_user())

method 4:
Greeting.gql("WHERE author = :author ORDER BY date DESC",
                               author=users.get_current_user())

method 5:
greetings = Greeting.all()
greetings.filter("author =", users.get_current_user())
greetings.order("-date")

Clearing the Development Server Datastore
ex:
dev_appserver.py --clear_datastore helloworld/

form in webapp

import cgi

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users

class MainPage(webapp.RequestHandler):
def get(self):
self.response.out.write("""
      <html>
        <body>
          <form action="/sign" method="post">
            <div><textarea name="content" rows="3" cols="60"></textarea></div>
<input type="submit" value="Sign Guestbook"></div>
          </form>
        </body>
      </html>""")
class Guestbook(webapp.RequestHandler):
def post(self):
self.response.out.write('<html><body>You wrote:<pre>')
self.response.out.write(cgi.escape(self.request.get('content')))
self.response.out.write('</pre></body></html>')
application = webapp.WSGIApplication( [('/', MainPage), ('/sign', Guestbook)], debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()

users service

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users

class MainPage(webapp.RequestHandler):
def get(self):
user = users.get_current_user()

if user:
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write('Hello, ' + user.nickname())
else:
self.redirect(users.create_login_url(self.request.uri))
application = webapp.WSGIApplication( [('/', MainPage)], debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()

self.request.uri is current uri. Hence, after successful login, user can back here

webapp framework

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class MainPage(webapp.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write('Hello, webapp World!')
application = webapp.WSGIApplication( [('/', MainPage)], debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()

a hello world page

1. create project directory:
helloworld

2. in the directory, create two files

(1)helloworld.py:
print 'Content-Type: text/plain'
print ''
print 'Hello, world!'

(2)app.yaml
application: helloworld
version: 1
runtime: python
api_version: 1

handlers:
- url: /.*
script: helloworld.py

url: /.*
script: helloworld.py means any url will be handled by helloworld.py

(3)run web server:
dev_appserver.py helloworld

(4) connect to server
127.0.0.1:8080

(5) update to google web server:
appcfg.py helloworld