mashup:使用 Eclipse 在 Google App Engine 上创建 mashup 第 3 部分: 使用 RESTful Web 服务

  

  注意仍然把 /api 请求发送给主模块app.yaml 中为什么需要个新映射?我们不需要对 aggroGator API 进行验证这是在 app.yaml 中需要新规则原因由于利用主模块因此需要对它进行修改

  清单 13. 主模块新规则

def :
  app = webapp.WSGIApplication([
    ('/', MainPage),
    ('/addService', AddService),
    ('/getEntries', GetEntries),
    ('/api', AggroWebService),
    ('/getUserServices', GetUserServices),
    ], debug=True)
  util.run_wsgi_app(app)
__name__ '____':
  


  对该所做全部操作是向映射列表中添加个条目将把 /api 映射到 AggroWebService 控制器类中该类如下所示:

  清单 14. AggroWebService 控制器类

AggroWebService(webapp.RequestHandler):
  def get(self):
    self.response.headers['content-type'] = 'text/xml'
    username = self.request.get('username')
    entries = aggrogator.Aggrogator.get_feed(username)
    str = u"""<?xml version="1.0" encoding="utf-8"?><entries>"""
    for entry in entries:
      str entry.to_xml
    str "</entries>"
    self.response.out.write(str)


  该服务首先检索 username 请求参数然后使用以前看过 aggroGator 库但是使用区别思路方法 get_feed 以获得聚合条目该库代码如下所示:

  清单 15. aggroGator get_feed

Aggrogator:
  @method
  def get_feed(username):
    services = Aggrogator.get_services(username)
    entries =
    for svc_tuple in ((svc['service'], svc['username']) for svc in services):
      entries.extend(Cache.getEntries(*svc_tuple))
    entries.sort(key=operator.attrgetter('timestamp'), reverse=True)
     entries


  该 library 将使用在清单 10 中看到 get_services 检索聚合服务然后遍历服务代码将使用个集合以确保服务是惟(即如果用户已经订阅了都使用同项服务另外两个用户)由于使用了集合因此必须使用元组(tuple)只能使用不可修改对象最后按时间戳降序排列所有条目(首先列出最新条目)

  返回到清单 14在拥有条目列表的后使用某个简单串连接来创建 XML 文档对每个 Entry 例子使用 to_xml 思路方法这是个新思路方法如下所示:

  清单 16. Entry 类

Entry:
  def __init__(self, service=None, username=None, title=None,
link=None, content=None, timestamp=None):
    self.service = service
    self.username = username
    self.title = title
    self.link = link
    self.content = content
    self.timestamp = timestamp
  def to_dict(self):
     self.__dict__
  def to_xml(self):
    str = """<entry>
          <service>%s</service>
          <username>%s</username>
          <title>%s</title>
          <link>%s</link>
          <content><![CDATA[%s]]></content>
          <timestamp>%s</timestamp>
        </entry>"""
     str % (self.service, self.username, self.title, self.link, self.content,
self.timestamp)


  正如您所见to_xml 思路方法仅使用串模板和串替换来创建 XML 节点返回到清单 14在将 XML 文档创建为串后设置内容类型响应头部并将 XML 串发送回给请求者这是我们需要做全部操作我们创建了个可以供其他 mashup 使用 Web 服务



  结束语

  有关 Google App Engine “使用 Eclipse 在 Google App Engine 上创建 mashup” 系列第 3 部分到此结束在本文中添加了订阅和用于创建订阅 UI修改了使用订阅现有应用并且创建了 REST 样式 Web 服务以允许其他 mashup 从 aggroGator 进行构建在此的后我们还可以完成更多事务可以把注释添加到 Entry 类中添加允许用户向条目添加注释 UI可以提供订阅视图和个人视图可以扩展 Web 服务以便允许用户直接添加到提要中由于使用了 Google App Engine并且结合使用了 Eclipse 和 PyDev 等工具完成所有这些工作变得更加容易



Tags:  restful appengine googleappengine mashup

延伸阅读

最新评论

发表评论