我剛剛開始使用Google App Engine。目前,我的應用程序有兩個頁面:一個列出當前庫存的所有庫存,另一個列出給定項目的詳細信息頁面。我覺得我的編碼可能更幹。 (例如,我打電話打印頁眉和頁腳兩次)。Google App Engine:我如何幹這個基本的請求處理?
這是代碼。我如何分析重複?
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp.util import run_wsgi_app
import os
from google.appengine.ext.webapp import template
def render(filename, main, template_values):
path = os.path.join(os.path.dirname(__file__), filename)
main.response.out.write(template.render(path, template_values))
class Item(db.Model):
CSIN = db.IntegerProperty()
name = db.StringProperty()
price = db.IntegerProperty() # OK that it's ints?
quantity = db.IntegerProperty()
class MainPage(webapp.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/html'
render('Views/header.html', self, {'title' : 'Store'})
self.response.out.write('<h1>This is going to be the best Store app EVER!</h1>')
items = Item.all().order('name').fetch(10)
render('Views/table.html', self, {'items': items})
render('Views/footer.html', self, {})
class Detail(webapp.RequestHandler):
def get(self, CSIN):
self.response.headers['Content-Type'] = 'text/html'
render('Views/header.html', self, {'title' : 'Store'})
self.response.out.write('<h1>DETAILS %s</h1>' % CSIN)
# SQL injection risk here, or is that taken care of by the pattern?
item = db.GqlQuery("SELECT * FROM Item WHERE CSIN = :1", int(CSIN)).get()
if (item):
render('Views/item_detail.html', self, {'item': item})
else:
render('Views/item_not_found.html', self, {'CSIN': CSIN})
render('Views/footer.html', self, {})
application = webapp.WSGIApplication([('/detail/(\d+)', Detail),
('/.*', MainPage)], debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
謝謝您的意見!
方法調用中'*'的含義是什麼? – 2010-03-03 03:21:22
@Rosarch:'foo(* args)'是一種將任意數量的參數傳遞給函數的方法。見http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/ – unutbu 2010-03-03 03:45:19