Ejemplo n.º 1
0
 def PopulateRepos(self):
     shared.EnsureRunningInTask()  # gives us automatic retries
     repos = []
     template_dir = self.repo_collection.key.id()  # repo_collection_url
     for dirname in os.listdir(template_dir):
         # skip github submodule templates in production
         if not common.IsDevMode() and '-' in dirname:
             continue
         dirpath = os.path.join(template_dir, dirname)
         if not os.path.isdir(dirpath):
             continue
         try:
             with open(os.path.join(dirpath,
                                    _PLAYGROUND_SETTINGS_FILENAME)) as f:
                 data = json.loads(f.read())
             name = data.get('template_name')
             description = data.get('template_description')
             open_files = data.get('open_files', [])
         except IOError:
             name = dirpath
             description = dirname
             open_files = []
         url = os.path.join(template_dir, dirname)
         html_url = (
             'https://code.google.com/p/cloud-playground/source/browse/'
             '?repo=bliss#git%2F{}'.format(urllib.quote(url)))
         model.CreateRepoAsync(repo_url=url,
                               html_url=html_url,
                               name=name,
                               description=description,
                               open_files=open_files)
Ejemplo n.º 2
0
 def __call__(self, environ, start_response):
     if common.IsDevMode():
         logging.info('\n' * 1)
     try:
         return self.app(environ, start_response)
     except Exception, e:
         status, headers, body = error.MakeErrorResponse(e, self.debug)
         start_response(status, headers, sys.exc_info())
         return body
Ejemplo n.º 3
0
 def __call__(self, environ, start_response):
     if common.IsDevMode():
         logging.info('\n' * 1)
     # TODO: Use App Engine Modules to dispatch requests instead.
     if (environ['HTTP_HOST'] in settings.PLAYGROUND_HOSTS
             and environ['PATH_INFO'] == '/'):
         url = '/playground'
         if environ['QUERY_STRING']:
             url += '?' + environ['QUERY_STRING']
         start_response('302 Found', [('Location', url)])
         return iter([''])
     return self.app(environ, start_response)
Ejemplo n.º 4
0
def GetProjects(user):
  projects = ndb.get_multi(user.projects)
  if None in projects:
    # users.projects references projects which do not exist
    missing_projects = [key for (key, prj) in zip(user.projects, projects)
                        if prj is None]
    if common.IsDevMode():
      shared.e('Missing project(s): {0}'.format(missing_projects))
    else:
      shared.w('Missing project(s): {0}'.format(missing_projects))
      projects = [p for p in projects if p is not None]
  return projects
Ejemplo n.º 5
0
def _PerformCsrfRequestValidation(session, environ):
    session_xsrf = session['xsrf']
    client_xsrf = environ.get(_XSRF_TOKEN_HEADER)
    if not client_xsrf:
        Abort(httplib.UNAUTHORIZED, 'Missing client XSRF token.')
    if client_xsrf != session_xsrf:
        # do not log tokens in production
        if common.IsDevMode():
            logging.error(
                'Client XSRF token={0!r}, session XSRF token={1!r}'.format(
                    client_xsrf, session_xsrf))
        Abort(httplib.UNAUTHORIZED,
              'Client XSRF token does not match session XSRF token.')
Ejemplo n.º 6
0
    def PopulateRepos(self):
        shared.EnsureRunningInTask()  # gives us automatic retries
        baseurl = self.repo_collection.key.id()
        fetched = fetcher.Fetcher(baseurl, follow_redirects=True)
        page = fetched.content
        candidate_repos = self._GetChildPaths(page)
        fetches = []

        # we found a project in the root directory
        if 'app.yaml' in candidate_repos:
            candidate_repos.insert(0, '')

        if common.IsDevMode():
            # fetch fewer repos during development
            candidate_repos = candidate_repos[:1]

        for c in candidate_repos:
            if c and not c.endswith('/'):
                continue
            project_url = '{0}{1}'.format(baseurl, c)
            app_yaml_url = '{0}app.yaml'.format(project_url)
            fetched = fetcher.Fetcher(app_yaml_url, follow_redirects=True)
            fetches.append((c, project_url, app_yaml_url, fetched))

        for c, project_url, app_yaml_url, fetched in fetches:
            try:
                shared.i('found app.yaml: {}'.format(app_yaml_url))
                name = c.rstrip('/') or project_url
                description = 'Sample code from {0}'.format(project_url)
                model.CreateRepoAsync(owner=model.GetPublicTemplateOwner(),
                                      repo_url=project_url,
                                      html_url=project_url,
                                      name=name,
                                      description=description,
                                      show_files=[],
                                      read_only_files=[],
                                      read_only_demo_url=None)
            except urlfetch_errors.Error:
                exc_info = sys.exc_info()
                formatted_exception = traceback.format_exception(
                    exc_info[0], exc_info[1], exc_info[2])
                shared.w('skipping {0}'.format(project_url))
                for line in [line for line in formatted_exception if line]:
                    shared.w(line)
Ejemplo n.º 7
0
 def _MakeMimicUrl(self, project, path, params={}):
     """Build a mimic url."""
     project_id = urllib.quote_plus(str(project.key.id()))
     path = path.lstrip('/')
     if common.IsDevMode():
         url = ('{0}://{1}/{2}'.format(self.request.scheme,
                                       settings.MIMIC_HOST, path))
         params.update({
             common.config.PROJECT_ID_QUERY_PARAM: project_id,
         })
     else:
         url = ('{0}://{1}{2}{3}/{4}'.format(self.request.scheme,
                                             project_id, _DASH_DOT_DASH,
                                             settings.MIMIC_HOST, path))
     params.update({
         settings.ACCESS_KEY_SET_COOKIE_PARAM_NAME:
         project.access_key,
     })
     if params:
         url = "{}?{}".format(url, urllib.urlencode(params))
     return url
Ejemplo n.º 8
0
def _FixupSysPath():
    """Add additional directories to sys.path."""
    app_root_dir = os.path.dirname(__file__)
    for dir_name in ('lib', 'api-python-client'):
        dir_path = os.path.join(app_root_dir, 'api-python-client')
        if dir_path not in sys.path:
            sys.path.append(dir_path)


_FixupSysPath()

# our current app id
app_id = app_identity.get_application_id()

# pylint: disable-msg=invalid-name
if common.IsDevMode() or app_id == appids.PLAYGROUND_APP_ID:
    mimic_CREATE_TREE_FUNC = datastore_tree.DatastoreTree
else:
    mimic_CREATE_TREE_FUNC = zip_urlfetch_tree.ZipUrlFetchTree

mimic_JSON_ENCODER = json.JSONEncoder()
mimic_JSON_ENCODER.indent = 4
mimic_JSON_ENCODER.sort_keys = True

mimic_NAMESPACE = '_playground'

# keep in sync with app/js/controllers.js
mimic_PROJECT_ID_QUERY_PARAM = '_mimic_project'

mimic_PROJECT_ID_FROM_PATH_INFO_RE = re.compile('/playground/p/(.+?)/')
Ejemplo n.º 9
0
def ThisIsPlaygroundApp():
    """Determines whether this is the playground app id."""
    if common.IsDevMode():
        return not backends.get_backend()
    return app_identity.get_application_id() == appids.PLAYGROUND_APP_ID