Пример #1
0
def connect(url, email=None, password=None, exit_on_failure=False):
    """Sets up a connection to an app that has the remote_api handler."""
    secure, host, port, path = parse_url(url)
    hostport = '%s:%d' % (host, port)
    url = (secure and 'https' or 'http') + '://' + hostport + path

    def get_login():
        # Get the e-mail and password from args, os.environ, or the user.
        e = email or os.environ.get('USER_EMAIL')
        if not e:
            sys.stderr.write('User e-mail: ')
            sys.stderr.flush()
            e = raw_input()  # don't use raw_input's prompt (goes to stdout)
        else:
            print >> sys.stderr, 'User e-mail: %s' % e
        os.environ['USER_EMAIL'] = e  # used by users.get_current_user()
        p = password
        if not p and host != 'localhost':
            p = getpass.getpass('Password: '******'/remote_api'):
                path = path.rstrip('/') + '/remote_api'
                remote_api_stub.ConfigureRemoteApi(None,
                                                   path,
                                                   get_login,
                                                   hostport,
                                                   secure=secure)
            else:
                raise
    except Exception, e:
        if isinstance(e, urllib2.HTTPError):
            print >> sys.stderr, 'HTTP error %d from URL: %s' % (e.code, e.url)
        elif isinstance(e, urllib2.URLError):
            reason = hasattr(e.reason,
                             'args') and e.reason.args[-1] or e.reason
            print >> sys.stderr, 'Cannot connect to %s: %s' % (hostport,
                                                               reason)
        else:
            print >> sys.stderr, 'Connection error: %s' % e
        if exit_on_failure:
            sys.exit(1)
        return None
    def MaybeConfigureRemoteDataApis(self):
        """Set up stubs using remote_api as appropriate.

    If this is the API server (or is not multiprocess), return False.
    Otherwise, set up the stubs for data based APIs as remote stubs pointing at
    the to the API server and return True.
    """
        if self.IsDefault():
            return False

        services = (
            'app_identity_service',
            'capability_service',
            'conversion',
            'datastore_v3',
            'memcache',
            'taskqueue',
            'urlfetch',
        )
        remote_api_stub.ConfigureRemoteApi(self.app_id,
                                           PATH_DEV_API_SERVER,
                                           lambda: ('', ''),
                                           servername='%s:%d' %
                                           (API_SERVER_HOST, self.api_port),
                                           services=services,
                                           use_remote_datastore=False)
        return True
Пример #3
0
 def setupLocalRemote(self):
     """It connects with the remote/dev server."""
     time.sleep(2)
     remote_api_stub.ConfigureRemoteApi('dev~local-devel',
                                        '/_ah/remote_api', lambda:
                                        ('*****@*****.**', ''),
                                        "localhost:%d" % self.port)
Пример #4
0
def download_appstats(servername, appid, path, secure, rpc_server_factory,
                      filename, appdir, merge, java_application):
    """Invoke remote_api to download appstats data."""

    if os.path.isdir(appdir):
        sys.path.insert(0, appdir)
        try:
            logging.info('Importing appengine_config from %s', appdir)
            import appengine_config
        except ImportError as err:
            logging.warn('Failed to load appengine_config: %s', err)

    remote_api_stub.ConfigureRemoteApi(appid,
                                       path,
                                       auth_func,
                                       servername=servername,
                                       save_cookies=True,
                                       secure=secure,
                                       rpc_server_factory=rpc_server_factory)
    remote_api_stub.MaybeInvokeAuthentication()

    os.environ['SERVER_SOFTWARE'] = 'Development (remote_api_shell)/1.0'

    if not appid:

        appid = os.environ['APPLICATION_ID']
    download_data(filename, merge, java_application)
Пример #5
0
    def run_from_argv(self, argv):
        from google.appengine.ext.remote_api import remote_api_stub
        from google.appengine.tools import appengine_rpc
        import getpass
        from djangae.boot import find_project_root

        self.stdout = OutputWrapper(sys.stdout)

        def auth_func():
            return (raw_input('Google Account Login:'******'Password:'******'app.yaml')).read()

        app_id = app_yaml.split("application:")[1].lstrip().split()[0]

        self.stdout.write(
            "Opening Remote API connection to {0}...\n".format(app_id))
        remote_api_stub.ConfigureRemoteApi(
            None,
            '/_ah/remote_api',
            auth_func,
            servername='{0}.appspot.com'.format(app_id),
            secure=True,
        )
        self.stdout.write(
            "...Connection established...have a nice day :)\n".format(app_id))
        argv = argv[:1] + argv[2:]
        execute_from_command_line(argv)
Пример #6
0
  def activate(self):
    """Activates the testbed.

    Invoking this method will also assign default values to environment
    variables that are required by App Engine services, such as
    `os.environ['APPLICATION_ID']`. You can set custom values with
    `setup_env()`.
    """
    self._orig_env = dict(os.environ)
    self.setup_env()






    self._original_stub_map = apiproxy_stub_map.apiproxy
    self._test_stub_map = apiproxy_stub_map.APIProxyStubMap()
    internal_map = self._original_stub_map._APIProxyStubMap__stub_map
    self._test_stub_map._APIProxyStubMap__stub_map = dict(internal_map)
    apiproxy_stub_map.apiproxy = self._test_stub_map
    self._activated = True

    self._use_datastore_emulator = EmulatorSupportChecker.check()
    if self._use_datastore_emulator:
      self.api_port = EmulatorSupportChecker.get_api_port()
      self.rpc_server = remote_api_stub.ConfigureRemoteApi(
          os.environ['APPLICATION_ID'],
          '/',
          lambda: ('', ''),
          'localhost:%d' % self.api_port,
          services=[],
          apiproxy=self._test_stub_map,
          use_remote_datastore=False)
Пример #7
0
    def _env_setUp(self):
        self.kind_method_swapped = False
        self.original_kind_method = None

        if self.may_cleanup_used_kind():
            global kind_names_for_test
            kind_names_for_test = {}

        set_environments(self)

        if self.use_swapped_kind_name():
            self.swap_model_kind()

        if is_in_production() and self.use_production_environment():
            apiproxy_stub_map.apiproxy = get_original_apiproxy_behind_gaeunit()
        elif is_in_production():
            pass  # use apiproxy prepared by GAEUnit (datastore_stub is datastore_file_stub)
        elif not is_in_gaeunit() and self.use_remote_api():
            remote_api_stub.ConfigureRemoteApi(APP_ID,
                                               REMOTE_API_ENTRY_POINT,
                                               auth_func,
                                               secure=True,
                                               save_cookies=True)
            if not self.authenticated_for_remote_api:
                remote_api_stub.MaybeInvokeAuthentication()
                self.authenticated_for_remote_api = True
        else:
            apiproxy_stub_map.apiproxy = get_dev_apiproxy()
Пример #8
0
def main(key, url):
    print "Configuring GAE Remote API on {} to import {}".format(url, key)
    if 'localhost' in url:
        remote_api_stub.ConfigureRemoteApi(None, '/_ah/remote_api',
                                           local_auth_func, url)
    else:
        remote_api_stub.ConfigureRemoteApiForOAuth(url, '/_ah/remote_api')

    print "Loading data from The Blue Alliance requires an API key"
    print "Please go to https://thebluealliance.com/account and generate a read API key"
    apiv3_key = raw_input("Enter your API key: ")

    global AUTH_TOKEN
    AUTH_TOKEN = apiv3_key

    if Match.validate_key_name(key):
        match_data = fetch_match(key)
        store_match(match_data)

    elif Event.validate_key_name(key):
        update_event(key)
    elif Team.validate_key_name(key):
        team_data = fetch_team(key)
        store_team(team_data)
    elif key.isdigit():
        event_keys = [
            event['key'] for event in fetch_endpoint('events/{}'.format(key))
        ]
        for event in event_keys:
            update_event(event)
    else:
        print "Unknown key :("
Пример #9
0
def clear_datastore(appid=('a', ''),
                    host=('h', ''),
                    path=('p', ''),
                    kinds=('k', ''),
                    clear_memcache=('c', False),
                    secure=True):
    """Clear all the data on GAE environment using remote_api.
  """
    if not appid:
        appid = get_appid()
    if not host:
        host = "%s.appspot.com" % appid
    if not path:
        path = '/remote_api'
    if not kinds:
        models = None
    else:
        models_dict = get_all_models_as_dict()
        models = []
        for kind in kinds.split(','):
            models.append(db.class_for_kind(kind))

    remote_api_stub.ConfigureRemoteApi(appid,
                                       path,
                                       auth_func,
                                       host,
                                       secure=secure,
                                       save_cookies=True)
    remote_api_stub.MaybeInvokeAuthentication()
    delete_all_entities(models)
    if clear_memcache:
        from google.appengine.api import memcache
        memcache.flush_all()
        sys.stderr.write("Flushed memcache.\n")
Пример #10
0
 def setup_remote(self):
     if not self.remote_api_path:
         from ..utils import appconfig
         for handler in appconfig.handlers:
             if handler.script == REMOTE_API_SCRIPT:
                 self.remote_api_path = handler.url
                 break
     self.remote = True
     remote_url = 'https://%s.appspot.com%s' % (self.remote_app_id,
                                                self.remote_api_path)
     logging.info('Setting up remote_api for "%s" at %s' %
                  (self.remote_app_id, remote_url))
     if not have_appserver:
         print 'Connecting to remote_api handler'
     from google.appengine.ext.remote_api import remote_api_stub
     remote_api_stub.ConfigureRemoteApi(self.remote_app_id,
         self.remote_api_path, auth_func, secure=self.secure_remote_api,
         rpc_server_factory=rpc_server_factory)
     retry_delay = 1
     while retry_delay <= 16:
         try:
             remote_api_stub.MaybeInvokeAuthentication()
         except HTTPError, e:
             if not have_appserver:
                 print 'Retrying in %d seconds...' % retry_delay
             time.sleep(retry_delay)
             retry_delay *= 2
         else:
             break
Пример #11
0
def create_user(user_name=('u', ''), password=('P', ''), is_admin=('A', False),
                appid=('a', ''), host=('h', ''), path=('p', ''), secure=True):
  """ Create new user using remote_api.
  """
  from kay.auth import (
    create_new_user, DuplicateKeyError,
  )
  if not user_name:
    print_status('user_name required')
    sys.exit(1)
  if not password:
    password = getpass.getpass('Please input a password for new user:'******'/remote_api'
  
  remote_api_stub.ConfigureRemoteApi(None, path, auth_func,
                                     host, secure=secure, save_cookies=True)
  remote_api_stub.MaybeInvokeAuthentication()
  try:
    create_new_user(user_name, password, is_admin=is_admin)
    print_status('A new user: %s successfully created.' % user_name)
    sys.exit(0)
  except DuplicateKeyError, e:
    print_status(e)
    sys.exit(1)
Пример #12
0
 def setup_remote_stubs(self, connection):
     if self.active_stubs == 'remote':
         return
     if not connection.remote_api_path:
         from ..utils import appconfig
         for handler in appconfig.handlers:
             if handler.script in REMOTE_API_SCRIPTS:
                 connection.remote_api_path = handler.url.split('(', 1)[0]
                 break
     server = '%s.%s' % (connection.remote_app_id, connection.domain)
     remote_url = 'https://%s%s' % (server, connection.remote_api_path)
     logging.info("Setting up remote_api for '%s' at %s." %
                  (connection.remote_app_id, remote_url))
     if not have_appserver:
         logging.info(
             "Connecting to remote_api handler.\n\n"
             "IMPORTANT: Check your login method settings in the "
             "App Engine Dashboard if you have problems logging in. "
             "Login is only supported for Google Accounts.")
     from google.appengine.ext.remote_api import remote_api_stub
     remote_api_stub.ConfigureRemoteApi(None,
         connection.remote_api_path, auth_func, servername=server,
         secure=connection.secure_remote_api,
         rpc_server_factory=rpc_server_factory)
     retry_delay = 1
     while retry_delay <= 16:
         try:
             remote_api_stub.MaybeInvokeAuthentication()
         except HTTPError, e:
             if not have_appserver:
                 logging.info("Retrying in %d seconds..." % retry_delay)
             time.sleep(retry_delay)
             retry_delay *= 2
         else:
             break
Пример #13
0
    def inner(appid=('a', ''),
              host=('h', ''),
              path=('p', ''),
              secure=True,
              clean=('c', False)):
        if not appid:
            appid = get_appid()
        if not host:
            host = "%s.appspot.com" % appid
        if not path:
            path = '/remote_api'

        if 'localhost' in host:
            auth_func = dummy_auth
        else:
            auth_func = auth

        remote_api_stub.ConfigureRemoteApi(appid,
                                           path,
                                           auth_func,
                                           host,
                                           secure=secure,
                                           save_cookies=True)
        remote_api_stub.MaybeInvokeAuthentication()

        if clean and callable(clean_func):
            clean_func()
        if callable(main_func):
            main_func()
def remote_api_shell(servername, appid, path, secure, rpc_server_factory):
  """Actually run the remote_api_shell."""


  remote_api_stub.ConfigureRemoteApi(appid, path, auth_func,
                                     servername=servername,
                                     save_cookies=True, secure=secure,
                                     rpc_server_factory=rpc_server_factory)
  remote_api_stub.MaybeInvokeAuthentication()


  os.environ['SERVER_SOFTWARE'] = 'Development (remote_api_shell)/1.0'

  if not appid:

    appid = os.environ['APPLICATION_ID']
  sys.ps1 = '%s> ' % appid
  if readline is not None:

    readline.parse_and_bind('tab: complete')
    atexit.register(lambda: readline.write_history_file(HISTORY_PATH))
    if os.path.exists(HISTORY_PATH):
      readline.read_history_file(HISTORY_PATH)


  code.interact(banner=BANNER, local=globals())
Пример #15
0
 def setup_remote(self):
     if not self.remote_api_path:
         from ..utils import appconfig
         for handler in appconfig.handlers:
             if handler.script == REMOTE_API_SCRIPT:
                 self.remote_api_path = handler.url.split('(', 1)[0]
                 break
     self.remote = True
     remote_url = 'https://%s.appspot.com%s' % (self.remote_app_id,
                                                self.remote_api_path)
     logging.info('Setting up remote_api for "%s" at %s' %
                  (self.remote_app_id, remote_url))
     if not have_appserver:
         print('Connecting to remote_api handler.\n\n'
               'IMPORTANT: Check your login method settings in the '
               'App Engine Dashboard if you have problems logging in. '
               'Login is only supported for Google Accounts.\n')
     from google.appengine.ext.remote_api import remote_api_stub
     remote_api_stub.ConfigureRemoteApi(self.remote_app_id,
         self.remote_api_path, auth_func, secure=self.secure_remote_api,
         rpc_server_factory=rpc_server_factory)
     retry_delay = 1
     while retry_delay <= 16:
         try:
             remote_api_stub.MaybeInvokeAuthentication()
         except HTTPError, e:
             if not have_appserver:
                 print 'Retrying in %d seconds...' % retry_delay
             time.sleep(retry_delay)
             retry_delay *= 2
         else:
             break
Пример #16
0
def setUpModule():
    handler_test_utils.start_dev_appserver(db='testutil/test_db.sqlite')
    remote_api_stub.ConfigureRemoteApi(
        None,
        '/_ah/remote_api',
        auth_func=(lambda: ('test', 'test')),  # username/password
        servername=handler_test_utils.appserver_url[len('http://'):])
    oauth_test_client.stub_for_oauth()
Пример #17
0
def attach(appid):
    def auth_func():
        return (raw_input('Email:'), getpass.getpass('Password:'******'SERVER_SOFTWARE'] = 'Development (remote_api)/1.0'
Пример #18
0
def init_remote_api(app_id):
    from remote_api_shell import fix_sys_path
    fix_sys_path()
    from google.appengine.ext.remote_api import remote_api_stub

    login = lambda: (app_engine_username, app_engine_password)

    remote_api_stub.ConfigureRemoteApi(None, '/_ah/remote_api', login,
                                       '%s.appspot.com' % app_id)
Пример #19
0
def prep_remote_shell(path='/remote_api'):
    """Prepares a remote shell using remote_api located at the given path on
    the given host, if given.  By default, will use the default version of the
    current App Engine application."""
    auth_func = lambda: (raw_input('Email: '), getpass.getpass('Password: '******'SERVER_SOFTWARE'] = 'Development (remote_api_shell)/1.0'
Пример #20
0
def attach(host=None):
    def auth_func():
        if host and host.startswith('localhost'):
            return ('foo', 'bar')
        else:
            return (EMAIL, getpass.getpass())

    remote_api_stub.ConfigureRemoteApi(APPID, REMOTE_API_PATH, auth_func, host)
    remote_api_stub.MaybeInvokeAuthentication()
    os.environ['SERVER_SOFTWARE'] = 'Development (remote_api)/1.0'
Пример #21
0
def rshell(appid=('a', ''),
           host=('h', ''),
           path=('p', ''),
           useful_imports=True,
           secure=True,
           use_ipython=True):
    """Start a new interactive python session with RemoteDatastore stub."""
    banner = ("Interactive Kay Shell with RemoteDatastore. \n"
              "-----------------WARNING--------------------\n"
              "\n"
              "Please be careful in this console session.\n"
              "\n"
              "-----------------WARNING--------------------\n")
    if useful_imports:
        namespace = create_useful_locals_for_rshell()
    else:
        namespace = {}
    if not appid:
        appid = get_appid()
    if not host:
        host = "%s.appspot.com" % appid
    if not path:
        path = '/remote_api'

    remote_api_stub.ConfigureRemoteApi(appid,
                                       path,
                                       auth_func,
                                       host,
                                       secure=secure,
                                       save_cookies=True)
    remote_api_stub.MaybeInvokeAuthentication()
    if use_ipython:
        try:
            import IPython
        except ImportError:
            pass
        else:
            sh = IPython.Shell.IPShellEmbed(
                argv=['-pi1',
                      '%s[\#]: ' % appid, '-po',
                      '%s[\#]: ' % appid],
                banner=banner)
            sh(global_ns={}, local_ns=namespace)
            return
    sys.ps1 = '%s> ' % appid
    if readline is not None:
        readline.parse_and_bind('tab: complete')
        atexit.register(lambda: readline.write_history_file(HISTORY_PATH))
        if os.path.exists(HISTORY_PATH):
            readline.read_history_file(HISTORY_PATH)
    from code import interact
    interact(banner, local=namespace)
Пример #22
0
 def test_setup_stubs(self):
     self.mox.StubOutWithMock(remote_api_stub, 'ConfigureRemoteApi')
     remote_api_stub.ConfigureRemoteApi('app',
                                        '/',
                                        mox.IgnoreArg(),
                                        'localhost:12345',
                                        use_remote_datastore=False)
     config = runtime_config_pb2.Config()
     config.app_id = 'app'
     config.api_port = 12345
     self.mox.ReplayAll()
     runtime.setup_stubs(config)
     self.mox.VerifyAll()
Пример #23
0
def configure_remote_api():
    def auth_func():
        return ('*****@*****.**', 'pyluojtwiazmklmq')

    remote_api_stub.ConfigureRemoteApi(
        'edufocal-app',
        '/_ah/remote_api',
        auth_func,
        servername='edufocal-app.appspot.com',
        save_cookies=True,
        secure=False,
        rpc_server_factory=appengine_rpc.HttpRpcServer)
    remote_api_stub.MaybeInvokeAuthentication()
Пример #24
0
def setup_stubs(config):
    """Sets up API stubs using remote API.

  Args:
    config: a runtime_config.Config instance.
  """
    remote_api_stub.ConfigureRemoteApi(
        config.app_id,
        '/',
        lambda: ('', ''),
        '%s:%d' % (str(config.api_host), config.api_port),
        use_remote_datastore=False,
        grpc_apis=config.grpc_apis,
        grpc_proxy_port=config.python_config.grpc_proxy_port)

    if config.HasField('cloud_sql_config'):
        # Connect the RDBMS API to MySQL.
        sys.modules['google.appengine.api.rdbms'] = rdbms_mysqldb
        google.appengine.api.rdbms = rdbms_mysqldb

        connect_kwargs = dict(host=config.cloud_sql_config.mysql_host,
                              port=config.cloud_sql_config.mysql_port,
                              user=config.cloud_sql_config.mysql_user,
                              passwd=config.cloud_sql_config.mysql_password)

        if config.cloud_sql_config.mysql_socket:
            connect_kwargs[
                'unix_socket'] = config.cloud_sql_config.mysql_socket
        elif (os.name == 'posix'
              and config.cloud_sql_config.mysql_host == 'localhost'):
            # From http://dev.mysql.com/doc/refman/5.0/en/connecting.html:
            # "On Unix, MySQL programs treat the host name localhost specially,
            # in a way that is likely different from what you expect compared to
            # other network-based programs. For connections to localhost, MySQL
            # programs attempt to connect to the local server by using a Unix socket
            # file. This occurs even if a --port or -P option is given to specify a
            # port number."
            #
            # This logic is duplicated in rdbms_mysqldb.connect but FindUnixSocket
            # will not worked in devappserver2 when rdbms_mysqldb.connect is called
            # because os.access is replaced in the sandboxed environment.
            #
            # A warning is not logged if FindUnixSocket returns None because it would
            # appear for all users, not just those who call connect.
            socket = rdbms_mysqldb.FindUnixSocket()
            # Don't set socket to None or the mysql driver will blow up with a
            # TypeError. This way it will raise a nicer connection error message.
            if socket is not None:
                connect_kwargs['unix_socket'] = socket

        rdbms_mysqldb.SetConnectKwargs(**connect_kwargs)
Пример #25
0
def main(argv):
  parser = optparse.OptionParser(usage=__doc__)
  parser.add_option('-s', '--server', dest='server',
                    help='The hostname your app is deployed on. '
                         'Defaults to <app_id>.appspot.com.')
  parser.add_option('-p', '--path', dest='path',
                    help='The path on the server to the remote_api handler. '
                         'Defaults to %s.' % DEFAULT_PATH)
  parser.add_option('--secure', dest='secure', action="store_true",
                    default=False, help='Use HTTPS when communicating '
                                        'with the server.')
  (options, args) = parser.parse_args()

  if ((not options.server and not args) or len(args) > 2
      or (options.path and len(args) > 1)):
    parser.print_usage(sys.stderr)
    if len(args) > 2:
      print >> sys.stderr, 'Unexpected arguments: %s' % args[2:]
    elif options.path and len(args) > 1:
      print >> sys.stderr, 'Path specified twice.'
    sys.exit(1)

  servername = options.server
  appid = None
  path = options.path or DEFAULT_PATH
  if args:
    if servername:
      appid = args[0]
    else:
      servername = '%s.appspot.com' % args[0]
    if len(args) == 2:
      path = args[1]

  remote_api_stub.ConfigureRemoteApi(appid, path, auth_func,
                                     servername=servername,
                                     save_cookies=True, secure=options.secure)
  remote_api_stub.MaybeInvokeAuthentication()

  os.environ['SERVER_SOFTWARE'] = 'Development (remote_api_shell)/1.0'

  if not appid:
    appid = os.environ['APPLICATION_ID']
  sys.ps1 = '%s> ' % appid
  if readline is not None:
    readline.parse_and_bind('tab: complete')
    atexit.register(lambda: readline.write_history_file(HISTORY_PATH))
    if os.path.exists(HISTORY_PATH):
      readline.read_history_file(HISTORY_PATH)

  code.interact(banner=BANNER, local=globals())
Пример #26
0
 def establish(self):
     """Establishes the environment for RPC execution."""
     try:
         remote_api_stub.ConfigureRemoteApi(
             self._get_internal_application_id(),
             self._path,
             self._get_auth_func(),
             servername=self._server,
             save_cookies=True,
             secure=self._get_secure(),
             rpc_server_factory=appengine_rpc.HttpRpcServer)
         remote_api_stub.MaybeInvokeAuthentication()
     except AttributeError:
         raise EnvironmentAuthenticationError
def remote_api_shell(servername,
                     appid,
                     path,
                     secure,
                     rpc_server_factory,
                     oauth2=False):
    """Actually run the remote_api_shell."""

    if oauth2:
        remote_api_stub.ConfigureRemoteApiForOAuth(servername,
                                                   path,
                                                   secure=secure,
                                                   app_id=appid)
    else:
        remote_api_stub.ConfigureRemoteApi(
            appid,
            path,
            auth_func,
            servername=servername,
            save_cookies=True,
            secure=secure,
            rpc_server_factory=rpc_server_factory)
    remote_api_stub.MaybeInvokeAuthentication()

    os.environ['SERVER_SOFTWARE'] = 'Development (remote_api_shell)/1.0'

    if not appid:

        appid = os.environ['APPLICATION_ID']
    sys.ps1 = '%s> ' % appid
    if readline is not None:

        readline.parse_and_bind('tab: complete')
        atexit.register(lambda: readline.write_history_file(HISTORY_PATH))
        if os.path.exists(HISTORY_PATH):
            readline.read_history_file(HISTORY_PATH)

    if '' not in sys.path:
        sys.path.insert(0, '')

    preimported_locals = {
        'memcache': memcache,
        'urlfetch': urlfetch,
        'users': users,
        'db': db,
        'ndb': ndb,
    }

    code.interact(banner=BANNER, local=preimported_locals)
Пример #28
0
def configure_remote_api(hostport, path, secure, server_type):
    if server_type == 'appengine':
        remote_api_stub.ConfigureRemoteApiForOAuth(hostport,
                                                   path,
                                                   secure=secure,
                                                   auth_tries=1)
    elif server_type == 'local':
        # It seems local dev_appserver doesn't support remote API with OAuth.
        remote_api_stub.ConfigureRemoteApi(None,
                                           path,
                                           lambda: ('*****@*****.**', None),
                                           hostport,
                                           secure=secure)
    else:
        raise Exception('Unknown --server_type: %r' % server_type)
Пример #29
0
def remote_api_shell(servername,
                     appid,
                     path,
                     secure,
                     rpc_server_factory,
                     email=None,
                     password=None,
                     ipython=True):
    """Actually run the remote_api_shell."""
    auth = partial(auth_func, email=email, password=password)
    remote_api_stub.ConfigureRemoteApi(appid,
                                       path,
                                       auth,
                                       servername=servername,
                                       save_cookies=True,
                                       secure=secure,
                                       rpc_server_factory=rpc_server_factory)
    remote_api_stub.MaybeInvokeAuthentication()

    os.environ['SERVER_SOFTWARE'] = 'Development (remote_api_shell)/1.0'

    if not appid:
        appid = os.environ['APPLICATION_ID']
    sys.ps1 = '%s> ' % appid
    if readline is not None:

        readline.parse_and_bind('tab: complete')
        atexit.register(lambda: readline.write_history_file(HISTORY_PATH))
        if os.path.exists(HISTORY_PATH):
            readline.read_history_file(HISTORY_PATH)

    if '' not in sys.path:
        sys.path.insert(0, '')

    preimported_locals = {
        'memcache': memcache,
        'urlfetch': urlfetch,
        'users': users,
        'db': db,
        'ndb': ndb,
    }

    if ipython and TerminalInteractiveShell:
        ishell = TerminalInteractiveShell(banner1=BANNER,
                                          user_ns=preimported_locals)
        ishell.mainloop()
    else:
        code.interact(banner=BANNER, local=preimported_locals)
Пример #30
0
def stub():
    """Do all the function-stubbing we need to do."""
    # Most important: make sure we can talk to the dev-appserver.
    remote_api_stub.ConfigureRemoteApi(
        None,
        '/_ah/remote_api',
        auth_func=(lambda: ('test', 'test')),  # username/password
        servername=handler_test_utils.appserver_url[len('http://'):])
    os.environ['SERVER_SOFTWARE'] = 'Development (remote-api)/1.0'

    # We want to do 'deferred' tasks immediately.
    def fake_defer(fn, *fn_args, **defer_kwargs):
        """fn_args are for fn, defer_kwargs are for deferred.defer."""
        fn(*fn_args)

    deferred.defer = fake_defer