Example #1
0
def wsgibase(environ, responder):
    """
    this is the gluon wsgi application. the first function called when a page
    is requested (static or dynamic). it can be called by paste.httpserver
    or by apache mod_wsgi.

      - fills request with info
      - the environment variables, replacing '.' with '_'
      - adds web2py path and version info
      - compensates for fcgi missing path_info and query_string
      - validates the path in url

    The url path must be either:

    1. for static pages:

      - /<application>/static/<file>

    2. for dynamic pages:

      - /<application>[/<controller>[/<function>[/<sub>]]][.<extension>]
      - (sub may go several levels deep, currently 3 levels are supported:
         sub1/sub2/sub3)

    The naming conventions are:

      - application, controller, function and extension may only contain
        [a-zA-Z0-9_]
      - file and sub may also contain '-', '=', '.' and '/'
    """

    current.__dict__.clear()
    request = Request()
    response = Response()
    session = Session()
    request.env.web2py_path = global_settings.applications_parent
    request.env.web2py_version = web2py_version
    request.env.update(global_settings)
    static_file = False
    try:
        try:
            try:
                # ##################################################
                # handle fcgi missing path_info and query_string
                # select rewrite parameters
                # rewrite incoming URL
                # parse rewritten header variables
                # parse rewritten URL
                # serve file if static
                # ##################################################

                if not environ.get('PATH_INFO',None) and \
                        environ.get('REQUEST_URI',None):
                    # for fcgi, get path_info and query_string from request_uri
                    items = environ['REQUEST_URI'].split('?')
                    environ['PATH_INFO'] = items[0]
                    if len(items) > 1:
                        environ['QUERY_STRING'] = items[1]
                    else:
                        environ['QUERY_STRING'] = ''
                if not environ.get('HTTP_HOST',None):
                    environ['HTTP_HOST'] = '%s:%s' % (environ.get('SERVER_NAME'),
                                                      environ.get('SERVER_PORT'))

                (static_file, environ) = rewrite.url_in(request, environ)
                if static_file:
                    if request.env.get('query_string', '')[:10] == 'attachment':
                        response.headers['Content-Disposition'] = 'attachment'
                    response.stream(static_file, request=request)

                # ##################################################
                # fill in request items
                # ##################################################

                http_host = request.env.http_host.split(':',1)[0]

                local_hosts = [http_host,'::1','127.0.0.1','::ffff:127.0.0.1']
                if not global_settings.web2py_runtime_gae:
                    local_hosts += [socket.gethostname(),
                                    socket.gethostbyname(http_host)]
                request.client = get_client(request.env)
                request.folder = abspath('applications',
                                         request.application) + os.sep
                x_req_with = str(request.env.http_x_requested_with).lower()
                request.ajax = x_req_with == 'xmlhttprequest'
                request.cid = request.env.http_web2py_component_element
                request.is_local = request.env.remote_addr in local_hosts
                request.is_https = request.env.wsgi_url_scheme \
                    in ['https', 'HTTPS'] or request.env.https == 'on'

                # ##################################################
                # compute a request.uuid to be used for tickets and toolbar
                # ##################################################

                response.uuid = request.compute_uuid()

                # ##################################################
                # access the requested application
                # ##################################################

                if not os.path.exists(request.folder):
                    if request.application == rewrite.thread.routes.default_application and request.application != 'welcome':
                        request.application = 'welcome'
                        redirect(Url(r=request))
                    elif rewrite.thread.routes.error_handler:
                        redirect(Url(rewrite.thread.routes.error_handler['application'],
                                     rewrite.thread.routes.error_handler['controller'],
                                     rewrite.thread.routes.error_handler['function'],
                                     args=request.application))
                    else:
                        raise HTTP(404,
                                   rewrite.thread.routes.error_message % 'invalid request',
                                   web2py_error='invalid application')
                request.url = Url(r=request, args=request.args,
                                       extension=request.raw_extension)

                # ##################################################
                # build missing folders
                # ##################################################

                create_missing_app_folders(request)

                # ##################################################
                # get the GET and POST data
                # ##################################################

                parse_get_post_vars(request, environ)

                # ##################################################
                # expose wsgi hooks for convenience
                # ##################################################

                request.wsgi.environ = environ_aux(environ,request)
                request.wsgi.start_response = lambda status='200', headers=[], \
                    exec_info=None, response=response: \
                    start_response_aux(status, headers, exec_info, response)
                request.wsgi.middleware = lambda *a: middleware_aux(request,response,*a)

                # ##################################################
                # load cookies
                # ##################################################

                if request.env.http_cookie:
                    try:
                        request.cookies.load(request.env.http_cookie)
                    except Cookie.CookieError, e:
                        pass # invalid cookies

                # ##################################################
                # try load session or create new session file
                # ##################################################

                session.connect(request, response)

                # ##################################################
                # set no-cache headers
                # ##################################################

                response.headers['Content-Type'] = contenttype('.'+request.extension)
                response.headers['Cache-Control'] = \
                    'no-store, no-cache, must-revalidate, post-check=0, pre-check=0'
                response.headers['Expires'] = \
                    time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime())
                response.headers['Pragma'] = 'no-cache'

                # ##################################################
                # run controller
                # ##################################################

                serve_controller(request, response, session)

            except HTTP, http_response:
                if static_file:
                    return http_response.to(responder)

                if request.body:
                    request.body.close()

                # ##################################################
                # on success, try store session in database
                # ##################################################
                session._try_store_in_db(request, response)

                # ##################################################
                # on success, commit database
                # ##################################################

                if response._custom_commit:
                    response._custom_commit()
                else:
                    BaseAdapter.close_all_instances('commit')

                # ##################################################
                # if session not in db try store session on filesystem
                # this must be done after trying to commit database!
                # ##################################################

                session._try_store_on_disk(request, response)

                # ##################################################
                # store cookies in headers
                # ##################################################

                if request.cid:

                    if response.flash and not 'web2py-component-flash' in http_response.headers:
                        http_response.headers['web2py-component-flash'] = \
                            dumps(str(response.flash).replace('\n',''))
                    if response.js and not 'web2py-component-command' in http_response.headers:
                        http_response.headers['web2py-component-command'] = \
                            response.js.replace('\n','')
                if session._forget:
                    del response.cookies[response.session_id_name]
                elif session._secure:
                    response.cookies[response.session_id_name]['secure'] = True
                if len(response.cookies)>0:
                    http_response.headers['Set-Cookie'] = \
                        [str(cookie)[11:] for cookie in response.cookies.values()]
                ticket=None

            except RestrictedError, e:

                if request.body:
                    request.body.close()

                # ##################################################
                # on application error, rollback database
                # ##################################################

                ticket = e.log(request) or 'unknown'
                if response._custom_rollback:
                    response._custom_rollback()
                else:
                    BaseAdapter.close_all_instances('rollback')

                http_response = \
                    HTTP(500,
                         rewrite.thread.routes.error_message_ticket % dict(ticket=ticket),
                         web2py_error='ticket %s' % ticket)
Example #2
0
def validarArchivos():

	## Función invocada mediante AJAX cuando se presiona el botón de "validar_archivos"
	## en la forma, y se encontró un valor t para los campos: "es_audible_ultrasonico"
	## y grabadora_id" (debido a este último, deben haberse seleccionado valores
	## de "conglomerado_muestra_id" y "sitio_muestra_id"). Esta función valida:
	##	1. Que el registro de los archivos no se haya realizado con anterioridad.
	##	2. Que la carpeta nombre_cgl_aaaa-mm-dd/t exista.
	##	3. Que dicha carpeta no esté vacía

	## Regresa un JSON con:
	## 1. El mensaje apropiado en cada caso, para que la vista
	## lo alerte
	## 2. Una bandera que indica si la validación fue exitosa o no
	## 3. El "nombre" y la "fecha_visita" del conglomerado cuyo id fue recibido
	## mediante AJAX, para no tener que recalcularlos en index2().

	# Bandera que indica si los archivos fueron validados correctamente

	flag = 0

	grabadoraElegidaID = request.vars.grabadora_id

	tipoArchivo = request.vars.es_audible_ultrasonico

	# Obteniendo los archivos correspondientes a la grabadora y tipo seleccionados.
	# ésto código no puede tronar porque, gracias a la validación en la vista,
	# los valores de "grabadoraElegidaID" y "tipoArchivo" son no vacíos.

	if tipoArchivo == "audible":

		archivosGrabadora = db(
			(db.Archivo_grabadora.grabadora_id == grabadoraElegidaID) &\
			(db.Archivo_grabadora.es_audible == True)
			).select()

	else:

		archivosGrabadora = db(
			(db.Archivo_grabadora.grabadora_id == grabadoraElegidaID) &\
			(db.Archivo_grabadora.es_audible == False)
			).select()

	datosConglomeradoNombre = ""
	datosConglomeradoFechaVisita = ""

	# Generando los distintos mensajes:

	if len(archivosGrabadora) > 0:

		mensaje = "Ya se han enviado los archivos " + tipoArchivo + "s para el " +\
		"conglomerado seleccionado. Si lo necesita, borre el registro de la grabadora " +\
		"en la sección de 'Revisar registros', y vuelva a declararla"

	else:

		# Obteniendo los datos del conglomerado seleccionado, con el fin de crear
		# el path hacia la carpeta apropiada:

		conglomeradoElegidoID = request.vars.conglomerado_muestra_id

		# Obteniendo la información del conglomerado

		datosConglomeradoAux = db(
			db.Conglomerado_muestra.id == conglomeradoElegidoID).select(
			db.Conglomerado_muestra.nombre, db.Conglomerado_muestra.fecha_visita)

		datosConglomerado = datosConglomeradoAux.first()

		datosConglomeradoNombre = str(datosConglomerado['nombre'])
		datosConglomeradoFechaVisita = str(datosConglomerado['fecha_visita'])

		# Creando la ruta hacia la carpeta nombre_cgl_aaaa-mm-dd/t

		rutaCarpetaCglMuestra = eaa.crearRutaCarpeta(
			datosConglomeradoNombre,
			datosConglomeradoFechaVisita
		)

		if tipoArchivo == "audible":
			subcarpeta = "g_a"

		else:
			subcarpeta = "g_u"

		rutaT = os.path.join(rutaCarpetaCglMuestra, subcarpeta)

		#rutaTMensaje es la rutaT expresada para que el usuario la entienda

		rutaTMensaje = os.path.join(
			'conglomerados',
			datosConglomeradoNombre + '_' + datosConglomeradoFechaVisita,
			subcarpeta)

		# Verificando que dicha carpeta exista

		if not os.path.isdir(rutaT):

			mensaje = "No se encontró la carpeta " + rutaTMensaje +\
			". Favor de crearla."

		else:

			# Verificando que dicha carpeta contenga archivos wav:

			# Enlistando los archivos en rutaT
			lista_archivos = os.listdir(rutaT)

			# Obteniendo de éstos, cuáles son los archivos con terminación wav.
			lista_wav = [archivo\
				for archivo in lista_archivos\
				if re.search(r'wav$', archivo, re.I)]

			if len(lista_wav) == 0:

				mensaje = "La carpeta " + rutaTMensaje + " no contiene archivos " +\
				"WAV, favor de agregarle los archivos " + tipoArchivo + "s"

			else:

				mensaje = "Validación exitosa para " + str(len(lista_wav)) +\
				" archivos WAV declarados como " + tipoArchivo + "s en: " +\
				rutaTMensaje + ". Ahora puede enviar la información."

				flag = 1

	# Enviando el diccionario como JSON para que JS lo pueda interpretar
	return json.dumps(dict(
		flag = flag,
		mensaje = mensaje,
		conglomerado_muestra_nombre = datosConglomeradoNombre,
		conglomerado_muestra_fecha_visita = datosConglomeradoFechaVisita,
		))
Example #3
0
def json(value):
    return simplejson.dumps(value)
Example #4
0
def json(value,default=custom_json):
    return simplejson.dumps(value,default=default)
Example #5
0
def json(value,default=custom_json):
    return simplejson.dumps(value,default=default)
def json(value):
    return simplejson.dumps(value)
Example #7
0
def wsgibase(environ, responder):
    """
    this is the gluon wsgi application. the first function called when a page
    is requested (static or dynamic). it can be called by paste.httpserver
    or by apache mod_wsgi.

      - fills request with info
      - the environment variables, replacing '.' with '_'
      - adds web2py path and version info
      - compensates for fcgi missing path_info and query_string
      - validates the path in url

    The url path must be either:

    1. for static pages:

      - /<application>/static/<file>

    2. for dynamic pages:

      - /<application>[/<controller>[/<function>[/<sub>]]][.<extension>]
      - (sub may go several levels deep, currently 3 levels are supported:
         sub1/sub2/sub3)

    The naming conventions are:

      - application, controller, function and extension may only contain
        [a-zA-Z0-9_]
      - file and sub may also contain '-', '=', '.' and '/'
    """

    current.__dict__.clear()
    request = Request()
    response = Response()
    session = Session()
    request.env.web2py_path = global_settings.applications_parent
    request.env.web2py_version = web2py_version
    request.env.update(global_settings)
    static_file = False
    try:
        try:
            try:
                # ##################################################
                # handle fcgi missing path_info and query_string
                # select rewrite parameters
                # rewrite incoming URL
                # parse rewritten header variables
                # parse rewritten URL
                # serve file if static
                # ##################################################

                if not environ.get('PATH_INFO',None) and \
                        environ.get('REQUEST_URI',None):
                    # for fcgi, get path_info and query_string from request_uri
                    items = environ['REQUEST_URI'].split('?')
                    environ['PATH_INFO'] = items[0]
                    if len(items) > 1:
                        environ['QUERY_STRING'] = items[1]
                    else:
                        environ['QUERY_STRING'] = ''
                if not environ.get('HTTP_HOST', None):
                    environ['HTTP_HOST'] = '%s:%s' % (
                        environ.get('SERVER_NAME'), environ.get('SERVER_PORT'))

                (static_file, environ) = rewrite.url_in(request, environ)
                if static_file:
                    if request.env.get('query_string',
                                       '')[:10] == 'attachment':
                        response.headers['Content-Disposition'] = 'attachment'
                    response.stream(static_file, request=request)

                # ##################################################
                # fill in request items
                # ##################################################

                http_host = request.env.http_host.split(':', 1)[0]

                local_hosts = [
                    http_host, '::1', '127.0.0.1', '::ffff:127.0.0.1'
                ]
                if not global_settings.web2py_runtime_gae:
                    local_hosts += [
                        socket.gethostname(),
                        socket.gethostbyname(http_host)
                    ]
                request.client = get_client(request.env)
                request.folder = abspath('applications',
                                         request.application) + os.sep
                x_req_with = str(request.env.http_x_requested_with).lower()
                request.ajax = x_req_with == 'xmlhttprequest'
                request.cid = request.env.http_web2py_component_element
                request.is_local = request.env.remote_addr in local_hosts
                request.is_https = request.env.wsgi_url_scheme \
                    in ['https', 'HTTPS'] or request.env.https == 'on'

                # ##################################################
                # compute a request.uuid to be used for tickets and toolbar
                # ##################################################

                response.uuid = request.compute_uuid()

                # ##################################################
                # access the requested application
                # ##################################################

                if not os.path.exists(request.folder):
                    if request.application == rewrite.thread.routes.default_application and request.application != 'welcome':
                        request.application = 'welcome'
                        redirect(Url(r=request))
                    elif rewrite.thread.routes.error_handler:
                        redirect(
                            Url(rewrite.thread.routes.
                                error_handler['application'],
                                rewrite.thread.routes.
                                error_handler['controller'],
                                rewrite.thread.routes.
                                error_handler['function'],
                                args=request.application))
                    else:
                        raise HTTP(404,
                                   rewrite.thread.routes.error_message %
                                   'invalid request',
                                   web2py_error='invalid application')
                request.url = Url(r=request,
                                  args=request.args,
                                  extension=request.raw_extension)

                # ##################################################
                # build missing folders
                # ##################################################

                create_missing_app_folders(request)

                # ##################################################
                # get the GET and POST data
                # ##################################################

                parse_get_post_vars(request, environ)

                # ##################################################
                # expose wsgi hooks for convenience
                # ##################################################

                request.wsgi.environ = environ_aux(environ, request)
                request.wsgi.start_response = lambda status='200', headers=[], \
                    exec_info=None, response=response: \
                    start_response_aux(status, headers, exec_info, response)
                request.wsgi.middleware = lambda *a: middleware_aux(
                    request, response, *a)

                # ##################################################
                # load cookies
                # ##################################################

                if request.env.http_cookie:
                    try:
                        request.cookies.load(request.env.http_cookie)
                    except Cookie.CookieError, e:
                        pass  # invalid cookies

                # ##################################################
                # try load session or create new session file
                # ##################################################

                session.connect(request, response)

                # ##################################################
                # set no-cache headers
                # ##################################################

                response.headers['Content-Type'] = contenttype(
                    '.' + request.extension)
                response.headers['Cache-Control'] = \
                    'no-store, no-cache, must-revalidate, post-check=0, pre-check=0'
                response.headers['Expires'] = \
                    time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime())
                response.headers['Pragma'] = 'no-cache'

                # ##################################################
                # run controller
                # ##################################################

                serve_controller(request, response, session)

            except HTTP, http_response:
                if static_file:
                    return http_response.to(responder)

                if request.body:
                    request.body.close()

                # ##################################################
                # on success, try store session in database
                # ##################################################
                session._try_store_in_db(request, response)

                # ##################################################
                # on success, commit database
                # ##################################################

                if response._custom_commit:
                    response._custom_commit()
                else:
                    BaseAdapter.close_all_instances('commit')

                # ##################################################
                # if session not in db try store session on filesystem
                # this must be done after trying to commit database!
                # ##################################################

                session._try_store_on_disk(request, response)

                # ##################################################
                # store cookies in headers
                # ##################################################

                if request.cid:

                    if response.flash and not 'web2py-component-flash' in http_response.headers:
                        http_response.headers['web2py-component-flash'] = \
                            dumps(str(response.flash).replace('\n',''))
                    if response.js and not 'web2py-component-command' in http_response.headers:
                        http_response.headers['web2py-component-command'] = \
                            response.js.replace('\n','')
                if session._forget:
                    del response.cookies[response.session_id_name]
                elif session._secure:
                    response.cookies[response.session_id_name]['secure'] = True
                if len(response.cookies) > 0:
                    http_response.headers['Set-Cookie'] = \
                        [str(cookie)[11:] for cookie in response.cookies.values()]
                ticket = None

            except RestrictedError, e:

                if request.body:
                    request.body.close()

                # ##################################################
                # on application error, rollback database
                # ##################################################

                ticket = e.log(request) or 'unknown'
                if response._custom_rollback:
                    response._custom_rollback()
                else:
                    BaseAdapter.close_all_instances('rollback')

                http_response = \
                    HTTP(500,
                         rewrite.thread.routes.error_message_ticket % dict(ticket=ticket),
                         web2py_error='ticket %s' % ticket)
Example #8
0
def validarArchivos():

	## Función invocada mediante AJAX cuando se presiona el botón de "validar_archivos"
	## en la forma, y además se encuentra un valor para "camara_id" (por lo que
	## deben haberse seleccionado valores de "conglomerado_muestra_id" y
	## "sitio_muestra_id"). Esta función valida:
	##	1. Que el registro de los archivos no se haya realizado con anterioridad.
	##	2. Que la carpeta nombre_cgl_aaaa-mm-dd/c exista.
	##	3. Que dicha carpeta no esté vacía

	## Regresa un JSON con:
	## 1. El mensaje apropiado en cada caso, para que la vista
	## lo alerte
	## 2. Una bandera que indica si la validación fue exitosa o no
	## 3. El "nombre" y la "fecha_visita" del conglomerado cuyo id fue recibido
	## mediante AJAX, para no tener que recalcularlos en index2().

	# Bandera que indica si los archivos fueron validados correctamente

	flag = 0

	camaraElegidaID = request.vars.camara_id

	# Obteniendo los archivos correspondientes a la cámara seleccionada

	archivosCamara = db(db.Archivo_camara.camara_id == camaraElegidaID).select()

	datosConglomeradoNombre = ""
	datosConglomeradoFechaVisita = ""

	# Generando los distintos mensajes:

	if len(archivosCamara) > 0:

		mensaje = "Ya se han enviado los archivos de la cámara para el " +\
		"conglomerado seleccionado. Si lo necesita, borre el registro de la cámara " +\
		"en la sección de 'Revisar registros', y vuelva a declararla"

	else:

		# Obteniendo los datos del conglomerado seleccionado, con el fin de crear
		# el path hacia la carpeta apropiada:

		conglomeradoElegidoID = request.vars.conglomerado_muestra_id

		# Obteniendo la información del conglomerado

		datosConglomeradoAux = db(
			db.Conglomerado_muestra.id == conglomeradoElegidoID).select(
			db.Conglomerado_muestra.nombre, db.Conglomerado_muestra.fecha_visita)

		datosConglomerado = datosConglomeradoAux.first()

		datosConglomeradoNombre = str(datosConglomerado['nombre'])
		datosConglomeradoFechaVisita = str(datosConglomerado['fecha_visita'])

		# Creando la ruta hacia la carpeta nombre_cgl_aaaa-mm-dd/c

		rutaCarpetaCglMuestra = eaa.crearRutaCarpeta(
			datosConglomeradoNombre,
			datosConglomeradoFechaVisita
		)

		rutaC = os.path.join(rutaCarpetaCglMuestra, 'c')

		#rutaCMensaje es la ruta C expresada para que el usuario la entienda

		rutaCMensaje = os.path.join(
			'conglomerados',
			datosConglomeradoNombre + '_' + datosConglomeradoFechaVisita,
			'c')

		# Verificando que dicha carpeta exista

		if not os.path.isdir(rutaC):

			mensaje = "No se encontró la carpeta " + rutaCMensaje +\
			". Favor de crearla."

		else:

			# Verificando que dicha carpeta contenga archivos jpg/avi:

			# Enlistando los archivos en rutaC
			lista_archivos = os.listdir(rutaC)

			# Obteniendo de éstos, cuáles son los archivos con terminación jpg/avi.
			lista_jpg_avi = [archivo\
				for archivo in lista_archivos\
				if re.search(r'(jp.?g|avi)$', archivo, re.I)]

			if len(lista_jpg_avi) == 0:

				mensaje = "La carpeta " + rutaCMensaje + " no contiene archivos " +\
				"JPG/AVI, favor de agregarle las imágenes y videos."

			else:

				mensaje = "Validación exitosa para " + str(len(lista_jpg_avi)) +\
				" archivos JPG/AVI en: " + rutaCMensaje + ". Ahora puede enviar la " +\
				"información."

				flag = 1

	# Enviando el diccionario como JSON para que JS lo pueda interpretar
	return json.dumps(dict(
		flag = flag,
		mensaje = mensaje,
		conglomerado_muestra_nombre = datosConglomeradoNombre,
		conglomerado_muestra_fecha_visita = datosConglomeradoFechaVisita
		))