def getProfesores(self, unused_request):
        '''
        Devuelve una lista con todos los profesores registrados en el sistema, de forma simplificada (solo nombre y DNI)

        Llamada desde terminal:
        curl -X GET localhost:8001/_ah/api/helloworld/v1/profesores/getProfesores
        Llamada desde JavaScript:
        response =service.profesores.getProfesores().execute()
        '''
        #Identificación del módulo en el que estamos.
        module = modules.get_current_module_name()
        instance = modules.get_current_instance_id()

        #Leclear decimos a que microservicio queremos conectarnos (solo usando el nombre del mismo), GAE descubre su URL solo.
        url = "http://%s/" % modules.get_hostname(module="microservicio1")
        #Añadimos el recurso al que queremos conectarnos.
        url+="profesores"
        if v:
            print str(url)
        #Al no especificar nada se llama al método GET de la URL.
        result = urlfetch.fetch(url)
        if v:
            print result.content
        listaProfesores = jsonpickle.decode(result.content)

        #Creamos un vector
        profesoresItems= []
        #Que rellenamos con todo los profesores de la listaProfesores
        for profesore in listaProfesores:
            profesoresItems.append(Profesor( nombre=str(alumno.get('nombre')), dni=str(alumno.get('dni'))  ))

        #Los adaptamos al tipo de mensaje y enviamos
        #return Greeting(message=str(result.content))
        return ListaAlumnos(alumnos=alumnosItems)
def update_entities(kind, entity_id):

    """
    Data Base micro Service Resource connector, to update all kind of entities in this mService.
    More details in tdbms.

    :param kind: Type of element to modify.
    :param entity_id: Id of entity to modify.
    :param payload:

        A json dict with any elements to change.

    :return: The element modified or error status code if any problem.

    Exampe of use:
     # curl -H "Content-Type: application/json" -X PUT -d '{ "name": "nameModified", "surname": "surnameModified"} ' localhost:8001/entities/teacher/1

    """

    response = requests.put(url='http://' + str(modules.get_hostname(module='tdbms')) + '/entities/' + str(kind) + '/' + str(entity_id),
                            json=request.get_json())

    response = make_response(response.content, response.status_code)
    response.headers['Access-Control-Allow-Origin'] = "*"
    return response
Ejemplo n.º 3
0
def _StartBackendSearchCall(mr,
                            query_project_names,
                            shard_key,
                            invalidation_timestep,
                            deadline=None,
                            failfast=True):
    """Ask a backend to query one shard of the database."""
    shard_id, subquery = shard_key
    backend_host = modules.get_hostname(module='besearch')
    url = 'http://%s%s' % (backend_host,
                           framework_helpers.FormatURL(
                               mr,
                               urls.BACKEND_SEARCH,
                               projects=','.join(query_project_names),
                               q=subquery,
                               start=0,
                               num=mr.start + mr.num,
                               logged_in_user_id=mr.auth.user_id or 0,
                               me_user_id=mr.me_user_id,
                               shard_id=shard_id,
                               invalidation_timestep=invalidation_timestep))
    logging.info('\n\nCalling backend: %s', url)
    rpc = urlfetch.create_rpc(deadline=deadline or settings.backend_deadline)
    headers = _MakeBackendRequestHeaders(failfast)
    # follow_redirects=False is needed to avoid a login screen on googleplex.
    urlfetch.make_fetch_call(rpc, url, follow_redirects=False, headers=headers)
    return rpc
Ejemplo n.º 4
0
    def get(self):

        params = {
            'decimalLatitude': self.request.get('decimalLatitude'),
            'decimalLongitude': self.request.get('decimalLongitude'),
            'countryCode': self.request.get('countryCode'),
            'scientificName': self.request.get('scientificName')
        }

        data = urlencode(params)

        urlfetch.set_default_fetch_deadline(URLFETCH_DEADLINE)

        url = "http://"+modules.get_hostname(module=MODULE)+"/geospatial/singlerecord"
        result = urlfetch.fetch(
            url=url,
            payload=data,
            method=urlfetch.POST,
            headers={"Content-Type":"application/x-www-form-urlencoded"}
        )

        fl = ast.literal_eval(result.content)
        params['flags'] = fl

        self.response.headers["Access-Control-Allow-Origin"] = "*"
        self.response.headers["Access-Control-Allow-Headers"] = "content-type"
        self.response.headers['Content-Type'] = 'application/json'
        self.response.out.write(json.dumps(params))
        return
Ejemplo n.º 5
0
def get_item_from_tdbms(kind, id, params):
    """
    Call to TDBmS to get info about a specific item.

    :param kind: Object kind in TDBmS
    :param id: Integer that identify the item there.
    :param params: Attributes that we want receive from service.
    :return: A dict with all info required.
    """

    url = 'http://{}/{}/{}'.format(modules.get_hostname(module='tdbms'),
                                   'entities/' + kind, id)

    if params:
        url += '?params='
        for param in params:
            url += param + ','
    url = url[:-1]

    time_before = datetime.datetime.now()
    response = requests.get(url)
    time_after = datetime.datetime.now()

    info = {
        'url': url,
        'time': '{} sec'.format((time_after - time_before).total_seconds())
    }

    status = response.status_code

    if status == 200:
        return json.loads(response.content)
    else:
        return status
def get_entities(kind, entity_id=None):
    """
    Data Base micro Service Resource connector, to get info about all kind of entities in this mService.

    :param kind: Type of entity to get info.
    :param entity_id:
    :return: Exactly the response which is received from service.

    Example of use:

         curl -i -X GET localhost:8001/entities/teacher

    See more info in dbms_apy.py
    """


    url = 'http://' + str(modules.get_hostname(module='tdbms')) + '/' + 'entities/' + str(kind)
    if entity_id is not None:
        url += '/' + str(entity_id)

    params = request.args.get('params', None)
    if params != None:
        print params
        url += '?params='+str(params)

    response = requests.get(url)
    response = make_response(response.content, response.status_code)
    response.headers['Access-Control-Allow-Origin'] = "*"
    return response
    def get(cls, service, resource, id=None, args=None):
        """
        Do a GET request over a micro service in the backend using the params given.

        :param service: The name of the service (used for google services auto discovering).
        :param resource: The url segment of the service.
        :param id: The id of the request item.
        :param args: Args to put in the url (?paramA=<>&...)
        :return: Exactly the same response of the service.
        """

        url = 'http://{}/{}'.format(modules.get_hostname(module=service), resource)

        if id:
            url += '/{}'.format(id)

        if args:
            url += '?'
            for arg in args:
                url += '{}={}&'.format(arg, args.get(arg))
            url = url[:-1]

        response = requests.get(url, timeout=10)
        response.headers['Access-Control-Allow-Origin'] = "*"
        return make_response(response.content, response.status_code)
Ejemplo n.º 8
0
    def get(self):
        email_address = self.request.get("email_address")
        if not mail.is_email_valid(email_address):
            self.response.write('invalid email address')
            self.response.status = 400
            return
        confirm_id = str(uuid.uuid4().get_hex().upper()[0:6])
        confirmation_url = 'http://' + modules.get_hostname(
        ) + '/news/confirm?confirm_id=' + confirm_id
        subject = "Confirm your subscription"
        body = """Thank you for subscribing to splunk-sizing.appspot.com!

Please confirm your email address by clicking on the link below:

%s
""" % confirmation_url
        subscription = Subscription.get_or_insert(email_address)
        if subscription.confirmed:
            self.response.write('already confirmed')
            self.response.status = 400
            return
        subscription.confirm_date = None
        subscription.confirm_id = confirm_id
        subscription.put()
        mail.send_mail(sender_address, email_address, subject, body)
Ejemplo n.º 9
0
def invite_send():
    """Sends an email to invite the user at the email address given."""
    name = request.values.get('displayname')
    person_obj = model.Person.find_or_create_by_name(name)
    url = ''.join([
        'http://',
        modules.get_hostname(version=modules.get_current_version_name()),
        '/register/',
        person_obj.key.urlsafe()
    ])
    email = request.values.get('email')
    message = request.values.get('message')
    sender = 'invite@' + app_identity.get_application_id() + ".appspotmail.com"
    logging.debug(sender)
    logging.debug(url)
    # logging.debug(render_template("invite_message.txt", join_url=url, personal_message=message))
    mail.send_mail(sender=sender,
                   to=email,
                   subject="You have been invited to a Book Club!",
                   bcc='*****@*****.**',
                   body=render_template("invite_message.txt",
                                        join_url=url,
                                        personal_message=message))
    flash("Email sent to %s" % email)
    return redirect(url_for('admin.invite_form'))
Ejemplo n.º 10
0
def get_movies():
    movie_service_url = modules.get_hostname(module='movie')
    movie_movies_url = 'http://' + movie_service_url + '/movies/'

    response = ""

    try:
        result = urlfetch.fetch(movie_movies_url)

        if result.status_code == 200:
            movies = json.loads(result.content)

            response += 'Got {} movies from {}'.format(len(movies),
                                                       movie_movies_url)
            response += '<br/>-----<br />'
            response += ''.join([format_movie(movie) for movie in movies])
        else:
            response += 'Could not fetch movies from {}.<br/>'.format(
                movie_movies_url)
            response += 'Got response code {}.'.format(result.status_code)

    except Exception as e:
        response += 'Could not fetch movies from {}'.format(movie_movies_url)
        response += '<br/>'
        response += str(e)

    return response
Ejemplo n.º 11
0
    def post(self):
        x = self.request.get('x')

        if (x == ''):
            self.redirect('/%s' % modules.get_current_module_name())

        form_fields = {
            'x' : x
        }
        url = "http://%s/sqrt/" % modules.get_hostname(module="webmath")

        form_data = urllib.urlencode(form_fields)
        result = urlfetch.fetch(url=url,
                                payload = form_data,
                                method = urlfetch.POST,
                                headers={'Content-Type': 'application/x-www-form-urlencoded'})
        if (result.status_code == 200) :
            squareroot = result.content
        else:
            squareroot = result.status_code

        template_values = {
            'x': x,
            'result': squareroot
        }
        self.render('result', template_values)
Ejemplo n.º 12
0
  def archive(self):

    archiver_host = modules.get_hostname(module="zipper")

    url = 'http://%s/archive?%s' % (archiver_host, self.request.query_string)
    logging.info('dispatching to archiver at: %s', url)
    result = urlfetch.fetch(url, deadline=60)
    return result.content
Ejemplo n.º 13
0
    def insertar_alumno(self, request):

        print "POST EN CLOUDPOINTS"
        #La capacidad de recoger datos desde request vendrá dada por tipo de
        #objeto que se espera como petición, en este caso podrán obtenerse
        #todos los atributos que se hayan definido en AlumnoCompleto

        if v:
            print "Contenido de petición a insertar"
            print str(request)

        #Si no tenemos todos los atributos entonces enviamos un error de bad request.
        if request.nombre == None or request.dni == None or request.direccion == None or request.localidad == None or request.provincia == None or request.fecha_nac == None or request.telefono == None:
            raise endpoints.BadRequestException(
                'Peticion erronea, faltan datos.')

        #Conformamos la dirección:
        url = "http://%s/" % modules.get_hostname(module="microservicio1")
        #Añadimos el servicio al que queremos conectarnos.
        url += "alumnos"

        print url

        from google.appengine.api import urlfetch
        import urllib

        #Si algun dato no es pasado se introduce None

        #Extraemos lo datos de la petición al endpoints
        form_fields = {
            "nombre": request.nombre,
            "dni": request.dni,
            "direccion": request.direccion,
            "localidad": request.localidad,
            "provincia": request.provincia,
            "fecha_nac": request.fecha_nac,
            "telefono": request.telefono
        }

        ##Doc de urlfetch: https://cloud.google.com/appengine/docs/python/refdocs/google.appengine.api.urlfetch
        form_data = urllib.urlencode(form_fields)
        #Realizamos la petición al servicio con los datos pasados al endpoint
        result = urlfetch.fetch(url=url,
                                payload=form_data,
                                method=urlfetch.POST)

        if v:
            print "RESULTADOS DE PETICION AL M1: "
            print result.content
            print result.status_code

        if str(result.status_code) == '404':
            raise endpoints.NotFoundException(
                'Alumno con DNI %s ya existe en el sistema.' % (request.dni))

        #return MensajeRespuesta(message="Todo OK man!")
        #Mandamos la respuesta que nos devuelve la llamada al microservicio:
        return MensajeRespuesta(message=result.content)
Ejemplo n.º 14
0
 def get(self):
     # [START access_another_module]
     backend_hostname = modules.get_hostname(module='my-backend')
     url = "http://{}/".format(backend_hostname)
     try:
         result = urllib2.urlopen(url).read()
         self.response.write('Got response {}'.format(result))
     except urllib2.URLError:
         pass
Ejemplo n.º 15
0
def postProfesor():
    '''
    Método que inserta un nuevo profesor en el sistema.
    curl -d "nombre=Juan&apellidos=Bartlo&dni=46666&direccion=Calle arabl&localidad=Jerez de la fronta&provincia=Granada&fecha_nacimiento=1988-2-6&telefono=137631" -i -X POST localhost:8002/profesores


    '''
    if v:
        print nombreMicroservicio
        print " Calling postProfesor()"
        print " "+str(request.form)

    salida = GestorProfesores.nuevoProfesor(request.form['nombre'],
                              request.form['apellidos'],
                              request.form['dni'],
                              request.form['direccion'],
                              request.form['localidad'],
                              request.form['provincia'],
                              request.form['fecha_nacimiento'],
                              request.form['telefono'],
                              )


    #Una vez creado el profesor añadimos sus crendenciales de acceso al sistema básicas
    if salida['status']=='OK':
        print ' Profesor creado con éxito. Creando sus credenciales de acceso al sistema.'
        #Creamos las credenciales del usuario en la tabla credenciales usando el id del usuario que devuelve nuevoProfesor
        #Por defecto el alias y el password de un profesor en el sistemas serán su dni
        #salida Creacion Credenciales
        salidaCC=GestorCredenciales.postCredenciales(salida['idProfesor'], request.form['nombre'], request.form['dni'], request.form['dni'], 'admin')
        if salidaCC != 'OK':
            salida['status']='SBD ERROR'


        #Una vez creadas las credenciales llamamos al servicio SCE para que actualice su sistema (### DISPARADOR ###)

        #Conformamos la dirección:
        module = modules.get_current_module_name()
        url = "http://%s/" % modules.get_hostname(module="sce")
        #Añadimos el servicio al que queremos conectarnos.
        url+="profesores"

        #Creamos un diccionario con los datos.
        datos = {
          "idProfesor": salida['idProfesor'],
          "nombreProfesor": request.form['nombre']+' '+request.form['apellidos'],
        }
        form_data = urllib.urlencode(datos)
        result=urlfetch.fetch(url=url, payload=form_data, method=urlfetch.POST)
        json = jsonpickle.decode(result.content)
        if json['status']!='OK':
            salida['status']='SCE ERROR'

    if v:
        print ' Return: '+str(salida)

    return jsonpickle.encode(salida)
    def testStartBackendNonviewableCall(self):
        self.mox.StubOutWithMock(urlfetch, 'create_rpc')
        self.mox.StubOutWithMock(urlfetch, 'make_fetch_call')
        self.mox.StubOutWithMock(modules, 'get_hostname')
        a_fake_rpc = testing_helpers.Blank(callback=None)
        urlfetch.create_rpc(
            deadline=settings.backend_deadline).AndReturn(a_fake_rpc)
        modules.get_hostname(module='besearch')
        urlfetch.make_fetch_call(a_fake_rpc,
                                 mox.StrContains(urls.BACKEND_NONVIEWABLE),
                                 follow_redirects=False,
                                 headers=mox.IsA(dict))
        self.mox.ReplayAll()

        processed_invalidations_up_to = 12345
        frontendsearchpipeline._StartBackendNonviewableCall(
            789, 111L, 2, processed_invalidations_up_to)
        self.mox.VerifyAll()
Ejemplo n.º 17
0
 def get(self):
     # [START access_another_module]
     backend_hostname = modules.get_hostname(module='my-backend')
     url = "http://{}/".format(backend_hostname)
     try:
         result = urllib2.urlopen(url).read()
         self.response.write('Got response {}'.format(result))
     except urllib2.URLError:
         pass
Ejemplo n.º 18
0
def get_custom_hostname():
    """
    hostname = self.request.host  - doesn't work for cron tasks.
    and get_default_version_hostname() returns 1.default.appbfw.appspot.com - which is no good either.
    """
    hostname = modules.get_hostname()
    if u'appspot.com' in hostname:  # woops!
        logging.warning('get_custom_hostname() - updating custom hostname from %s', hostname)
        hostname = u'www.bunjilforestwatch.net'
    return hostname
    def insertar_alumno(self, request):

        print "POST EN CLOUDPOINTS"
        #La capacidad de recoger datos desde request vendrá dada por tipo de
        #objeto que se espera como petición, en este caso podrán obtenerse
        #todos los atributos que se hayan definido en AlumnoCompleto

        if v:
            print "Contenido de petición a insertar"
            print str(request)

        #Si no tenemos todos los atributos entonces enviamos un error de bad request.
        if request.nombre==None or request.dni==None or request.direccion==None or request.localidad==None or request.provincia==None or request.fecha_nac==None or request.telefono==None:
            raise endpoints.BadRequestException('Peticion erronea, faltan datos.')

        #Conformamos la dirección:
        url = "http://%s/" % modules.get_hostname(module="microservicio1")
        #Añadimos el servicio al que queremos conectarnos.
        url+="alumnos"

        print url

        from google.appengine.api import urlfetch
        import urllib

        #Si algun dato no es pasado se introduce None

        #Extraemos lo datos de la petición al endpoints
        form_fields = {
          "nombre": request.nombre,
          "dni": request.dni,
          "direccion": request.direccion,
          "localidad": request.localidad,
          "provincia": request.provincia,
          "fecha_nac": request.fecha_nac,
          "telefono": request.telefono
        }

        ##Doc de urlfetch: https://cloud.google.com/appengine/docs/python/refdocs/google.appengine.api.urlfetch
        form_data = urllib.urlencode(form_fields)
        #Realizamos la petición al servicio con los datos pasados al endpoint
        result = urlfetch.fetch(url=url, payload=form_data, method=urlfetch.POST)


        if v:
            print "RESULTADOS DE PETICION AL M1: "
            print result.content
            print result.status_code

        if str(result.status_code) == '404':
            raise endpoints.NotFoundException('Alumno con DNI %s ya existe en el sistema.' % (request.dni))

        #return MensajeRespuesta(message="Todo OK man!")
        #Mandamos la respuesta que nos devuelve la llamada al microservicio:
        return MensajeRespuesta(message=result.content)
Ejemplo n.º 20
0
def get_login_module_base_url(current_scheme='https'):
  host_name = modules.get_hostname(module=app_globals.login_module['name'])
  scheme = app_globals.login_module.get('protocol', None)
  scheme = scheme and scheme or current_scheme
  base_url = re.match(r"[\w\-]*\.(.*)(?=(\.[\w\-]*\.\w*$))", host_name)
  if base_url:
    base_url = base_url.groups()
    base_url = (scheme == 'https' and base_url[0].replace('.', '-dot-') or base_url[0]) + base_url[1]
  else:
    base_url = host_name
  return scheme + '://' + base_url
Ejemplo n.º 21
0
 def GetModuleUrl(self, module=None, url=None):
   """Get the url for the current page but on the given module."""
   url_parts = list(urlparse.urlsplit(url or self.request.url))
   url_parts[1] = modules.get_hostname(module=module)
   # If we're on https we need to replace version.backend.datapipeline
   # with version-dot-backend-dot-datapipeline
   if url_parts[0] == 'https':
     hostname_parts = url_parts[1].rsplit('.', 2)
     hostname_parts[0] = hostname_parts[0].replace('.', '-dot-')
     url_parts[1] = '.'.join(hostname_parts)
   return str(urlparse.urlunsplit(url_parts))
    def testStartBackendSearchCall(self):
        self.mox.StubOutWithMock(urlfetch, 'create_rpc')
        self.mox.StubOutWithMock(urlfetch, 'make_fetch_call')
        self.mox.StubOutWithMock(modules, 'get_hostname')
        a_fake_rpc = testing_helpers.Blank(callback=None)
        urlfetch.create_rpc(
            deadline=settings.backend_deadline).AndReturn(a_fake_rpc)
        modules.get_hostname(module='besearch')
        urlfetch.make_fetch_call(a_fake_rpc,
                                 mox.StrContains(urls.BACKEND_SEARCH),
                                 follow_redirects=False,
                                 headers=mox.IsA(dict))
        self.mox.ReplayAll()

        processed_invalidations_up_to = 12345
        mr = testing_helpers.MakeMonorailRequest(
            path='/p/proj/issues/list?q=foo')
        mr.me_user_id = 111L
        frontendsearchpipeline._StartBackendSearchCall(
            mr, ['proj'], (2, 'priority=high'), processed_invalidations_up_to)
        self.mox.VerifyAll()
def test():
    """
     Test resource.

    :return:

     Example of use:
        curl -i -X GET localhost:8001/test
    """

    response = requests.get("http://%s/test" % modules.get_hostname(module='tdbms'))
    return make_response(response.content, response.status_code)
Ejemplo n.º 24
0
def get_custom_hostname():
    """
    hostname = self.request.host  - doesn't work for cron tasks.
    and get_default_version_hostname() returns 1.default.appbfw.appspot.com - which is no good either.
    """
    hostname = modules.get_hostname()
    if u'appspot.com' in hostname:  # woops!
        logging.warning(
            'get_custom_hostname() - updating custom hostname from %s',
            hostname)
        hostname = u'www.bunjilforestwatch.net'
    return hostname
    def delete(cls, service, resource, id):
        """
        Do a DELETE request over a micro service in the backend using the params given.

        :param service: The name of the service (used for google services auto discovering).
        :param resource: The url segment of the service.
        :param id: The id of the request item.
        :return: Exactly the same response of the service.
        """

        response = requests.delete('http://{}/{}/{}'.format(modules.get_hostname(module=service), resource, id))
        response.headers['Access-Control-Allow-Origin'] = "*"
        return  make_response(response.content, response.status_code)
    def post(cls, service, resource, json):
        """
        Do a POST request over a micro service in the backend using the params given.

        :param service: The name of the service (used for google services auto discovering).
        :param resource: The url segment of the service.
        :param json: The payload where are the data to put in a dict format.
        :return: Exactly the same response of the service.
        """

        response = requests.post(url='http://{}/{}'.format(modules.get_hostname(module=service), resource), json=json)
        response.headers['Access-Control-Allow-Origin'] = "*"
        return make_response(response.content, response.status_code)
Ejemplo n.º 27
0
def _CreateRequestURL(module, path):
    """Composes the appropriate request URL for a given AppEngine module.

  Exists primarily for easier unit testing.

  Args:
    module: The name of the AppEngine module.
    path: The path portion of the URL.

  Returns:
    A fully-composed request URL.
  """
    parts = ('https', modules.get_hostname(module=module), path, '', '')
    return urlparse.urlunsplit(parts)
Ejemplo n.º 28
0
def get_versioned_hosturl():
    """Returns the url hostname of this instance locked to the currently running
  version.

  This function hides the fact that app_identity.get_default_version_hostname()
  returns None on the dev server and modules.get_hostname() returns incorrectly
  qualified hostname for HTTPS usage on the prod server. <3
  """
    if is_local_dev_server():
        # TODO(maruel): It'd be nice if it were easier to use a ephemeral SSL
        # certificate here and not assume unsecured connection.
        return "http://" + modules.get_hostname()

    return "https://%s-dot-%s" % (get_app_version(), app_identity.get_default_version_hostname())
Ejemplo n.º 29
0
def get_versioned_hosturl():
  """Returns the url hostname of this instance locked to the currently running
  version.

  This function hides the fact that app_identity.get_default_version_hostname()
  returns None on the dev server and modules.get_hostname() returns incorrectly
  qualified hostname for HTTPS usage on the prod server. <3
  """
  if is_local_dev_server():
    # TODO(maruel): It'd be nice if it were easier to use a ephemeral SSL
    # certificate here and not assume unsecured connection.
    return 'http://' + modules.get_hostname()

  return 'https://%s-dot-%s' % (
      get_app_version(), app_identity.get_default_version_hostname())
    def getAlumno(self,request):
        print "GET CON PARÁMETROS EN ENDPOINT"

        #Cuando se llama a este recurso lo que se quiere es recibir toda la información
        #de una entidad Alumno, para ello primero vamos a recuperar la información del microsrevicio apropiado:

        #Conexión a un microservicio específico:
        module = modules.get_current_module_name()
        instance = modules.get_current_instance_id()

        #Le decimos al microservicio que queremos conectarnos (solo usando el nombre del mismo), GAE descubre su URL solo.
        url = "http://%s/" % modules.get_hostname(module="microservicio1")

        '''
        Según la doc. de urlfetch (ver arriba) no podemos pasar parámetros con el payload, así que como conocemos
        la api del microservicios al que vamos a llamr realizamos la petición bajo su especificacion, según la cual
        solo tenemos que llamar a /alumnos/<id_alumno> entonces concatenamos a la url esa id qu recibimos en la llamada
        a este procedimiento.
        '''
        #Recursos más entidad
        url+='alumnos/'+request.dni

        if v:
            print "calling: "+ url

        #Petición al microservicio
        result = urlfetch.fetch(url=url, method=urlfetch.GET)

        print "RESULTADO:"+str(result.status_code)
        #print result.content
        if v:
            print result.status_code
        if str(result.status_code) == '400':
            raise endpoints.BadRequestException('Peticion erronea')

        if str(result.status_code) == '404':
            raise endpoints.NotFoundException('Alumno con DNI %s no encontrado.' % (request.dni))

        alumno = jsonpickle.decode(result.content)

        return AlumnoCompleto(nombre=alumno.get('nombre'),
                                 dni=alumno.get('dni'),
                                 direccion=alumno.get('direccion'),
                                 localidad=alumno.get('localidad'),
                                 provincia=alumno.get('provincia'),
                                 fecha_nac=str(alumno.get('fecha_nac')),
                                 telefono=alumno.get('telefono')
                                )
 def getAsignaturasAlumno(self, request):
     if v:
         print ("Ejecución de getAsignaturasAlumno en apigateway")
     module = modules.get_current_module_name()
     instance = modules.get_current_instance_id()
     url = "http://%s/" % modules.get_hostname(module="microservicio1")
     url+='alumnos/'+request.dni+"/asignaturas"
     result = urlfetch.fetch(url)
     if v:
         print result.content
     listaAsignaturas = jsonpickle.decode(result.content)
     print listaAsignaturas
     asignaturasItems= []
     for asignatura in listaAsignaturas:
         asignaturasItems.append( Asignatura( id=str(asignatura.get('id')), nombre=str(asignatura.get('nombre')) ) )
     return ListaAsignaturas(asignaturas=asignaturasItems)
Ejemplo n.º 32
0
def _get_dev2_hostname(backend, instance=None):
    """Returns the hostname of a backend [instance] in devappserver2.

  Args:
    backend: The name of the backend.
    instance: The backend instance number, in [0, instances-1].

  Returns:
    The hostname of the backend.
  """
    try:
        return modules.get_hostname(module=backend, instance=instance)
    except modules.InvalidModuleError:
        raise InvalidBackendError()
    except modules.InvalidInstancesError:
        raise InvalidInstanceError()
Ejemplo n.º 33
0
def _get_dev2_hostname(backend, instance=None):
    """Returns the hostname of a backend [instance] in devappserver2.

  Args:
    backend: The name of the backend.
    instance: The backend instance number, in [0, instances-1].

  Returns:
    The hostname of the backend.
  """
    try:
        return modules.get_hostname(module=backend, instance=instance)
    except modules.InvalidModuleError:
        raise InvalidBackendError()
    except modules.InvalidInstancesError:
        raise InvalidInstanceError()
 def getCursosAlumno(self, request):
     if v:
         print ("Ejecución de getCursosAlumno en apigateway")
     module = modules.get_current_module_name()
     instance = modules.get_current_instance_id()
     url = "http://%s/" % modules.get_hostname(module="microservicio1")
     url+='alumnos/'+request.dni+"/cursos"
     result = urlfetch.fetch(url)
     if v:
         print result.content
     listaCursos = jsonpickle.decode(result.content)
     print listaCursos
     cursosItems= []
     for curso in listaCursos:
         cursosItems.append(Curso(id=str(curso.get('id')),curso=str(curso.get('nombre')),grupo=str(curso.get('grupo')),nivel=str(curso.get('nivel'))))
     return ListaCursos(cursos=cursosItems)
Ejemplo n.º 35
0
    def getAlumno(self, request):
        print "GET CON PARÁMETROS EN ENDPOINT"

        #Cuando se llama a este recurso lo que se quiere es recibir toda la información
        #de una entidad Alumno, para ello primero vamos a recuperar la información del microsrevicio apropiado:

        #Conexión a un microservicio específico:
        module = modules.get_current_module_name()
        instance = modules.get_current_instance_id()

        #Le decimos al microservicio que queremos conectarnos (solo usando el nombre del mismo), GAE descubre su URL solo.
        url = "http://%s/" % modules.get_hostname(module="microservicio1")
        '''
        Según la doc. de urlfetch (ver arriba) no podemos pasar parámetros con el payload, así que como conocemos
        la api del microservicios al que vamos a llamr realizamos la petición bajo su especificacion, según la cual
        solo tenemos que llamar a /alumnos/<id_alumno> entonces concatenamos a la url esa id qu recibimos en la llamada
        a este procedimiento.
        '''
        #Recursos más entidad
        url += 'alumnos/' + request.dni

        if v:
            print "calling: " + url

        #Petición al microservicio
        result = urlfetch.fetch(url=url, method=urlfetch.GET)

        print "RESULTADO:" + str(result.status_code)
        #print result.content
        if v:
            print result.status_code
        if str(result.status_code) == '400':
            raise endpoints.BadRequestException('Peticion erronea')

        if str(result.status_code) == '404':
            raise endpoints.NotFoundException(
                'Alumno con DNI %s no encontrado.' % (request.dni))

        alumno = jsonpickle.decode(result.content)

        return AlumnoCompleto(nombre=alumno.get('nombre'),
                              dni=alumno.get('dni'),
                              direccion=alumno.get('direccion'),
                              localidad=alumno.get('localidad'),
                              provincia=alumno.get('provincia'),
                              fecha_nac=str(alumno.get('fecha_nac')),
                              telefono=alumno.get('telefono'))
Ejemplo n.º 36
0
    def getAlumnos(self, unused_request):
        #Transformación de la llamada al endpoints a la llamada a la api rest del servicio.

        print("Llamando a una función específica")

        #Conexión a un microservicio específico:

        module = modules.get_current_module_name()
        instance = modules.get_current_instance_id()

        #Le decimos a que microservicio queremos conectarnos (solo usando el nombre del mismo), GAE descubre su URL solo.
        url = "http://%s/" % modules.get_hostname(module="microservicio1")
        #Añadimos el recurso al que queremos conectarnos.
        url += "alumnos"
        print str(url)
        #result = urllib2.urlopen(url)
        #print result

        #Llamamos al microservicio y recibimos los resultados con URLFetch
        #Al no especificar nada se llama al método GET de la URL.
        result = urlfetch.fetch(url)

        #Vamos a intentar consumir los datos en JSON y convertirlos a un mensje enviable :)

        print "IMPRESION DE LOS DATOS RECIBIDOS"
        print result.content
        listaAlumnos = jsonpickle.decode(result.content)

        for alumno in listaAlumnos:
            print "nombre: " + str(alumno.get('nombre'))
            print "dni: " + str(alumno.get('dni'))
        '''
        miListaAlumnos=ListaAlumnos()
        miListaAlumnos.alumnos = listaAlumnos
        '''

        #Creamos un vector
        alumnosItems = []
        #Que rellenamos con todo los alumnos de la listaAlumnos
        for alumno in listaAlumnos:
            alumnosItems.append(
                Alumno(nombre=str(alumno.get('nombre')),
                       dni=str(alumno.get('dni'))))

        #Los adaptamos al tipo de mensaje y enviamos
        #return Greeting(message=str(result.content))
        return ListaAlumnos(alumnos=alumnosItems)
    def getAlumnos(self, unused_request):
        #Transformación de la llamada al endpoints a la llamada a la api rest del servicio.

        print ("Llamando a una función específica")

        #Conexión a un microservicio específico:

        module = modules.get_current_module_name()
        instance = modules.get_current_instance_id()

        #Le decimos a que microservicio queremos conectarnos (solo usando el nombre del mismo), GAE descubre su URL solo.
        url = "http://%s/" % modules.get_hostname(module="microservicio1")
        #Añadimos el recurso al que queremos conectarnos.
        url+="alumnos"
        print str(url)
        #result = urllib2.urlopen(url)
        #print result

        #Llamamos al microservicio y recibimos los resultados con URLFetch
        #Al no especificar nada se llama al método GET de la URL.
        result = urlfetch.fetch(url)

        #Vamos a intentar consumir los datos en JSON y convertirlos a un mensje enviable :)

        print "IMPRESION DE LOS DATOS RECIBIDOS"
        print result.content
        listaAlumnos = jsonpickle.decode(result.content)

        for alumno in listaAlumnos:
            print "nombre: "+str(alumno.get('nombre'))
            print "dni: "+str(alumno.get('dni'))

        '''
        miListaAlumnos=ListaAlumnos()
        miListaAlumnos.alumnos = listaAlumnos
        '''

        #Creamos un vector
        alumnosItems= []
        #Que rellenamos con todo los alumnos de la listaAlumnos
        for alumno in listaAlumnos:
            alumnosItems.append(Alumno( nombre=str(alumno.get('nombre')), dni=str(alumno.get('dni'))  ))

        #Los adaptamos al tipo de mensaje y enviamos
        #return Greeting(message=str(result.content))
        return ListaAlumnos(alumnos=alumnosItems)
def post_entity(kind):
    """
    Data Base micro Service Resource connector, put all kind of entities in this mService.

    :param kind:
    :payload json:
    :return:

     Example of use:
      curl -i -H "Content-Type: application/json" -X POST -d '{ "data": {"name": "new name"} }' localhost:8001/entities/student
      curl -i -H "Content-Type: application/json" -X POST -d '{ "data": {"course": 1, "word": "B", "level": "ESO"} }' localhost:8001/entities/class

    """
    response = requests.post(url='http://' + str(modules.get_hostname(module='tdbms')) + '/entities/' + str(kind),
                             json=request.get_json())
    response.headers['Access-Control-Allow-Origin'] = "*"
    return make_response(response.content, response.status_code)
Ejemplo n.º 39
0
def postAsignatura():
    '''
    Inserta una nueva asignatura en el sistema.
    curl -d "nombre=ComputacionZZ" -i -X POST localhost:8002/asignaturas
    '''
    #Info de seguimiento
    if v:
        print nombreMicroservicio
        print ' Recurso: /asignaturas, metodo: POST \n'
        print ' Petición '
        print request.form

    salida = GestorAsignaturas.nuevaAsignatura(
        request.form['nombre'].encode('latin-1'))

    print "Salida del Gestor"
    print salida

    if salida['status'] == 'OK':

        #Una vez insertada la asignatura en el SBD llamamos al servicio SCE para que actualice su sistema (### DISPARADOR ###)

        #Conformamos la dirección:
        module = modules.get_current_module_name()
        url = "http://%s/" % modules.get_hostname(module="sce")
        #Añadimos el servicio al que queremos conectarnos.
        url += "asignaturas"

        #Creamos un diccionario con los datos.
        datos = {
            "idAsignatura": salida['idAsignatura'],
            "nombreAsignatura": request.form['nombre'],
        }
        form_data = urllib.urlencode(datos)
        result = urlfetch.fetch(url=url,
                                payload=form_data,
                                method=urlfetch.POST)
        json = jsonpickle.decode(result.content)
        if json['status'] != 'OK':
            salida['status'] = 'SCE ERROR'

    if v:
        print ' Return: ' + str(salida)

    return jsonpickle.encode(salida)
Ejemplo n.º 40
0
 def getAsignaturasAlumno(self, request):
     if v:
         print("Ejecución de getAsignaturasAlumno en apigateway")
     module = modules.get_current_module_name()
     instance = modules.get_current_instance_id()
     url = "http://%s/" % modules.get_hostname(module="microservicio1")
     url += 'alumnos/' + request.dni + "/asignaturas"
     result = urlfetch.fetch(url)
     if v:
         print result.content
     listaAsignaturas = jsonpickle.decode(result.content)
     print listaAsignaturas
     asignaturasItems = []
     for asignatura in listaAsignaturas:
         asignaturasItems.append(
             Asignatura(id=str(asignatura.get('id')),
                        nombre=str(asignatura.get('nombre'))))
     return ListaAsignaturas(asignaturas=asignaturasItems)
Ejemplo n.º 41
0
def postClase():
    '''
    Inserta una nueva clase en el sistema.
    curl -d "curso=3&grupo=C&nivel=ESO" -i -X POST localhost:8002/clases
    '''
    salida = GestorClases.nuevaClase(request.form['curso'],
                                     request.form['grupo'],
                                     request.form['nivel'])

    if salida['status'] == 'OK':

        #Una vez insertada la asignatura en el SBD llamamos al servicio SCE para que actualice su sistema (### DISPARADOR ###)

        #Conformamos la dirección:
        module = modules.get_current_module_name()
        url = "http://%s/" % modules.get_hostname(module="sce")
        #Añadimos el servicio al que queremos conectarnos.
        url += "clases"
        #Componemos el nombre como un solo string
        nombreClase = request.form['curso'] + request.form[
            'grupo'] + request.form['nivel']
        print nombreClase
        #Creamos un diccionario con los datos.
        datos = {
            "idClase": salida['idClase'],
            "nombreClase": nombreClase,
        }
        form_data = urllib.urlencode(datos)
        result = urlfetch.fetch(url=url,
                                payload=form_data,
                                method=urlfetch.POST)
        print result.content
        json = jsonpickle.decode(result.content)

        print 'AQUIIIIIIIIIIIIIIIIIIIIII'
        print json['status']

        if json['status'] != 'OK':
            salida['status'] = 'SCE ERROR'

    if v:
        print ' Return: ' + str(salida)

    return jsonpickle.encode(salida)
    def getProfesoreAlumno(self, request):
        #Transformación de la llamada al endpoints a la llamada a la api rest del servicio.
        if v:
            print ("Ejecución de getProfesoresAlumno en apigateway")

        #Conexión a un microservicio específico:

        module = modules.get_current_module_name()
        instance = modules.get_current_instance_id()
        #Le decimos a que microservicio queremos conectarnos (solo usando el nombre del mismo), GAE descubre su URL solo.
        url = "http://%s/" % modules.get_hostname(module="microservicio1")

        #Añadimos a la url la coleccion (alumnos), el recurso (alumno dado por su dni) y el recurso anidado de este (profesores)
        url+='alumnos/'+request.dni+"/profesores"

        #Realizamos la petición
        result = urlfetch.fetch(url)

        #Vamos a intentar consumir los datos en JSON y convertirlos a un mensje enviable :)

        print "IMPRESION DE LOS DATOS RECIBIDOS"
        print result.content
        listaProfesores = jsonpickle.decode(result.content)

        #Creamos un vector
        profesoresItems= []
        #Que rellenamos con todo los alumnos de la listaAlumnos
        for profesor in listaProfesores:
            profesoresItems.append(ProfesorCompleto( nombre=str(profesor.get('nombre')),
                                           dni=str(profesor.get('dni')),
                                           direccion=str(profesor.get('direccion')),
                                           localidad=str(profesor.get('localidad')),
                                           provincia=str(profesor.get('provincia')),
                                           fecha_nac=str(profesor.get('fecha_nac')),
                                           telefonoA=str(profesor.get('telefonoA')),
                                           telefonoB=str(profesor.get('telefonoB'))
                                         )
                                )

        #Los adaptamos al tipo de mensaje y enviamos
        #return Greeting(message=str(result.content))
        return ListaProfesores(profesores=profesoresItems)
Ejemplo n.º 43
0
def postAsignatura():
    '''
    Inserta una nueva asignatura en el sistema.
    curl -d "nombre=ComputacionZZ" -i -X POST localhost:8002/asignaturas
    '''
    #Info de seguimiento
    if v:
        print nombreMicroservicio
        print ' Recurso: /asignaturas, metodo: POST \n'
        print ' Petición '
        print request.form

    salida = GestorAsignaturas.nuevaAsignatura(request.form['nombre'].encode('latin-1'))

    print "Salida del Gestor"
    print salida

    if salida['status'] == 'OK':

        #Una vez insertada la asignatura en el SBD llamamos al servicio SCE para que actualice su sistema (### DISPARADOR ###)

        #Conformamos la dirección:
        module = modules.get_current_module_name()
        url = "http://%s/" % modules.get_hostname(module="sce")
        #Añadimos el servicio al que queremos conectarnos.
        url+="asignaturas"

        #Creamos un diccionario con los datos.
        datos = {
          "idAsignatura": salida['idAsignatura'],
          "nombreAsignatura": request.form['nombre'],
        }
        form_data = urllib.urlencode(datos)
        result=urlfetch.fetch(url=url, payload=form_data, method=urlfetch.POST)
        json = jsonpickle.decode(result.content)
        if json['status']!='OK':
            salida['status']='SCE ERROR'

    if v:
        print ' Return: '+str(salida)

    return jsonpickle.encode(salida)
Ejemplo n.º 44
0
 def getCursosAlumno(self, request):
     if v:
         print("Ejecución de getCursosAlumno en apigateway")
     module = modules.get_current_module_name()
     instance = modules.get_current_instance_id()
     url = "http://%s/" % modules.get_hostname(module="microservicio1")
     url += 'alumnos/' + request.dni + "/cursos"
     result = urlfetch.fetch(url)
     if v:
         print result.content
     listaCursos = jsonpickle.decode(result.content)
     print listaCursos
     cursosItems = []
     for curso in listaCursos:
         cursosItems.append(
             Curso(id=str(curso.get('id')),
                   curso=str(curso.get('nombre')),
                   grupo=str(curso.get('grupo')),
                   nivel=str(curso.get('nivel'))))
     return ListaCursos(cursos=cursosItems)
    def put(cls, service, resource, id, json):
        """
        Do a PUT request over a micro service in the backend using the params given.

        :param service: The name of the service (used for google services auto discovering).
        :param resource: The url segment of the service.
        :param id: The id of the request item. **CAN BE NONE TO SINGLETON RESOURCES**
        :param json: The payload where are the data to put in a dict format.
        :return: Exactly the same response of the service.
        """

        # For singleton resources.
        url = 'http://{}/{}'.format(modules.get_hostname(module=service), resource)

        if id:
            url += '/{}'.format(id)

        response = requests.put(url=url, json=json)
        response.headers['Access-Control-Allow-Origin'] = "*"
        return make_response(response.content, response.status_code)
Ejemplo n.º 46
0
    def getProfesoreAlumno(self, request):
        #Transformación de la llamada al endpoints a la llamada a la api rest del servicio.
        if v:
            print("Ejecución de getProfesoresAlumno en apigateway")

        #Conexión a un microservicio específico:

        module = modules.get_current_module_name()
        instance = modules.get_current_instance_id()
        #Le decimos a que microservicio queremos conectarnos (solo usando el nombre del mismo), GAE descubre su URL solo.
        url = "http://%s/" % modules.get_hostname(module="microservicio1")

        #Añadimos a la url la coleccion (alumnos), el recurso (alumno dado por su dni) y el recurso anidado de este (profesores)
        url += 'alumnos/' + request.dni + "/profesores"

        #Realizamos la petición
        result = urlfetch.fetch(url)

        #Vamos a intentar consumir los datos en JSON y convertirlos a un mensje enviable :)

        print "IMPRESION DE LOS DATOS RECIBIDOS"
        print result.content
        listaProfesores = jsonpickle.decode(result.content)

        #Creamos un vector
        profesoresItems = []
        #Que rellenamos con todo los alumnos de la listaAlumnos
        for profesor in listaProfesores:
            profesoresItems.append(
                ProfesorCompleto(nombre=str(profesor.get('nombre')),
                                 dni=str(profesor.get('dni')),
                                 direccion=str(profesor.get('direccion')),
                                 localidad=str(profesor.get('localidad')),
                                 provincia=str(profesor.get('provincia')),
                                 fecha_nac=str(profesor.get('fecha_nac')),
                                 telefonoA=str(profesor.get('telefonoA')),
                                 telefonoB=str(profesor.get('telefonoB'))))

        #Los adaptamos al tipo de mensaje y enviamos
        #return Greeting(message=str(result.content))
        return ListaProfesores(profesores=profesoresItems)
def get_related_entities(kind, entity_id, related_kind, rk_entity_id=None, subrelated_kind=None):
    """

    :param kind:
    :param entity_id:
    :param related_kind:
    :return:

     Example of use:
       curl -i -X GET localhost:8001/entities/student/1/teacher
    """

    url = 'http://{}/entities/{}/{}/{}'.format(modules.get_hostname(module='tdbms'),kind,entity_id, related_kind)

    if rk_entity_id and subrelated_kind:
        url += '/{}/{}'.format(rk_entity_id, subrelated_kind)

    response = requests.get(url)
    response = make_response(response.content, response.status_code)
    response.headers['Access-Control-Allow-Origin'] = "*"
    return response
Ejemplo n.º 48
0
def enqueue_process_change_task(auth_db_rev):
    """Transactionally adds a call to 'process_change' to the task queue.

  Pins the task to currently executing version of BACKEND_MODULE module
  (defined in config.py).

  Added as AuthDB commit callback in get_backend_routes() below.
  """
    assert ndb.in_transaction()
    conf = config.ensure_configured()
    try:
        # Pin the task to the module and version.
        taskqueue.add(
            url="/internal/auth/taskqueue/process-change/%d" % auth_db_rev,
            queue_name=conf.PROCESS_CHANGE_TASK_QUEUE,
            headers={"Host": modules.get_hostname(module=conf.BACKEND_MODULE)},
            transactional=True,
        )
    except Exception as e:
        logging.error('Problem adding "process-change" task to the task queue (%s): %s', e.__class__.__name__, e)
        raise
Ejemplo n.º 49
0
def postClase():
    '''
    Inserta una nueva clase en el sistema.
    curl -d "curso=3&grupo=C&nivel=ESO" -i -X POST localhost:8002/clases
    '''
    salida = GestorClases.nuevaClase(request.form['curso'], request.form['grupo'], request.form['nivel'])


    if salida['status'] == 'OK':

        #Una vez insertada la asignatura en el SBD llamamos al servicio SCE para que actualice su sistema (### DISPARADOR ###)

        #Conformamos la dirección:
        module = modules.get_current_module_name()
        url = "http://%s/" % modules.get_hostname(module="sce")
        #Añadimos el servicio al que queremos conectarnos.
        url+="clases"
        #Componemos el nombre como un solo string
        nombreClase = request.form['curso']+request.form['grupo']+request.form['nivel']
        print nombreClase
        #Creamos un diccionario con los datos.
        datos = {
          "idClase": salida['idClase'],
          "nombreClase": nombreClase,
        }
        form_data = urllib.urlencode(datos)
        result=urlfetch.fetch(url=url, payload=form_data, method=urlfetch.POST)
        print result.content
        json = jsonpickle.decode(result.content)

        print 'AQUIIIIIIIIIIIIIIIIIIIIII'
        print json['status']

        if json['status']!='OK':
            salida['status']='SCE ERROR'

    if v:
        print ' Return: '+str(salida)

    return jsonpickle.encode(salida)
Ejemplo n.º 50
0
def get_task_queue_host():
  """Returns domain name of app engine instance to run a task queue task on.

  By default will use 'backend' module. Can be changed by calling
  set_task_queue_module during application startup.

  This domain name points to a matching version of appropriate app engine
  module - <version>.<module>.<app-id>.appspot.com where:
    version: version of the module that is calling this function.
    module: app engine module to execute task on.

  That way a task enqueued from version 'A' of default module would be executed
  on same version 'A' of backend module.
  """
  # modules.get_hostname sometimes fails with unknown internal error.
  # Cache its result in a memcache to avoid calling it too often.
  cache_key = 'task_queue_host:%s:%s' % (_task_queue_module, get_app_version())
  value = memcache.get(cache_key)
  if not value:
    value = modules.get_hostname(module=_task_queue_module)
    memcache.set(cache_key, value)
  return value
    def eliminar_alumno(self, request):

        print "POST EN CLOUDPOINTS"
        print str(request)

        #Una vez que tenemos los datos aquí los enviamos al servicio que gestiona la base de datos.
        #Podemos imprimir por pantalla los datos recolectados
        print "MENSAJE RECIBIDO EN ENDPOINTS"+request.dni

        #Nos conectamos al modulo para enviarle los mismos
        from google.appengine.api import modules
        #Conformamos la dirección:
        url = "http://%s/" % modules.get_hostname(module="microservicio1")

        '''
        Parece que urlfetch da problemas a al hora de pasar parámetros (payload) cuando se trata del
        método DELETE.
        Extracto de la doc:
        payload: POST, PUT, or PATCH payload (implies method is not GET, HEAD, or DELETE). this is ignored if the method is not POST, PUT, or PATCH.
        Además no somos los primeros en encontrarse este problema:
        http://grokbase.com/t/gg/google-appengine/13bvr5qjyq/is-there-any-reason-that-urlfetch-delete-method-does-not-support-a-payload

        Según la última cuestión puede que tengamos que usar POST

        '''
        url+='alumnos/'+request.dni

        #EL problema queda aquí, a expensas de ver si podemos usar DELETE o tenemos que realizar un apaño con post
        #usando algún parámetro que indique si se debe eliminar.
        result = urlfetch.fetch(url=url, method=urlfetch.DELETE)

        print "RESULTADOS DE PETICION AL M1: "
        print result.content

        #return MensajeRespuesta(message="Todo OK man!")
        #Mandamos la respuesta que nos devuelve la llamada al microservicio:
        return MensajeRespuesta(message=result.content)
Ejemplo n.º 52
0
    def get(self):
        email_address = self.request.get("email_address")
        if not mail.is_email_valid(email_address):
            self.response.write('invalid email address')
            self.response.status = 400
            return
        confirm_id = str(uuid.uuid4().get_hex().upper()[0:6])
        confirmation_url = 'http://'+modules.get_hostname()+'/news/confirm?confirm_id='+confirm_id
        subject = "Confirm your subscription"
        body = """Thank you for subscribing to splunk-sizing.appspot.com!

Please confirm your email address by clicking on the link below:

%s
""" % confirmation_url
        subscription = Subscription.get_or_insert(email_address)
        if subscription.confirmed:
            self.response.write('already confirmed')
            self.response.status = 400
            return
        subscription.confirm_date = None
        subscription.confirm_id = confirm_id
        subscription.put()
        mail.send_mail(sender_address, email_address, subject, body)
Ejemplo n.º 53
0
import urllib2
import json

sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from db_models.user_data import UserData

from google.appengine.ext import db
from kombu import Queue, Exchange

from common.config import AgentTypes, AgentConfig, FlexConfig, JobDatabaseConfig
import common.helper as helper
from databases.flex_db import FlexDB
from db_models.vm_state_model import VMStateModel

BACKEND_NAME = "backendthread"
BACKEND_URL = "http://%s" % modules.get_hostname(BACKEND_NAME)

BACKEND_START = "{0}/_ah/start".format(BACKEND_URL)
BACKEND_BACKGROUND = "{0}/_ah/background".format(BACKEND_URL)
BACKEND_SYN_R_URL = "{0}/backend/synchronizedb".format(BACKEND_URL)
BACKEND_MANAGER_R_URL = "{0}/backend/manager".format(BACKEND_URL)
BACKEND_QUEUE_R_URL = "http://{0}{1}".format(modules.get_hostname("backendqueue"), "/backend/queue")
BACKEND_PREPARE_VMS_OP = "prepare_vms"

INS_TYPES_EC2 = ["t1.micro", "m1.small", "m3.medium", "m3.large", "c3.large", "c3.xlarge"]


class VMStateSyn(db.Model):
    last_syn = db.DateTimeProperty()
    infra = db.StringProperty()
    thread_id = db.IntegerProperty()  # So only one thread is active per infra
Ejemplo n.º 54
0
def get_local_dev_server_host():
  """Returns 'hostname:port' for a default module on a local dev server."""
  assert utils.is_local_dev_server()
  return modules.get_hostname(module='default')
Ejemplo n.º 55
0
    def post(self):
        
        urlfetch.set_default_fetch_deadline(URLFETCH_DEADLINE)

        try:
            records = json.loads(self.request.body)
            logging.info(len(records))

        except ValueError:
            self.error(400)
            self.response.out.write('{"error":"Wrong input format. Must provide a list-type object with the records"}')
            return
        if self.request.body == '' or type(records) != type([]):
            self.error(400)
            self.response.out.write('{"error":"Wrong input format. Must provide a list-type object with the records"}')
            return
        if len(records) > 1000:
            self.error(400)
            self.response.out.write('{"error":"Too many records. There is a hard limit of 1000 records per request"}')
            return

        idxs = {}
        flags = {}

        # Extract indices for records
        for i in range(len(records)):

            # Get values from record
            decimalLatitude = records[i]['decimalLatitude'] if 'decimalLatitude' in records[i].keys() else None
            decimalLongitude = records[i]['decimalLongitude'] if 'decimalLongitude' in records[i].keys() else None
            countryCode = records[i]['countryCode'] if 'countryCode' in records[i].keys() else None
            scientificName = records[i]['scientificName'] if 'scientificName' in records[i].keys() else None
            
            # Build "ID" by tupling values
            idx = ((decimalLatitude, decimalLongitude), countryCode, scientificName)

            # Store id in position in array
            idxs[i] = idx

            # Initialize empty flag object for that ID
            flags[idx] = {}

        # ADDED TO AVOID query_wait_timeout ISSUES IN CARTODB

        # Divide list of IDs into smaller chunks
        idx_chunks = chunks(flags.keys(), POST_CHUNK_SIZE)

        # Process chunks iteratively
        for chunk in idx_chunks:

            logging.info("Processing chunk of %d IDs" % len(chunk))

            # Create and launch RPCs
            for i in chunk:

                # Create a new RPC
                rpc = urlfetch.create_rpc()
                params = {
                    'decimalLatitude': i[0][0],
                    'decimalLongitude': i[0][1],
                    'countryCode': i[1],
                    'scientificName': i[2]
                }
                try:
                    data = urlencode(params)
                except UnicodeEncodeError:
                    logging.error(params)
                    raise UnicodeEncodeError

                # Launch the async call to singlerecord
                urlfetch.make_fetch_call(
                    rpc,
                    url="http://"+modules.get_hostname(module=MODULE)+"/geospatial/singlerecord",
                    payload=data,
                    method=urlfetch.POST,
                    headers={"Content-Type":"application/x-www-form-urlencoded"}
                )

                # Store the rpc
                flags[i]['rpc'] = rpc

            # Wait for RPCs to finish and get results
            for i in chunk:

                result = flags[i]['rpc'].get_result()
                fl = ast.literal_eval(result.content)
                flags[i]['flags'] = fl
                # try:
                #     result = flags[i]['rpc'].get_result()
                # except QueryWaitTimeoutError:
                #     logging.warning("Got query_wait_timeout error, retrying")
                # flags[i]['flags'] = json.loads(flags[i]['rpc'].get_result().content.replace("u'", "'").replace("'", '"'))['flags']

        # Fill in flags in each record
        for i in idxs.keys():
            records[i]['flags'] = flags[idxs[i]]['flags']

        self.response.headers["Access-Control-Allow-Origin"] = "*"
        self.response.headers["Access-Control-Allow-Headers"] = "content-type"
        self.response.headers['Content-Type'] = 'application/json'
        self.response.out.write(json.dumps(records))

        return
Ejemplo n.º 56
0
 def get(self):
     context = {'api_base_url': modules.get_hostname(module='api')}
     content = self.jinja2.render_template('main.html', **context)
     self.response.write(content)
Ejemplo n.º 57
0
import os
import json
import urllib
import logging

from google.appengine.api import urlfetch, mail, modules
import webapp2

__author__ = '@jotegui'

URLFETCH_DEADLINE = 60
MODULE_NAME = "tools-repochecker"
MODULE_URL = modules.get_hostname(module=MODULE_NAME)

IS_DEV = os.environ.get('SERVER_SOFTWARE', '').startswith('Development')

SENDER = "Resource Name Checker <*****@*****.**>"

if IS_DEV:
    ADMINS = ["*****@*****.**"]
else:
    ADMINS = [
        "*****@*****.**",
        "*****@*****.**",
        "*****@*****.**",
        "*****@*****.**"
    ]

ghb_url = "https://api.github.com"
cdb_url = "https://vertnet.cartodb.com/api/v2/sql"
Ejemplo n.º 58
0
def postAlumno():
    '''
    Método que inserta un nuevo alumno en el sistema.
    curl -d "nombre=Juan&apellidos=Fernandez&dni=45601218&direccion=Calle arabl&localidad=Jerez de la frontera&provincia=Granada&fecha_nacimiento=1988-2-6&telefono=677164459" -i -X POST localhost:8002/alumnos
    '''
    if v:
        print nombreMicroservicio
        print 'Recurso: /alumnos , metodo: POST'
        print "Petición: "
        print request.form

        print 'aqui'
        imagen = request.form.get('imagen')

        #print imagen

        salida= "";

    if imagen != None:
        print 'Calling with image'
        salida = GestorAlumnos.nuevoAlumno(request.form['nombre'].encode('latin-1'),
                                  request.form['apellidos'].encode('latin-1'),
                                  request.form['dni'].encode('latin-1'),
                                  request.form['direccion'].encode('latin-1'),
                                  request.form['localidad'].encode('latin-1'),
                                  request.form['provincia'].encode('latin-1'),
                                  request.form['fecha_nacimiento'].encode('latin-1'),
                                  request.form['telefono'].encode('latin-1'),
                                  request.form['imagen'])
    else:
        print 'Calling without image'
        salida = GestorAlumnos.nuevoAlumno(request.form['nombre'].encode('latin-1'),
                                  request.form['apellidos'].encode('latin-1'),
                                  request.form['dni'].encode('latin-1'),
                                  request.form['direccion'].encode('latin-1'),
                                  request.form['localidad'].encode('latin-1'),
                                  request.form['provincia'].encode('latin-1'),
                                  request.form['fecha_nacimiento'].encode('latin-1'),
                                  request.form['telefono'].encode('latin-1'))


    if salida['status'] == 'OK':

        #Una vez insertada la asignatura en el SBD llamamos al servicio SCE para que actualice su sistema (### DISPARADOR ###)

        #Conformamos la dirección:
        module = modules.get_current_module_name()
        url = "http://%s/" % modules.get_hostname(module="sce")
        #Añadimos el servicio al que queremos conectarnos.
        url+="alumnos"

        #Creamos un diccionario con los datos.
        datos = {
          "idAlumno": salida['idAlumno'],
          "nombreAlumno": request.form['nombre']+' '+request.form['apellidos'],
        }
        form_data = urllib.urlencode(datos)
        result=urlfetch.fetch(url=url, payload=form_data, method=urlfetch.POST)
        print 'yeahhhhhhhhhhhhhhhhhhhhhhhhhh';
        print result.content
        json = jsonpickle.decode(result.content)
        if json['status']!='OK':
            salida['status']='SCE ERROR'

    if v:
        print ' Return: '+str(salida)

    return jsonpickle.encode(salida)
Ejemplo n.º 59
0
from google.appengine.api import modules

MODULE_NAME = "tools-usagestats"
MODULE = modules.get_hostname(module=MODULE_NAME).replace("prod.", "")

# External API URLs and configs

# CartoDB
CDB_URL = "https://vertnet.cartodb.com/api/v2/sql"
CDB_TABLE = "query_log_master"

# Geonames
GNM_URL = "http://api.geonames.org/countryCodeJSON"

# GitHub
GH_URL = "https://api.github.com"
GH_REPOS = GH_URL + "/repos"
GH_COMMITTER = {
    'name': 'VertNet',
    'email': '*****@*****.**'
}

# URIs, relative to app root
URI_BASE = "/admin/parser/"
URI_INIT = URI_BASE + "init"
URI_GET_EVENTS = URI_BASE + "get_events"
URI_PROCESS_EVENTS = URI_BASE + "process_events"
URI_GITHUB_STORE = URI_BASE + "github_store"
URI_GITHUB_ISSUE = URI_BASE + "github_issue"

# URLs