Run taobao API using GAE

为了学习GAE(google app engine), 我写了一个小例子.因为GAE使用了django,沿用了其网络框架中基本
概念MTV(Model-Template-view). 在例子中,我用的model数据来自taobao API, 可以参考上篇文章:
Try taobao open API in python

在上篇文章中,调用taobao API拿到了一些测试数据, 可以把这些数据保存在GAE的数据库中,然后在View上
显示出来.
把上个taobao的代码做了写修改,把返回的测试数据封装成一个list,每个list的元素就是一个
taobaoke product.

现在为数据建模: 通过定义将 Model 作为子类的类,应用程序可以定义数据模型。使用 Model
属性和 Property 类实例,可以定义 Model 的属性. 一个taobao product的key有tile,nick等.

class TaobaoProduct(db.Model):
    title = db.StringProperty()
    nick = db.StringProperty()
    pic_url = db.LinkProperty()
    price = db.StringProperty()
    click_url = db.StringProperty()

model建立好之后,接着准备view. 这里面就要用到GAE的webapp. 这个框架是一个简单的网络应用程序
框架,可用来开发适用于 App Engine 的 Python 网络应用程序。webapp 可兼容
Python 网络应
用程序容器的 WSGI 标准。webapp 提供了一种简单的方式来开始开发适用于 App Engine 的应用程序。

application = webapp.WSGIApplication([('/', MainPage),
                                      ('.*',Error404)],
                                      debug=True)

wsgiref.handlers.CGIHandler().run(application)

上述代码把 网址路径映射到 RequestHandler 类的与 WSGI 兼容的应用程序.就是说当访问
http://localhost:8080/ 时候, 相对应的RequestHandler类的get方法就会返回. 这里的MainPage
和Error404就是基于webapp.RequestHandler的字类, 调用self.response.out.write向CGI写HTML数据.

my_product_list数据来源于taobao.py. 拿到一个元素为hash的list. 这时候我们把这些数据存在
GAE的database中(通过model.put). 数据库建立好之后, 就需要通过template和View把数据表示
成HTML格式,这个过程template.render函数可以帮你完成.

class MainPage(webapp.RequestHandler):

    def get(self):

        self.response.out.write("<html><body>")
        #self.response.headers['Content-Type'] = ‘text/plain’
        self.response.out.write("<p>List all Taobao Products</p>")

        # get taobao product from OpenAPI
        # See taobao.py for more details
        data = taobao.get_taobao_data()
        my_product_list = taobao.dump_data(data)

        # Store data to databases
        for item in my_product_list:
            one_product = TaobaoProduct(tile=item['title'],
                                        nick=item['nick'],
                                        pic_url=item['pic_url'],
                                        price=item['price'],
                                        click_url=item['click_url'])
            # save this product
            one_product.put()
            #print "save" , one_product.title

        # get all products in database
        products = TaobaoProduct.all()
        html_data = template.render(’table.html’, {’product_list’ : products})
        self.response.out.write(html_data )
        self.response.out.write("</body></html>")

这里render相当的难理解, 参考GAE的源码和django, render的第一个参数就是temlate文件,第二个
参数是一个hash, 可以把template文件里面的数据结构和需要显示的数据关联起来.

from google.appengine.ext import webapp

def render(template_path, template_dict, debug=False):
  """Renders the template at the given path with the given dict of values.

  Example usage:
    render("templates/index.html", {"name": "Bret", "values": [1, 2, 3]})

  Args:
    template_path: path to a Django template
    template_dict: dictionary of values to apply to the template
  """
  t = load(template_path, debug)
  return t.render(Context(template_dict))

在本例中, products表示所有TaobaoProduct object, ‘product_list’ 关键字就是在tempalte文
件中可以使用的变量. table.html文件如下, 显示了product的列表. 关于tempalte的语法,请参
考django的文档.

<ul>
{% for product in product_list %}
    <li>{{ product.title }}</li>
    <li>{{ product.nick }}</li>
    <li>{{ product.pic_url }}</li>
    <li>{{ product.price }}</li>
    <li>{{ product.click_url }}</li>
    <p></p>
{% endfor %}
</ul>

然后运行 ./dev_appserver.py ../helloworld/
运行结果如下:

<img src=”http://blogimg.chinaunix.net/blog/upfile2/090801114125.png" onload="javascript:if(this.width>500)this.width=500;" />500)this.width=500;" border="0">
APP目录helloworld打包下载:

文件:helloworld.zip
大小:3KB
下载:下载

Share and Enjoy:
  • Print this article!
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • RSS
  • Slashdot
  • Technorati
  • TwitThis

No related posts.

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Contact us

Admin: Bryan Wu