def DoMappingTest(self,
                    services,
                    registry_path='/myreg',
                    expected_paths=None):
    mapped_services = mapping = service_handlers.service_mapping(services,
                                                                 registry_path)
    if registry_path:
      form_mapping = mapping[:2]
      mapped_registry_path, mapped_registry_factory = mapping[-1]
      mapped_services = mapping[2:-1]
      self.CheckFormMappings(form_mapping, registry_path=registry_path)

      self.assertEquals(r'(%s)%s' % (registry_path,
                                     service_handlers._METHOD_PATTERN),
                        mapped_registry_path)
      self.assertEquals(registry.RegistryService,
                        mapped_registry_factory.service_factory.service_class)

      # Verify registry knows about other services.
      expected_registry = {registry_path: registry.RegistryService}
      for path, factory in dict(services).iteritems():
        if isinstance(factory, type) and issubclass(factory, remote.Service):
          expected_registry[path] = factory
        else:
          expected_registry[path] = factory.service_class
      self.assertEquals(expected_registry,
                        mapped_registry_factory().service.registry)

    # Verify that services are mapped to URL.
    self.assertEquals(len(services), len(mapped_services))
    for path, service in dict(services).iteritems():
      mapped_path = r'(%s)%s' %  (path, service_handlers._METHOD_PATTERN)
      mapped_factory = dict(mapped_services)[mapped_path]
      self.assertEquals(service, mapped_factory.service_factory)
示例#2
0
文件: main.py 项目: Alattack/catapult
def main():
  path_info = os.environ.get('PATH_INFO', '')
  service_path, registry_path = parse_service_path(path_info)

  # Create webapp URL mappings for service and private registry.
  mapping = service_handlers.service_mapping(
    [(service_path, protorpc_appstats.AppStatsService)], registry_path)

  application = webapp.WSGIApplication(mapping)
  util.run_wsgi_app(application)
示例#3
0
def main():
    path_info = os.environ.get('PATH_INFO', '')
    service_path, registry_path = parse_service_path(path_info)

    # Create webapp URL mappings for service and private registry.
    mapping = service_handlers.service_mapping(
        [(service_path, protorpc_appstats.AppStatsService)], registry_path)

    application = webapp.WSGIApplication(mapping)
    util.run_wsgi_app(application)
  def testDefaultMappingWithFactory(self):
    mapping = service_handlers.service_mapping(
      [MyService.new_factory('service1')])
    mapped_services = mapping[2:-1]
    self.assertEquals(1, len(mapped_services))
    path, factory = mapped_services[0]

    self.assertEquals(
      r'(/test_package/MyService)' + service_handlers._METHOD_PATTERN,
      path)
    self.assertEquals(MyService, factory.service_factory.service_class)
示例#5
0
class EndToEndTestBase(WebServerTestBase):

  # Sub-classes may override to create alternate configurations.
  DEFAULT_MAPPING = service_handlers.service_mapping(
    [('/my/service', TestService),
     ('/my/other_service', TestService.new_factory('initialized')),
    ])

  def setUp(self):
    super(EndToEndTestBase, self).setUp()

    self.stub = TestService.Stub(self.connection)

    self.other_connection = ServerTransportWrapper(
      self.server,
      self.CreateTransport(self.other_service_url))
    self.other_stub = TestService.Stub(self.other_connection)

    self.mismatched_stub = AlternateService.Stub(self.connection)

  @property
  def other_service_url(self):
    return 'http://localhost:%d/my/other_service' % self.port

  def CreateWsgiApplication(self):
    """Create WSGI application used on the server side for testing."""
    return webapp.WSGIApplication(self.DEFAULT_MAPPING, True)

  def DoRawRequest(self,
                   method,
                   content='',
                   content_type='application/json',
                   headers=None):
    headers = headers or {}
    headers.update({'content-length': len(content or ''),
                    'content-type': content_type,
                   })
    request = urllib2.Request('%s.%s' % (self.service_url, method),
                              content,
                              headers)
    self.server.handle_request()
    return urllib2.urlopen(request)

  def RawRequestError(self,
                      method,
                      content='',
                      content_type='application/json',
                      headers=None):
    try:
      self.DoRawRequest(method, content, content_type, headers)
      self.fail('Expected HTTP error')
    except urllib2.HTTPError, err:
      return err.code, err.read(), err.headers
示例#6
0
def main():
    util.run_wsgi_app(webapp.WSGIApplication(
        # RPC services go here
        service_handlers.service_mapping([
            hello.HelloService.mapping(
                root='/rpc',
                implementation=HelloServiceImpl("Hey, hello %s!")
            ),
        ])
        +
        # Normal webapp handlers go here
        [
            ('/Test', TestHandler),
        ]
    ))
  def testDefaultMappingWithClass(self):
    """Test setting path just from the class.

    Path of the mapping will be the fully qualified ProtoRPC service name with
    '.' replaced with '/'.  For example:

      com.nowhere.service.TheService -> /com/nowhere/service/TheService
    """
    mapping = service_handlers.service_mapping([MyService])
    mapped_services = mapping[2:-1]
    self.assertEquals(1, len(mapped_services))
    path, factory = mapped_services[0]

    self.assertEquals(
      r'(/test_package/MyService)' + service_handlers._METHOD_PATTERN,
      path)
    self.assertEquals(MyService, factory.service_factory)
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util

from protorpc import messages
from protorpc import remote
from protorpc.webapp import service_handlers

from handler.orderajax import BlacklistAjax
from handler.orderajax import OrderAjax

service_mappings = service_handlers.service_mapping(
    [('/orderajax', OrderAjax),
     ('/blacklist', BlacklistAjax)
    ])

application = webapp.WSGIApplication(service_mappings)

def main():
  util.run_wsgi_app(application)

if __name__ == '__main__':
  main()
示例#9
0
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util

from protorpc import messages
from protorpc import remote
from protorpc.webapp import service_handlers

from handler.orderajax import BlacklistAjax
from handler.orderajax import OrderAjax

service_mappings = service_handlers.service_mapping([('/orderajax', OrderAjax),
                                                     ('/blacklist',
                                                      BlacklistAjax)])

application = webapp.WSGIApplication(service_mappings)


def main():
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
示例#10
0
                            record.friends.remove(
                                request.nickname
                            )  # will raise ValueError if request.nickname is not in friends
                            q[0].delete()
                            record.put()
                            error = "removed %s" % (request.nickname)
                        except ValueError:
                            # trying to remove a value not in a list raises ValueError
                            error = "could not find %s in your friend list" % (
                                request.nickname)
                else:
                    error = "could not find %s in your friend list" % (
                        request.nickname)
            else:
                pass
        else:
            logging.info(__file__ + ': no user logged in')

        #create and return the response
        fsar = FriendServiceActionResponse()
        fsar.error = error
        return fsar


application = webapp.WSGIApplication(service_handlers.service_mapping([
    ('/FriendService', FriendService)
]),
                                     debug=True)

if __name__ == "__main__":
    run_wsgi_app(application)
示例#11
0
文件: root.py 项目: jenaiz/Crawly
class Note(messages.Message):
    text = messages.StringField(1, required=True)
    when = messages.IntegerField(2)


class RootService(remote.Service):
    @remote.method(Note, Note)
    def add_worker(self, request):
        # print str(requefdfhhhffufufuufuffuuufufufufuuuufufufuffuufufuuufufuufuuuuffufuufufuufufufufuufuufufufuuffufffuufufufuuufufuuuuufufuudfufufufuufuffuufufufufuffuufufufuffuuffuuufuffffffufuufuufufufuffudfucufuffufuuffufufufifuufufufuff8f88fufufuduvvcicuuciviififuvIUPÑKLLst.text)
        # text = 'Receiving... ' + request.text
        return Note(text=u"Answering ...", when=int(time.time()))


# app = webapp.WSGIApplication(service_handlers.service_mapping([('/root', RootService)]),  debug=True)

# Map the RPC service and path (/hello)
# hello_service = service.service_mapping(RootService, '/root.*')
# app = webapp2.WSGIApplication([('/root', RootService),],
#                              debug=True)

service_mappings = service_handlers.service_mapping([("/root", RootService)])

app = webapp.WSGIApplication(service_mappings, debug=True)

# def main():
#  run_wsgi_app(appn)


# if __name__ == '__main__':
#  main()
示例#12
0
#
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.
#
#
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import postservice
from protorpc.webapp import service_handlers

application = webapp.WSGIApplication(service_handlers.service_mapping([('/tick', postservice.ReceiveTick)]),debug=True)


def main():
        util.run_wsgi_app(application)
        #webapp.WSGIApplication(application)
if __name__ == '__main__':
        main()
示例#13
0
文件: root.py 项目: jenaiz/Crawly
        url = request.message
        urls = url.split(',')
        for l in urls:
            taskqueue.add(url='/queue', params={'key': l})
      
        return RootResponse(message='urls received: ' + str(len(urls)))

class QueueHandler(webapp.RequestHandler):
    def post(self):
        key = self.request.get('key')
        page = crawler.crawl_web(key)
        def txn():
            url = Url.get_by_key_name(key)
            if url is None:
                url = Url(key_name=key, uri=key, content=cgi.escape(page[:100]))
            url.put()
        db.run_in_transaction(txn)


service_mappings = service_handlers.service_mapping(
        [('/root', RootService)         
        ])
#service_mappings.append(('/queue', QueueHandler))

app = webapp2.WSGIApplication(service_mappings)

def main():
    util.run_wsgi_app(application)

if __name__ == '__main__':
    main()
示例#14
0
def main():
    application = webapp.WSGIApplication(
        service_handlers.service_mapping(urls), debug=True)
    util.run_wsgi_app(application)
示例#15
0
文件: main.py 项目: Alattack/catapult
def load_quota_config(quota_config_path=QUOTA_CONFIG_PATH):
  """Load quota configuration from from file.

  Args:
    quota_config_path: Quota to configuration file.  Contents of file must be
      a JSON encoded ProtoRPC message of the format defined by
      quota.services.QuotaConfig.

    Returns:
      quota.services.QuotaConfig instance with contents parsed from quota file.
  """
  with open(quota_config_path) as quota_config_file:
    encoded_config = quota_config_file.read()
  return protojson.decode_message(services.QuotaConfig, encoded_config)

service_mappings = service_handlers.service_mapping(
  [
    ('/quota-service',
     services.QuotaService.new_factory(load_quota_config(), {})),
  ])

application = webapp.WSGIApplication(service_mappings, debug=True)


def main():
  util.run_wsgi_app(application)


if __name__ == '__main__':
  main()
示例#16
0
def load_quota_config(quota_config_path=QUOTA_CONFIG_PATH):
    """Load quota configuration from from file.

  Args:
    quota_config_path: Quota to configuration file.  Contents of file must be
      a JSON encoded ProtoRPC message of the format defined by
      quota.services.QuotaConfig.

    Returns:
      quota.services.QuotaConfig instance with contents parsed from quota file.
  """
    with open(quota_config_path) as quota_config_file:
        encoded_config = quota_config_file.read()
    return protojson.decode_message(services.QuotaConfig, encoded_config)


service_mappings = service_handlers.service_mapping([
    ('/quota-service',
     services.QuotaService.new_factory(load_quota_config(), {})),
])

application = webapp.WSGIApplication(service_mappings, debug=True)


def main():
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
示例#17
0
        notes = []
        for note_model in query.fetch(request.limit):
            if note_model.date:
                when = int(time.mktime(note_model.date.utctimetuple()))
            else:
                when = None
            note = Note(text=note_model.content, when=when)
            notes.append(note)

        if request.order == GetNotesRequest.Order.TEXT:
            notes.sort(key=lambda note: note.text)

        return Notes(notes=notes)


service_mapping = service_handlers.service_mapping([('/postservice',
                                                     PostService)])

application = webapp.WSGIApplication([
    ('/', MainPage),
    ('/sign', Guestbook),
] + service_mapping,
                                     debug=True)


def main():
    wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
    main()
示例#18
0
文件: main.py 项目: dfuerle/elondore
# !/usr/bin/env python
from google.appengine.dist import use_library
use_library('django', '1.2')
#use_library('django', '0.96')
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from protorpc.webapp import service_handlers

import elondoreService

# Register mapping with application.
application = webapp.WSGIApplication(
  service_handlers.service_mapping(
    [('/rpc', elondoreService.elondoreService)]),
  debug=True)

def main():
  util.run_wsgi_app(application)

if __name__ == '__main__':
  main()
示例#19
0
class GetImageRequest(messages.Message):
  id = messages.StringField(1, required=True)

class GetImageResponse(messages.Message):
  ogl = messages.StringField(1, required=True)

class RPCService(remote.Service):
    
  @remote.method(GetOGLRequest, GetOGLResponse)
  def GetImage(self, request):
      
      lease = OilGasLease.get_by_key_name( request.id )
      if lease:
          lease.toCSV()
          
      
    return GetOGLResponse(hello='Hello there, %s!' %
                         request.my_name)

service_mappings = service_handlers.service_mapping(
    [('/rpc', RPCService),
    ])

application = webapp.WSGIApplication(service_mappings)

def main():
  util.run_wsgi_app(application)

if __name__ == '__main__':
  main()
示例#20
0
def main():
    application = webapp.WSGIApplication(service_handlers.service_mapping(urls),
        debug=True)
    util.run_wsgi_app(application)
                    else:
                        try:
                            record = q[0]
                            record.friends.remove(request.nickname) # will raise ValueError if request.nickname is not in friends
                            q[0].delete()
                            record.put()
                            error = "removed %s" % (request.nickname)
                        except ValueError:
                            # trying to remove a value not in a list raises ValueError
                            error = "could not find %s in your friend list" % (request.nickname)
                else:
                    error = "could not find %s in your friend list" % (request.nickname)
            else:
                pass
        else:
            logging.info(__file__ + ': no user logged in')
        
        #create and return the response
        fsar = FriendServiceActionResponse()
        fsar.error = error
        return fsar

application = webapp.WSGIApplication(
    service_handlers.service_mapping(
        [('/FriendService', FriendService)]
    ),
    debug=True
)

if __name__ == "__main__":
    run_wsgi_app(application)
示例#22
0
        logging.debug("Success")
        total=0.0
        for page in query:
            p = pageInfo()
            p = page
            
            if existing_pages.has_key(p.page_name) == False:
                existing_pages[p.page_name]='exist'
                pages.append(p)
                total = total + p.page_rank
                                                         
        for p in pages:
            self.response.out.write("%s %f\n" % (p.page_name,p.page_rank))
        self.response.out.write("Total %f" % total)    

service_mapping = service_handlers.service_mapping([('/getindex',GetPageRankIndexService),])

APP = webapp.WSGIApplication(
    [
        ('/', IndexHandler),
        ('/page-rank-index',GetPageRankIndex),
    ]+service_mapping,
    debug=True)

def main():
    
  logging.getLogger().setLevel(logging.DEBUG) 
  util.run_wsgi_app(APP)

if __name__ == '__main__':
  main()
示例#23
0
   notes = []
   for note_model in query.fetch(request.limit):
    if note_model.date:
      when = int(time.mktime(note_model.date.utctimetuple()))
    else:
      when = None
    note = Note(text=note_model.content, when=when)
    notes.append(note)

   if request.order == GetNotesRequest.Order.TEXT:
    notes.sort(key=lambda note: note.text)

   return Notes(notes=notes)


service_mapping = service_handlers.service_mapping(
    [('/postservice', PostService)])

application = webapp.WSGIApplication([
  ('/', MainPage),
  ('/sign', Guestbook),
] + service_mapping,
debug=True)


def main():
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()
示例#24
0
import os

os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

import django.core.handlers.wsgi

app = django.core.handlers.wsgi.WSGIHandler()

from google.appengine.ext import deferred

app_deferred = deferred.application

import webapp2
from protorpc.webapp import service_handlers

from service.api.one import timelineservice, suggestionservice, mapservice, loginservice
from service.api import middleware


# Register mapping with application.
app_api = webapp2.WSGIApplication(
                                     service_handlers.service_mapping(
                                          [('(?i)/api/1/TimelineService', timelineservice.TimelineService),
                                           ('(?i)/api/1/SuggestionService', suggestionservice.SuggestionService),
                                           ('(?i)/api/1/MapService', mapservice.MapService),
                                           ('(?i)/api/1/LoginService', loginservice.LoginService),
                                           ]),
                                          debug=True)
app_api = middleware.OAuthware(app_api)
示例#25
0
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util

from protorpc.webapp import service_handlers

from webservices import authenticateuserservice
from webservices import getservicesservice
from webservices import getserviceusageservice
from webservices import validateclientservice

# http://localhost:8080/webservices/authenticateuser/authenticateuserservice
# http://localhost:8080/webservices/authenticateuser/authenticateuser
# http://localhost:8080/protorpc/form

service_mappings = service_handlers.service_mapping([
    ("/webservices/user", authenticateuserservice.AuthenticateUserService),
    ("/webservices/client", validateclientservice.ValidateClientService),
    ("/webservices/services", getservicesservice.GetServicesService),
    ("/webservices/serviceusage", getserviceusageservice.GetServiceUsageService)
])

application = webapp.WSGIApplication(service_mappings, debug = True)

def main():
    util.run_wsgi_app(application)

if __name__ == "__main__":
    main()
示例#26
0
文件: worker.py 项目: jenaiz/Crawly
        
        return WorkerResponse(message='hashcode = ' + str(hash_code))
        
        
class QueueHandler(webapp.RequestHandler):
    def post(self):
        key = self.request.get('key')
        url = Url.get_by_key_name(key)
        if url is None:
            page, links = crawler.crawl_web(key)
            def txn():
                url = Url.get_by_key_name(key)
                if url is None:
                    url = Url(key_name=key, uri=key)
                    for l in links:
                        taskqueue.add(queue_name='url-crawler-queue', url='/queue', params={'key': l})                    
                url.put()
            db.run_in_transaction(txn)

service_mappings = service_handlers.service_mapping(
        [('/worker', WorkerService)         
        ])
service_mappings.append(('/queue', QueueHandler))

application = webapp.WSGIApplication(service_mappings)

def main():
    util.run_wsgi_app(application)

if __name__ == '__main__':
    main()