Beispiel #1
0
    def identify(self, environ):
        path_info = environ['PATH_INFO']
        query = parse_dict_querystring(environ)

        if path_info == self.logout_handler_path:
            # we've been asked to perform a logout
            form = parse_formvars(environ)
            form.update(query)
            referer = environ.get('HTTP_REFERER', '/')
            environ['repoze.who.application'] = HTTPUnauthorized()

            # invalidate the session
            identity = environ.get('repoze.who.identity')
            if identity:
                self.forget(environ, identity)

            return None

        elif path_info == self.login_handler_path:
            # we've been asked to perform a login
            form = parse_formvars(environ)
            form.update(query)

            credentials = self._getCredentials(form)

            referer = environ.get('HTTP_REFERER', '/')
            environ['repoze.who.application'] = HTTPFound(referer)
            if 'login' not in credentials or 'password' not in credentials:
                return None
            return credentials
    def identify(self, environ):
        path_info = environ['PATH_INFO']
        query = parse_dict_querystring(environ)

        if path_info == self.logout_handler_path:
            # we've been asked to perform a logout
            form = parse_formvars(environ)
            form.update(query)
            referer = environ.get('HTTP_REFERER', '/')
            environ['repoze.who.application'] = HTTPUnauthorized()
            return None

        elif path_info == self.login_handler_path:
            # we've been asked to perform a login
            form = parse_formvars(environ)
            form.update(query)
            try:
                max_age = form.get('max_age', None)
                credentials = {
                    'login':form['login'],
                    'password':form['password'],
                    'realm':form['realm'],
                    }
            except KeyError:
                credentials = None

            if credentials is not None:
                max_age = form.get('max_age', None)
                if max_age is not None:
                    credentials['max_age'] = max_age

            referer = environ.get('HTTP_REFERER', '/')
            environ['repoze.who.application'] = HTTPFound(referer)
            return credentials
Beispiel #3
0
    def identify(self, environ):
        path_info = environ['PATH_INFO']
        query = parse_dict_querystring(environ)

        if path_info == self.logout_handler_path:
            # we've been asked to perform a logout
            form = parse_formvars(environ)
            form.update(query)
            referer = environ.get('HTTP_REFERER', '/')
            environ['repoze.who.application'] = HTTPUnauthorized()
            return None

        elif path_info == self.login_handler_path:
            # we've been asked to perform a login
            form = parse_formvars(environ)
            form.update(query)
            try:
                max_age = form.get('max_age', None)
                credentials = {
                    'login': form['login'],
                    'password': form['password'],
                    'realm': form['realm'],
                }
            except KeyError:
                credentials = None

            if credentials is not None:
                max_age = form.get('max_age', None)
                if max_age is not None:
                    credentials['max_age'] = max_age

            referer = environ.get('HTTP_REFERER', '/')
            environ['repoze.who.application'] = HTTPFound(referer)
            return credentials
Beispiel #4
0
		def wrapped_function(environ, start_response):

			# Get the request information with Paste
			req = request.parse_formvars(environ, include_get_vars).mixed()

			# Start the coroutine. When it's done, we'll send the response back via
			# HTTP.
			response_coro = coroutine.Coroutine(func(**req))

			def completion_handler(retval, exc_info):
				"""
				Called when any coroutine-based page completes. Applies all
				postprocessing steps, and returns the page to the browser.
				"""

				if exc_info:
					# Shit
					raise exc_info[0], exc_info[1], exc_info[2]

				# Handle all the postprocessing steps
				if hasattr(func, "chiral_postprocessors"):
					for postproc in func.chiral_postprocessors:
						retval = postproc(retval)

				# Return it to the browser
				start_response("200 OK", {})

				return [ retval ], None

			response_coro.add_completion_callback(completion_handler)

			environ["chiral.http.set_coro"](response_coro)
			return [""]
Beispiel #5
0
def get_context(environ):
    """Figure out the CGI variables passed to this script"""
    form = parse_formvars(environ)
    if "year" in form:
        year1 = form.get("year")
        year2 = year1
    else:
        year1 = form.get("year1")
        year2 = form.get("year2")
    month1 = form.get("month1")
    month2 = form.get("month2")
    day1 = form.get("day1")
    day2 = form.get("day2")
    hour1 = form.get("hour1")
    hour2 = form.get("hour2")
    minute1 = form.get("minute1")
    minute2 = form.get("minute2")

    sts = utc(int(year1), int(month1), int(day1), int(hour1), int(minute1))
    ets = utc(int(year2), int(month2), int(day2), int(hour2), int(minute2))
    if ets < sts:
        s = ets
        ets = sts
        sts = s

    form["fmt"] = form.get("fmt", "shp")
    form["sts"] = sts
    form["ets"] = ets

    return form
Beispiel #6
0
def application(environ, start_response):
    """Go Main Go."""
    form = parse_formvars(environ)
    try:
        lat = float(form.get("lat"))
        lon = float(form.get("lon"))
    except (ValueError, TypeError):
        headers = [("Content-type", "text/plain")]
        start_response("500 Internal Server Error", headers)
        return [b"API FAIL!"]
    fn = spiral(lon, lat)
    if fn is None:
        headers = [("Content-type", "text/plain")]
        start_response("500 Internal Server Error", headers)
        return [b"API FAIL!"]

    headers = [
        ("Content-type", "application/octet-stream"),
        (
            "Content-Disposition",
            "attachment; filename=%s" % (fn.split("/")[-1], ),
        ),
    ]
    start_response("200 OK", headers)
    return [open(fn, "rb").read()]
Beispiel #7
0
def application(environ, start_response):
    """Main()"""
    headers = [("Content-type", "application/json")]

    form = parse_formvars(environ)
    network = form.get("network", "IACLIMATE").upper()
    month = int(form.get("month", 1))
    day = int(form.get("day", 1))
    syear = int(form.get("syear", 1800))
    eyear = int(form.get("eyear", datetime.datetime.now().year + 1))
    cb = form.get("callback", None)

    mckey = "/geojson/climodat_dayclimo/%s/%s/%s/%s/%s" % (
        network,
        month,
        day,
        syear,
        eyear,
    )
    mc = memcache.Client(["iem-memcached:11211"], debug=0)
    res = mc.get(mckey)
    if not res:
        res = run(network, month, day, syear, eyear)
        mc.set(mckey, res, 86400)

    if cb is None:
        data = res
    else:
        data = "%s(%s)" % (html_escape(cb), res)

    start_response("200 OK", headers)
    return [data.encode("ascii")]
Beispiel #8
0
    def __call__(self, environ, start_response):

        # log form fields
        pprint(parse_formvars(environ))

        # response
        # TODO: to format as ushahidi do
        start_response('200 OK', [('content-type', 'application/json')])

        #pprint(environ)
        #import pdb; pdb.set_trace()

        CATEGORIES['payload']['domain']= environ.get('HTTP_ORIGIN')
        
        if environ.get('REQUEST_METHOD','') == 'POST':
            #~ import pdb; pdb.set_trace()
            if  environ['paste.parsed_formvars'][0].has_key('task'):
                result = CATEGORIES  
            else:
                result = { "payload": {
                              "domain": environ.get('HTTP_ORIGIN'),
                              "success":"true"
                            },
                            "error":{ "code":"0",
                                      "message":"No Error"}
                        }
        elif environ.get('REQUEST_METHOD','') == 'GET' and \
             environ.get('QUERY_STRING', '') == 'task=categories':
            result = CATEGORIES
        else:
            result = {"status": "ok", "now": int(time.time())}

        return json.dumps(result)
Beispiel #9
0
def tilecache(request, *xtra):

    try:

        path_info = host = ""

        if "HTTP_X_FORWARDED_HOST" in request.META:
            host = "http://" + request.META["HTTP_X_FORWARDED_HOST"]

        elif "HTTP_HOST" in request.META:
            host = "http://" +request.META["HTTP_HOST"]

        host += request.META["SCRIPT_NAME"]
        req_method = request.META["REQUEST_METHOD"]
        path_info = request.META["PATH_INFO"]

        fields = parse_formvars(request.META)
        
        ##### test configs for changes #####
        
        myservice.checkchange()

        format, image = myservice.dispatchRequest( fields, path_info, req_method, host )
        headers = [( 'Content-Type', format.encode('utf-8') )]

    except TileCacheException, E:
        return HttpResponseServerError(["An error occurred: %s\n%s\n" % (
                                  str(E), 
                                  "".join(traceback.format_tb(sys.exc_traceback)))])
Beispiel #10
0
def app(environ, start_response):
    cfg = ConfigParser()
    cfg.read('crowd.properties')	
    fields = parse_formvars(environ)
    if environ['REQUEST_METHOD'] == 'POST':
	cc = CrowdPy()
	cc.createClient()
	cc.authenticateApplication()
	headers = [] 
	headers.append(('content-type','text/html'))
	try:
		authenticated = cc.authenticatePrincipal(fields['usernname'],fields['password'])
		cookieInfo = cc.getCookieInfo()
		if cookieInfo.domain is None:
			domain = cfg.get('default','domain.name')
		else:
			domain = cookieInfo.domain
		headers.append(('Set-Cookie','crowd.token_key=' + authenticated + ';path=/;domain='+ domain +';expires=Sat, 7-Feb-2012 03:10:00' ))
	except WebFault:
		start_response('200 OK', headers)
		return ['Invalid username/password']
	start_response('200 OK', headers)
	return ['Hello, ', fields['usernname'], ' You are valid user!']
    else:
	start_response('200 OK', [('content-type', 'text/html')])
	cookies = request.get_cookie_dict(environ)
	if 'crowd.token_key' in cookies.keys():
		cc = CrowdPy()
		cc.createClient()
		cc.authenticateApplication()
		isValid = cc.isValidPrincipalToken(cookies['crowd.token_key'])
             	return 'Already Authenticated'
        return ['<form method="POST">User-name: <input type="text" '
                'name="usernname"><br> Password : <input type="password" name="password" > <input type="submit"></form>']
Beispiel #11
0
def application(environ, start_response):
    """Do Fun things"""
    form = parse_formvars(environ)
    cb = form.get("callback", None)
    huc12 = form.get("huc12", "000000000000")[:12]
    mode = form.get("mode", "daily")
    fmt = form.get("format", "json")

    if fmt == "json":
        headers = [("Content-Type", "application/vnd.geo+json")]
    elif fmt == "xlsx":
        headers = [
            ("Content-Type", EXL),
            ("Content-disposition", f"attachment; Filename=dep{huc12}.xlsx"),
        ]
    start_response("200 OK", headers)

    mckey = f"/geojson/huc12_events/{huc12}/{mode}/{fmt}"
    mc = Client(["iem-memcached", 11211])
    res = mc.get(mckey)
    if res is None:
        res = do(huc12, mode, fmt)
        if fmt == "xlsx":
            mc.close()
            return [res]
        mc.set(mckey, res, 15)
    else:
        res = res.decode("utf-8")
    mc.close()
    if cb is not None:
        res = f"{cb}({res})"
    return [res.encode("ascii")]
Beispiel #12
0
def application(environ, start_response):
    """Answer request."""
    fields = parse_formvars(environ)
    sid = fields.get("station", "")[:4]
    if len(sid) == 3:
        sid = "K" + sid
    ts = parse_time(fields.get("ts"))
    pressure = int(fields.get("pressure", -1))
    cb = fields.get("callback")

    mckey = "/json/raob/%s/%s/%s?callback=%s" % (
        ts.strftime("%Y%m%d%H%M"),
        sid,
        pressure,
        cb,
    )
    mc = memcache.Client(["iem-memcached:11211"], debug=0)
    res = mc.get(mckey)
    if not res:
        res = run(ts, sid, pressure)
        mc.set(mckey, res)

    if cb is None:
        data = res
    else:
        data = "%s(%s)" % (html_escape(cb), res)

    headers = [("Content-type", "application/json")]
    start_response("200 OK", headers)
    return [data.encode("ascii")]
Beispiel #13
0
def application(environ, start_response):
    """ see how we are called """
    fields = parse_formvars(environ)
    dt = fields.get("dt", datetime.date.today().strftime("%Y-%m-%d"))
    ts = datetime.datetime.strptime(dt, "%Y-%m-%d")
    cb = fields.get("callback", None)
    fmt = fields.get("fmt", "geojson")

    headers = []
    if fmt == "geojson":
        headers.append(("Content-type", "application/vnd.geo+json"))
    else:
        headers.append(("Content-type", "text/plain"))

    mckey = "/geojson/cli/%s?callback=%s&fmt=%s" % (
        ts.strftime("%Y%m%d"),
        cb,
        fmt,
    )
    mc = memcache.Client(["iem-memcached:11211"], debug=0)
    res = mc.get(mckey)
    if not res:
        res = get_data(ts, fmt)
        mc.set(mckey, res, 300)
    if cb is None:
        data = res
    else:
        data = "%s(%s)" % (html_escape(cb), res)

    start_response("200 OK", headers)
    return [data.encode("ascii")]
Beispiel #14
0
def wsgiHandler (environ, start_response, service):
    from paste.request import parse_formvars
    try:
        path_info = host = ""


        if "PATH_INFO" in environ: 
            path_info = environ["PATH_INFO"]

        if "HTTP_X_FORWARDED_HOST" in environ:
            host      = "http://" + environ["HTTP_X_FORWARDED_HOST"]
        elif "HTTP_HOST" in environ:
            host      = "http://" + environ["HTTP_HOST"]

        host += environ["SCRIPT_NAME"]
        req_method = environ["REQUEST_METHOD"]
        fields = parse_formvars(environ)

        format, image = service.dispatchRequest( fields, path_info, req_method, host )
        headers = [('Content-Type',format)]
        if format.startswith("image/"):
            if service.cache.sendfile:
                headers.append(('X-SendFile', image))
            if service.cache.expire:
                headers.append(('Expires', email.Utils.formatdate(time.time() + service.cache.expire, False, True)))

        start_response("200 OK", headers)
        if service.cache.sendfile and format.startswith("image/"):
            return []
        else:
            return [image]

    except TileCacheException, E:
        start_response("404 Tile Not Found", [('Content-Type','text/plain')])
        return ["An error occurred: %s" % (str(E))]
    def identify(self, environ):
        query = parse_dict_querystring(environ)
        # If the extractor finds a special query string on any request,
        # it will attempt to find the values in the input body.
        if query.get(self.login_form_qs):
            form = parse_formvars(environ)
            from StringIO import StringIO
            # XXX we need to replace wsgi.input because we've read it
            # this smells funny
            environ['wsgi.input'] = StringIO()
            form.update(query)
            try:
                login = form['login']
                password = form['password']
                realm = form['realm']
            except KeyError:
                return None
            del query[self.login_form_qs]
            environ['QUERY_STRING'] = urllib.urlencode(query)
            environ['repoze.who.application'] = HTTPFound(
                                                    construct_url(environ))
            credentials = {'login':login, 'password':password, 'realm':realm}
            max_age = form.get('max_age', None)
            if max_age is not None:
                credentials['max_age'] = max_age
            return credentials

        return None
Beispiel #16
0
def application(environ, start_response):
    """Answer request."""
    fields = parse_formvars(environ)
    station = fields.get("station", "KDSM")[:4]
    year = int(fields.get("year", 2019))
    cb = fields.get("callback")
    fmt = fields.get("fmt", "json")

    headers = []
    if fmt == "json":
        headers.append(("Content-type", "application/json"))
    else:
        headers.append(("Content-type", "text/plain"))
    mckey = "/json/cli/%s/%s?callback=%s&fmt=%s" % (station, year, cb, fmt)
    mc = memcache.Client(["iem-memcached:11211"], debug=0)
    res = mc.get(mckey)
    if not res:
        res = get_data(station, year, fmt)
        mc.set(mckey, res, 300)
    if cb is None:
        data = res
    else:
        data = "%s(%s)" % (html_escape(cb), res)

    start_response("200 OK", headers)
    return [data.encode("ascii")]
Beispiel #17
0
    def identify(self, environ):
        query = parse_dict_querystring(environ)
        # If the extractor finds a special query string on any request,
        # it will attempt to find the values in the input body.
        if query.get(self.login_form_qs):
            form = parse_formvars(environ)
            from StringIO import StringIO
            # XXX we need to replace wsgi.input because we've read it
            # this smells funny
            environ['wsgi.input'] = StringIO()
            form.update(query)

            credentials = self._getCredentials(form)

            del query[self.login_form_qs]
            environ['QUERY_STRING'] = urllib.urlencode(query)
            environ['repoze.who.application'] = HTTPFound(
                                                    construct_url(environ))

            if 'login' not in credentials or 'password' not in credentials:
                return None

            return credentials

        return None
Beispiel #18
0
def application(environ, start_response):
    """Answer request."""
    fields = parse_formvars(environ)
    ts = fields.get("ts", None)
    lat = float(fields.get("lat", 0))
    lon = float(fields.get("lon", 0))
    if ts is None:
        ts = datetime.datetime.utcnow()
    else:
        ts = datetime.datetime.strptime(ts, "%Y%m%d%H%M")
    ts = ts.replace(tzinfo=pytz.UTC)

    cb = fields.get("callback")

    if lat != 0 and lon != 0:
        mckey = ("/json/spcwatch/%.4f/%.4f") % (lon, lat)
    else:
        mckey = "/json/spcwatch/%s" % (ts.strftime("%Y%m%d%H%M"),)
    mc = memcache.Client(["iem-memcached:11211"], debug=0)
    res = mc.get(mckey)
    if not res:
        if lat != 0 and lon != 0:
            res = pointquery(lon, lat)
        else:
            res = dowork(ts)
        mc.set(mckey, res)

    if cb is None:
        data = res
    else:
        data = "%s(%s)" % (html_escape(cb), res)

    headers = [("Content-type", "application/vnd.geo+json")]
    start_response("200 OK", headers)
    return [data.encode("ascii")]
Beispiel #19
0
    def identify(self, environ):
        path_info = environ['PATH_INFO']
        query = parse_dict_querystring(environ)

        # we've been asked to perform a login
        if self.login_handler_match(path_info):
            body = environ['wsgi.input'].read()
            stream = environ['wsgi.input'] = StringIO(body)
            form = parse_formvars(environ)
            form.update(query)
            stream.seek(0)

            # extract username and password
            for key in self.username:
                if key in form:
                    login = form[key]; break
            else:
                return None

            for key in self.password:
                if key in form:
                    password = form[key]; break
            else:
                return None

            return {
                'login': login,
                'password': password,
                }
Beispiel #20
0
def application(environ, start_response):
    """Answer request."""
    fields = parse_formvars(environ)

    year = int(fields.get("year", 2015))
    fmt = fields.get("format", "json")
    if fmt not in ["json", "html"]:
        headers = [("Content-type", "text/plain")]
        start_response("500 Internal Server Error", headers)
        msg = "Invalid format provided."
        return [msg.encode("ascii")]
    cb = fields.get("callback", None)
    headers = []
    if fmt == "json":
        headers.append(("Content-type", "application/json"))
    else:
        headers.append(("Content-type", "text/html"))

    mckey = "/json/vtec_max_etn/%s/%s" % (year, fmt)
    mc = memcache.Client(["iem-memcached:11211"], debug=0)
    res = mc.get(mckey)
    if res is None:
        res = run(year, fmt)
        mc.set(mckey, res, 3600)

    if cb is None:
        data = res
    else:
        data = "%s(%s)" % (html_escape(cb), res)

    start_response("200 OK", headers)
    return [data.encode("ascii")]
Beispiel #21
0
def application(environ, start_response):
    """Yawn"""
    form = parse_formvars(environ)
    year = int(form.get("year", 2018))
    etn = int(form.get("etn", 1))

    return [main(year, etn, start_response)]
Beispiel #22
0
    def identify(self, environ):
        query = parse_dict_querystring(environ)
        # If the extractor finds a special query string on any request,
        # it will attempt to find the values in the input body.
        if query.get(self.login_form_qs): 
            form = parse_formvars(environ)
            from StringIO import StringIO
            # XXX we need to replace wsgi.input because we've read it
            # this smells funny
            environ['wsgi.input'] = StringIO()
            form.update(query)
            try:
                login = form['login']
                password = form['password']
            except KeyError:
                return None
            del query[self.login_form_qs]
            environ['QUERY_STRING'] = urllib.urlencode(query)
            environ['repoze.who.application'] = HTTPFound(
                                                    construct_url(environ))
            credentials = {'login':login, 'password':password}
            max_age = form.get('max_age', None)
            if max_age is not None:
                credentials['max_age'] = max_age
            return credentials

        return None
Beispiel #23
0
def application(environ, start_response):
    """Go main go"""
    props = get_properties()
    form = parse_formvars(environ)
    if "address" in form:
        address = form["address"]
    elif "street" in form and "city" in form:
        address = "%s, %s" % (form["street"], form["city"])
    else:
        start_response("200 OK", [("Content-type", "text/plain")])
        return [b"APIFAIL"]

    req = requests.get(
        SERVICE,
        params=dict(
            address=address, key=props["google.maps.key2"], sensor="true"
        ),
        timeout=10,
    )
    data = req.json()
    sio = StringIO()
    if data["results"]:
        sio.write(
            "%s,%s"
            % (
                data["results"][0]["geometry"]["location"]["lat"],
                data["results"][0]["geometry"]["location"]["lng"],
            )
        )
    else:
        sio.write("ERROR")
    start_response("200 OK", [("Content-type", "text/plain")])
    return [sio.getvalue().encode("ascii")]
Beispiel #24
0
    def authenticate(self, environ, identity):
        log.info('In authenticate()')

        def set_error(msg):
            log.info(msg)
            err = 1
            environ['FAS_AUTH_ERROR'] = err
            # HTTPForbidden ?
            err_app = HTTPFound(err_goto + '?' + 'came_from=' +
                                quote_plus(came_from))
            environ['repoze.who.application'] = err_app

        err_goto = '/login'
        default_came_from = '/'
        if 'SCRIPT_NAME' in environ:
            sn = environ['SCRIPT_NAME']
            err_goto = sn + err_goto
            default_came_from = sn + default_came_from

        query = parse_dict_querystring(environ)
        form = parse_formvars(environ)
        form.update(query)
        came_from = form.get('came_from', default_came_from)

        try:
            auth_params = {
                'username': identity['login'],
                'password': identity['password']
            }
        except KeyError:
            try:
                auth_params = {'session_id': identity['session_id']}
            except:
                # On error we return None which means that auth failed
                set_error('Parameters for authenticating not found')
                return None

        try:
            user_data = self._retrieve_user_info(environ, auth_params)
        except AuthError as e:
            set_error('Authentication failed: %s' % exception_to_bytes(e))
            log.warning(e)
            return None
        except Exception as e:
            set_error('Unknown auth failure: %s' % exception_to_bytes(e))
            return None

        if user_data:
            try:
                del user_data[1]['password']
                environ['CSRF_AUTH_SESSION_ID'] = user_data[0]
                return user_data[1]['username']
            except ValueError:
                set_error('user information from fas not in expected format!')
                return None
            except Exception:
                pass
        set_error('An unknown error happened when trying to log you in.'
                  ' Please try again.')
        return None
Beispiel #25
0
def wsgiHandler (environ, start_response, service):
    from paste.request import parse_formvars
    try:
        path_info = host = ""


        if "PATH_INFO" in environ: 
            path_info = environ["PATH_INFO"]

        if "HTTP_X_FORWARDED_HOST" in environ:
            host      = "http://" + environ["HTTP_X_FORWARDED_HOST"]
        elif "HTTP_HOST" in environ:
            host      = "http://" + environ["HTTP_HOST"]

        host += environ["SCRIPT_NAME"]
        req_method = environ["REQUEST_METHOD"]
        fields = parse_formvars(environ)

        format, image = service.dispatchRequest( fields, path_info, req_method, host )
        start_response("200 OK", [('Content-Type',format)])
        return [image]

    except TileCacheException, E:
        start_response("404 Tile Not Found", [('Content-Type','text/plain')])
        return ["An error occurred: %s" % (str(E))]
Beispiel #26
0
def application(environ, start_response):
    """Answer request."""
    fields = parse_formvars(environ)
    pgconn = get_dbconn("afos")
    acursor = pgconn.cursor()
    pid = fields.get("product_id", "201302241937-KSLC-NOUS45-PNSSLC")
    cb = fields.get("callback")
    utc = datetime.datetime.strptime(pid[:12], "%Y%m%d%H%M")
    utc = utc.replace(tzinfo=pytz.UTC)
    pil = pid[-6:]
    root = {"products": []}

    acursor.execute(
        """
        SELECT data from products where pil = %s and
        entered = %s
        """,
        (pil, utc),
    )
    for row in acursor:
        root["products"].append({"data": row[0]})

    if cb is None:
        data = json.dumps(root)
    else:
        data = "%s(%s)" % (html_escape(cb), json.dumps(root))

    headers = [("Content-type", "application/json")]
    start_response("200 OK", headers)
    return [data.encode("ascii")]
    def __call__(self, environ, start_response):

        fields = parse_formvars(environ)
        obj = self.find_object(self.root, environ)
        response_body = obj(**fields.mixed())
        start_response('200 OK', [('content-type', 'text/html')])
        return [response_body]
Beispiel #28
0
def application(environ, start_response):
    status = '200 OK'
    output = b'Hello World!'
    if environ["REQUEST_METHOD"] == "POST":
        s = 3
        post_env = environ.copy()
        post_env['QUERY_STRING'] = ''
        form = cgi.FieldStorage(fp=environ['wsgi.input'],
                                environ=post_env,
                                keep_blank_values=True)
        #output = b''+form["word"].value
        #output = form.getvalue('word')
        #output = str.encode(output)
        content_length = int(environ['CONTENT_LENGTH'])
        output = environ['wsgi.input'].read(content_length)
        fields = request.parse_formvars(environ)
        field = fields['word']


##        output = str.encode(fields)
#temp = parse_qs(output)
#temp = parse_qs(environ['QUERY_STRING'])
#output = temp.get('word',[''])[0]
#output = str.encode(output)
#output = output.word.value #can't get it to work with forms :/
#print(b'bloop')
##    #form = cgi.FieldStorage()
##    #q = form.getvalue('q')
##
    response_headers = [('Content-type', 'text/plain'),
                        ('Content-Length', str(len(output)))]
    start_response(status, response_headers)
    return [output]
Beispiel #29
0
    def identify(self, environ):
        
        if environ['PATH_INFO'] == self.login_handler_path:
            ## We are on the URL where repoze.who processes authentication. ##
            form = parse_formvars(environ)
            try:
                credentials = {
                    'login': form['login'],
                    'password': form['password']
                    }
            except KeyError:
                credentials = None
            
            # destination is the post-login page
            destination = self._get_full_path(self.post_login_url, environ)
            # all variables from query string are kept in query string
            destination = self._replace_qs(destination, environ.get('QUERY_STRING'))

            environ['repoze.who.application'] = HTTPFound(destination)
            return credentials

        elif environ['PATH_INFO'] == self.logout_handler_path:
            ##    We are on the URL where repoze.who logs the user out.    ##
            # let's throw an exception to get challenged
            environ['repoze.who.application'] = HTTPUnauthorized()
            return None
Beispiel #30
0
def application(environ, start_response):
    """Answer request."""
    fields = parse_formvars(environ)

    feedtype = fields.get("feedtype", "IDS|DDPLUS").upper()[:32]
    cb = fields.get("callback")
    service = fields.get("service", "geojson")
    mckey = "/services/idd.py?service=%s&feedtype=%saa" % (service, feedtype)
    mc = memcache.Client(["localhost:11211"], debug=0)
    res = mc.get(mckey)
    if not res:
        if service == "geojson":
            res = run(feedtype)
            expire = 180
        else:
            res = stats()
            expire = 3600
        mc.set(mckey, res, expire)
    if cb is None:
        data = res
    else:
        data = "%s(%s)" % (cb, res)

    headers = [("Content-type", "application/vnd.geo+json")]
    start_response("200 OK", headers)
    return [data.encode("ascii", "ignore")]
Beispiel #31
0
 def __call__(self, environ, start_response):
     fields = parse_formvars(environ)
     print(fields)
     obj = self.find_object(self.root, environ)
     response_body = obj(**fields.mixed())
     start_response('200 OK', [('content-type', 'text/html')])
     return [response_body]
Beispiel #32
0
    def _parse_params(self, environ):
        # Try to find the parameters in various sources,
        # reflecting preference order:
        # Query string
        params = dict(parse_querystring(environ))
        # POST body
        request = Request(environ)
        if request.content_type == 'application/x-www-form-urlencoded':
            body = request.body
            params.update(parse_formvars(environ, include_get_vars=False))
            request.body = body
        # Authorization header
        auth_header = AUTHORIZATION(environ)
        if auth_header:
            try:
                params.update(oauth2.Request._split_header(auth_header))
            except:
                pass
        # Remove the non-oauth params
        if params:
            for key in params.keys():
                if not (key.startswith('oauth_') or key == 'realm'):
                    del params[key]

        return dict(params)
Beispiel #33
0
    def _parse_params(self, environ):
        # Try to find the parameters in various sources,
        # reflecting preference order:
        # Query string
        params = dict(parse_querystring(environ))
        # POST body
        request = Request(environ)
        if request.content_type == 'application/x-www-form-urlencoded':
            body = request.body
            params.update(parse_formvars(environ, include_get_vars=False))
            request.body = body
        # Authorization header
        auth_header = AUTHORIZATION(environ)
        if auth_header:
            try:
                params.update(oauth2.Request._split_header(auth_header))
            except:
                pass
        # Remove the non-oauth params
        if params:
            for key in params.keys():
                if not (key.startswith('oauth_') or key == 'realm'):
                    del params[key]

        return dict(params)
Beispiel #34
0
def get_context(environ):
    """Figure out the CGI variables passed to this script"""
    form = parse_formvars(environ)
    if "year" in form:
        year1 = form.get("year")
        year2 = year1
    else:
        year1 = form.get("year1")
        year2 = form.get("year2")
    month1 = form.get("month1")
    month2 = form.get("month2")
    day1 = form.get("day1")
    day2 = form.get("day2")
    hour1 = form.get("hour1")
    hour2 = form.get("hour2")
    minute1 = form.get("minute1")
    minute2 = form.get("minute2")

    sts = utc(int(year1), int(month1), int(day1), int(hour1), int(minute1))
    ets = utc(int(year2), int(month2), int(day2), int(hour2), int(minute2))
    if ets < sts:
        sts, ets = ets, sts
    radar = form.getall("radar")

    fmt = form.get("fmt", "shp")

    return dict(sts=sts, ets=ets, radar=radar, fmt=fmt)
Beispiel #35
0
def application(environ, start_response):
    """Answer request."""
    fields = parse_formvars(environ)
    if environ["REQUEST_METHOD"] not in ["GET", "POST"]:
        headers = [("Content-type", "text/plain")]
        start_response("500 Internal Server Error", headers)
        data = "Invalid Request"
        return [data.encode("ascii")]

    cb = fields.get("callback")

    mckey = "/json/tms.json"
    mc = memcache.Client(["iem-memcached:11211"], debug=0)
    res = mc.get(mckey)
    if not res:
        res = run()
        mc.set(mckey, res, 15)
    if cb is None:
        data = res
    else:
        data = "%s(%s)" % (html_escape(cb), res)

    headers = [("Content-type", "application/json")]
    start_response("200 OK", headers)
    return [data.encode("ascii")]
Beispiel #36
0
def application(environ, start_response):
    """Answer request."""
    fields = parse_formvars(environ)
    if environ["REQUEST_METHOD"] not in ["GET", "POST"]:
        headers = [("Content-type", "text/plain")]
        start_response("500 Internal Server Error", headers)
        data = "Invalid Request"
        return [data.encode("ascii")]

    operation = fields.get("operation", "list")
    callback = fields.get("callback")
    data = ""
    if callback is not None:
        data += "%s(" % (html_escape(callback), )
    if operation == "list":
        data += json.dumps(list_files(fields))
    elif operation == "available":
        data += json.dumps(available_radars(fields))
    elif operation == "products":
        data += json.dumps(list_products(fields))
    if callback is not None:
        data += ")"

    headers = [("Content-type", "application/json")]
    start_response("200 OK", headers)
    return [data.encode("ascii")]
Beispiel #37
0
def application(environ, start_response):
    """Answer request."""
    fields = parse_formvars(environ)

    station = fields.get("station", "AMW")
    network = fields.get("network", "IA_ASOS")
    date = fields.get("date", "2016-01-01")
    cb = fields.get("callback", None)

    hostname = os.environ.get("SERVER_NAME", "")
    mckey = "/json/obhistory/%s/%s/%s" % (station, network, date)
    mc = memcache.Client(["iem-memcached:11211"], debug=0)
    res = mc.get(mckey) if hostname != "iem.local" else None
    if not res:
        res = workflow(station, network, date).replace("NaN", "null")
        mc.set(mckey, res, 3600)

    if cb is None:
        data = res
    else:
        data = "%s(%s)" % (html_escape(cb), res)

    headers = [("Content-type", "application/json")]
    start_response("200 OK", headers)
    return [data.encode("ascii")]
Beispiel #38
0
def application(environ, start_response):
    """Do Workflow"""
    headers = [("Content-type", "application/vnd.geo+json")]

    form = parse_formvars(environ)
    group = form.get("group", "coop")
    cb = form.get("callback", None)
    dt = form.get("dt", datetime.date.today().strftime("%Y-%m-%d"))
    ts = datetime.datetime.strptime(dt, "%Y-%m-%d")
    ts = ts.replace(hour=12, tzinfo=pytz.utc)

    mckey = "/geojson/7am/%s/%s" % (dt, group)
    mc = memcache.Client(["iem-memcached:11211"], debug=0)
    res = mc.get(mckey)
    if not res:
        res = router(group, ts)
        mc.set(mckey, res, 15)

    if cb is None:
        data = res
    else:
        data = "%s(%s)" % (html_escape(cb), res)

    start_response("200 OK", headers)
    return [data.encode("ascii")]
Beispiel #39
0
    def identify(self, environ):
        path_info = environ['PATH_INFO']
        query = parse_dict_querystring(environ)

        # This will handle the logout request.
        if path_info == self._logout_url:
            # set in environ for self.challenge() to find later
            environ['repoze.who.application'] = HTTPUnauthorized()
            return None
        elif path_info == self._login_url:
            form = parse_formvars(environ)
            form.update(query)
            try:
                credentials = {
                    'login': form['login'],
                    'password': form['password']
                }
            except KeyError:
                credentials = None

            def auth_resp(environ, start_response):
                import json
                resp = {"success": True}

                resp_str = json.dumps(resp)

                content_length = CONTENT_LENGTH.tuples(str(len(resp_str)))
                content_type = CONTENT_TYPE.tuples('application/json')
                headers = content_length + content_type
                start_response('200 OK', headers)
                return [resp_str]

            environ['repoze.who.application'] = auth_resp
            return credentials
def application(environ, start_response):
    """Answer request."""
    fields = parse_formvars(environ)
    state = fields.get("state", "IA")[:2]
    year = int(fields.get("year", 2015))
    phenomena = fields.get("phenomena", "SV")[:2]
    significance = fields.get("significance", "W")[:1]
    cb = fields.get("callback")

    mckey = "/json/vtec_events_bystate/%s/%s/%s/%s" % (
        state,
        year,
        phenomena,
        significance,
    )
    mc = memcache.Client(["iem-memcached:11211"], debug=0)
    res = mc.get(mckey)
    if not res:
        res = run(state, year, phenomena, significance)
        mc.set(mckey, res, 60)

    if cb is None:
        data = res
    else:
        data = "%s(%s)" % (html_escape(cb), res)

    headers = [("Content-type", "application/json")]
    start_response("200 OK", headers)
    return [data.encode("ascii")]
def mainApp(environ, start_response):
    global requestCount
    requestCount += 1
    fields = parse_formvars(environ)
    method = environ["REQUEST_METHOD"]
    path = (environ.get("SCRIPT_NAME", "") + environ.get("PATH_INFO", ""))
    options = environ.get("options", {})
    host = environ["SERVER_NAME"]
    port = environ["SERVER_PORT"]
    #print "host='%s', port='%s'" % (host,port)
    errors = environ["wsgi.errors"]
    args = fields.mixed()
    filenames = {}
    for k, v in args.iteritems():
        if type(v) is types.InstanceType:
            filenames[k] = v
    cookies = environ.get("HTTP_COOKIE", "")
    if cookies.find("=")!=-1:
        cookies = dict([cookie.split("=") for cookie in cookies.split("; ")])
    else:
        cookies = {}
    sessionId = cookies.get("SESSION", None)
    requestData = serverRequestData(path=path, method=method, args=args, \
                    session=None, sessionId=sessionId, filenames=filenames, port=port)
    responseData = serverResponseData()
    
    threadName = threading.currentThread().getName()
    timeStr = time.strftime("%H:%M.%S")
    
    if path.startswith("/testing/"):
        getTestData(fields, environ, requestData, responseData, cookies)
    else:
        global iceRequest
        if iceRequest is None:
            baseUrl = "http://%s:%s/" % (host, port)
            iceRequest = ice_request.iceRequest(baseUrl=baseUrl)
            IceCommon.isServer = True
        gTime.setup()
        gTime.mark("Start request")
        
        iceRequest.processRequest(requestData, responseData)    #, request
        #responseData.contentType = "text/html"
        #responseData.write("TestingTwo")
        
        gTime.stopAll()
        if gTime.isHtmlPage:
            if gTime.enabled:
                print gTime
            else:
                print "Done."
        
    
    contentType = responseData.contentType
    data = responseData.data
    #contentType = "text/html"
    #data = "Testing one"
    start_response("200 OK", [("content-type", contentType), \
                                ("Set-Cookie", "SESSION=%s" % requestData.sessionId)])
    return [data]
Beispiel #42
0
 def caller(func, *args, **kargs):
     perm()
     # Remove login credentials
     form = parse_formvars(request.environ, include_get_vars=True)
     if form.pop('do_login__', None):
         form.pop('login', None)
         form.pop('password', None)
     return func(*args, **kargs)
Beispiel #43
0
def app(environ, start_response):
    fields = parse_formvars(environ)
    if environ["REQUEST_METHOD"] == "POST":
        start_response("200 OK", [("content-type", "text/html")])
        return ["Hello", fields["name"], "!"]
    else:
        start_response("200 OK", [("content-type", "text/html")])
        return ['<form method="POST">Name:<input type="text" ' 'name="name"><input type="submit"></form>']
Beispiel #44
0
def app(environ, start_response):
	fields = parse_formvars(environ)

	path = environ['PATH_INFO']
	Separators = re.compile('/')
	PathList = Separators.split(path)
	#print len(PathList)


	if path == "/":

		start_response('200 OK', [('content-type', 'text/html')])
		return ['<center> Welcome to Hot-Pi. </br> Call set/pi#/<number>/ to set a temp </br> Call get/pi# to get the temp</br> Call get_plan/pi# to get the policy</center>']

	elif PathList[1] == "set":

		pinum = PathList[2]
		temp = float(PathList[3])
		start_response('200 OK', [('content-type', 'text/xml')])
		pydict[pinum] = temp

		return ['<pi>'+'<pinumber>'+str(pinum)+'</pinumber><temp>'+ str(temp)+'</temp></pi>']


	elif PathList[1] == "set_ambient_temperature":

		pinum = PathList[2]
		temp = float(PathList[3])
		start_response('200 OK', [('content-type', 'text/xml')])
		pydictA[pinum] = temp

		return ['<pi>'+'<pinumber>'+str(pinum)+'</pinumber><AmbientTemp>'+ str(temp)+'</AmbientTemp></pi>']


	elif PathList[1] == "get":

		start_response('200 OK', [('content-type', 'text/xml')])

		pinum = PathList[2]
		if pinum in pydict:
			return [str(pydict[pinum])] #['<pi>'+'<pinumber>'+str(pinum)+'</pinumber><temp>'+ str(pydict[pinum])+'</temp></pi>']
		else:
			return ['<pi>'+'<pinumber>'+str(pinum)+'</pinumber><temp>NO TEMP</temp></pi>']

	elif PathList[1] == "get_plan":

		start_response('200 OK', [('content-type', 'text/xml')])

		pinum = PathList[2]
		if pinum in pydict:
			print getWeatherUndergroundForecastArray()
			return ['<pi>'+'<pinumber>'+str(pinum)+'</pinumber><temp>'+ str(pydict[pinum])+'</temp></pi>']
		else:
			return ['<pi>'+'<pinumber>'+str(pinum)+'</pinumber><temp>NO Policy</temp></pi>']

	else:
		start_response('200 OK', [('content-type', 'text/xml')])
		return ['<error> Not a valid request. For information about our API service please check our web site at http://www.intelligence.tuc.gr/renes. </error>']
Beispiel #45
0
    def authenticate(self, environ, identity):
        log.info('In authenticate()')

        def set_error(msg):
            log.info(msg)
            err = 1
            environ['FAS_AUTH_ERROR'] = err
            # HTTPForbidden ?
            err_app = HTTPFound(err_goto + '?' +
                                'came_from=' + quote_plus(came_from))
            environ['repoze.who.application'] = err_app

        err_goto = '/login'
        default_came_from = '/'
        if 'SCRIPT_NAME' in environ:
            sn = environ['SCRIPT_NAME']
            err_goto = sn + err_goto
            default_came_from = sn + default_came_from

        query = parse_dict_querystring(environ)
        form = parse_formvars(environ)
        form.update(query)
        came_from = form.get('came_from', default_came_from)

        try:
            auth_params = {'username': identity['login'],
                           'password': identity['password']}
        except KeyError:
            try:
                auth_params = {'session_id': identity['session_id']}
            except:
                # On error we return None which means that auth failed
                set_error('Parameters for authenticating not found')
                return None

        try:
            user_data = self._retrieve_user_info(environ, auth_params)
        except AuthError as e:
            set_error('Authentication failed: %s' % exception_to_bytes(e))
            log.warning(e)
            return None
        except Exception as e:
            set_error('Unknown auth failure: %s' % exception_to_bytes(e))
            return None

        if user_data:
            try:
                del user_data[1]['password']
                environ['CSRF_AUTH_SESSION_ID'] = user_data[0]
                return user_data[1]['username']
            except ValueError:
                set_error('user information from fas not in expected format!')
                return None
            except Exception:
                pass
        set_error('An unknown error happened when trying to log you in.'
                  ' Please try again.')
        return None
Beispiel #46
0
    def __call__(self, environ, start_response):

        # log form fields
        pprint(parse_formvars(environ))

        # response
        # TODO: to format as ushahidi do
        start_response('200 OK', [('content-type', 'application/json')])

        #pprint(environ)
        #import pdb; pdb.set_trace()

        if environ.get('REQUEST_METHOD','') == 'POST':
            result = { "payload": {
                          "domain": environ.get('HTTP_ORIGIN'),
                          "success":"true"
                        },
                        "error":{ "code":"0",
                                  "message":"No Error"}
                    }
        elif environ.get('REQUEST_METHOD','') == 'GET' and \
             environ.get('QUERY_STRING', '') == 'task=categories':
            result = { "payload": {
                          "domain": environ.get('HTTP_ORIGIN'),
                          "categories":[
                              {"category":
                                  { "id":"1",
                                    "parent_id":"0",
                                    "title":"Category 1",
                                    "description":"Category 1",
                                    "color":"9900CC","position":"0"}},
                              {"category":
                                  { "id":"2",
                                    "parent_id":"0",
                                    "title":"Category 2",
                                    "description":"Category 2",
                                    "color":"3300FF",
                                    "position":"0"}},
                              {"category":
                                  { "id":"3",
                                    "parent_id":"0",
                                    "title":"Category 3",
                                    "description":"Category 3",
                                    "color":"663300",
                                    "position":"0"}},
                              {"category":
                                  { "id":"4",
                                    "parent_id":"0",
                                    "title":"Trusted Reports",
                                    "description":"Reports from trusted reporters",
                                    "color":"339900","position":"0"}}
                          ]},
                        "error":{"code":"0","message":"No Error"}
                    }
        else:
            result = {"status": "ok", "now": int(time.time())}

        return json.dumps(result)
Beispiel #47
0
    def __call__(self, env, start_response):
        '''Handle HTTP request per `WSGI`__.

        __ http://www.python.org/dev/peps/pep-0333/

        :param env: access to HTTP request
        :type env: Dict[String, String]
        :param start_response: access to start HTTP response
        :type start_response: (String, Seq[(String, String)]) => Unit
        :rtype: Iterable[String]

        .. note:: We ignore extra HTTP request parameters.
        '''
        if env['REQUEST_METHOD'] != 'POST':
            start_response('405 method not allowed',
                           [('content-type', 'text/plain')])
            log.error('app called with non-POST method: %s',
                      env['REQUEST_METHOD'])
            return ['Bzzt. We only do POST.']

        args = parse_formvars(env)

        identity = lambda x: x

        try:
            [username, password] = [
                args.pop(k) for k in self.mandatory_params]
            log.info('Request from %s.', username)
            mvalues = dict([
                (k, (txform or identity)(args[k]))
                for (k, txform) in self._sub_params])
        except (KeyError, ValueError) as ex:
            start_response('400 bad request',
                           [('content-type', 'text/plain')])
            log.error('incorrect credentials for %s', username)
            return ['Incorrect parameters:', str(ex)]

        self._log_request(username, dict(args))
        try:
	    #log.info('env=%s', env)
	    #log.info('start_response=%s', start_response)
	    #log.info('username=%s', username)
	    #log.info('password=%s', password)
	    #log.info('mvalues=%s', mvalues)
            return self._subApp(env, start_response,
                                username, password,
                                **mvalues)
        except NotAuthorized:
            start_response('403 not authorized',
                           [('content-type', 'text/plain')])
            return ['incorrect credentials']
        # For debugging, catch IOError instead
        except Exception, ex:
            log.critical('Error:', exc_info=ex)
            start_response('500 I tried.',
                           [('content-type', 'text/plain')])
            return ['error:', str(ex)]
def handle_post_request(environ, start_response):
    if environ["PATH_INFO"] in router:
        path = environ["PATH_INFO"]
        fields = parse_formvars(environ)
        start_response("200 OK", [("content-type", "text/html")])
        return router[path].post(fields)
    else:
        start_response("200 OK", [("content-type", "text/html")])
        return ["ERROR 404"]
Beispiel #49
0
 def application(environ, start_response):
     form = request.parse_formvars(environ, include_get_vars=True)
     status = "200 OK"
     form["environ"] = environ
     try:
         res = func(*args, **form.mixed())
     except ValueError, ve:
         status = "500 Server Error"
         res = "<html>There was an error: %s</html>" % html_quote(ve)
Beispiel #50
0
 def identify(self, environ):
     form = parse_formvars(environ, include_get_vars=False)
     if form.get(self.login_form_qs, None):
         try:
             login = form['login']
             password = form['password']
         except KeyError:
             return None
         return dict(login=login, password=password)
Beispiel #51
0
def app(environ, start_response):
    fields = parse_formvars(environ)
    if environ['REQUEST_METHOD'] == 'POST':
        start_response('200 OK', [('content-type', 'text/html')])
        return ['<h1>Hello, ', fields['name'], '!</h1>']
    else:
        start_response('200 OK', [('content-type', 'text/html')])
        return ['<form method="POST">Name: <input type="text" '
                'name="name"><input type="submit"></form>']
Beispiel #52
0
def analyse(env):
    if (env['REQUEST_METHOD'] == 'POST'):
        fields = request.parse_formvars(env)
        input_data = json.loads(fields.get('input', '[]'))
        
        # I dunno lol
        return json.dumps({"decision": "REPORT", "cheatPercent": len(input_data)})
    else:
        return json.dumps({"decision": "NO-ACTION", "cheatPercent": 0})
Beispiel #53
0
 def start_tests(self,environ,start_response):
     param_string = parse_formvars(environ)['params']
     try:
         self.parse_settings(param_string)
         SeleniumStarter().start()
         start_response('200 Ok', [('content-type', 'text/html')])
         return ["OK"]
     except Exception as e:
         start_response('200 Ok', [('content-type', 'text/html')])
         return ["ERROR"]
Beispiel #54
0
def wsgiHandler (environ, start_response, service):
    from paste.request import parse_formvars

    try:
        path_info = host = ""


        if "PATH_INFO" in environ:
            path_info = environ["PATH_INFO"]

        if "HTTP_X_FORWARDED_HOST" in environ:
            host      = "http://" + environ["HTTP_X_FORWARDED_HOST"]
        elif "HTTP_HOST" in environ:
            host      = "http://" + environ["HTTP_HOST"]

        host += environ["SCRIPT_NAME"]
        req_method = environ["REQUEST_METHOD"]
        fields = parse_formvars(environ)

        format, image = service.dispatchRequest( fields, path_info, req_method, host )
        headers = [('Content-Type',format)]

        if format.startswith("image/"):
            if service.cache.sendfile:
                headers.append(('X-SendFile', image))
            if service.cache.expire:
                headers.append(('Expires', email.Utils.formatdate(time.time() + service.cache.expire, False, True)))

        # Hack start. Expire added to layers
        if format.startswith("image/"):
            if service.cache.sendfile:
                headers.append(('X-SendFile', image))
            layer_expire = None
            if fields.has_key('layers') or fields.has_key('LAYERS'):
                layers = fields.get('layers', fields.get('LAYERS'))
                # single layers only
                if not ',' in layers:
                    layer = service.layers[layers]
                    if layer.expire:
                        layer_expire = long(layer.expire)
                        headers.append(('Expires', email.Utils.formatdate(time.time() + layer_expire, False, True)))
            if service.cache.expire and not layer_expire:
                headers.append(('Expires', email.Utils.formatdate(time.time() + service.cache.expire, False, True)))
        # Hack end

        start_response("200 OK", headers)
        if service.cache.sendfile and format.startswith("image/"):
            return []
        else:
            return [image]

    except TileCacheException, E:
        start_response("404 Tile Not Found"+str(E), [('Content-Type','text/plain')])
        return ["An error occurred: %s" % (str(E))]
Beispiel #55
0
def define(env):
    if (env['REQUEST_METHOD'] == 'POST'):
        fields = request.parse_formvars(env)
        input_data = json.loads(fields.get('input', '[]'))
        
        client = MongoClient()
        db = client.tensorFlow
        collection = db.gameData
        collection.insert(input_data)
        return json.dumps({"nbAdded": len(input_data)})
    else:
        return json.dumps({"nbAdded": 0})
Beispiel #56
0
 def __call__(self, environ, start_response):
     fields = parse_formvars(environ)
     obj = self.find_object(self.root, environ)
     response_body = "as per usual"
     if obj:
         try:
             response_body = obj(**fields.mixed())
             start_response('200 OK', [('content-type', 'text/html')])
         except:
             start_response('400 Bad Request', [('content-type', 'text/html')])
     else:
         start_response('400 Bad Request', [('content-type', 'text/html')])
     return response_body
Beispiel #57
0
def render(environ,start_response):
  fields = parse_formvars(environ)
  start_response('200 OK', [('content-type', 'text/html')])
  ##
  env = jinja2.Environment(loader=jinja2.DictLoader(tmpls))
  ctx = dict()
  ctx["title"] = "Processes"
  #ps = sp.Popen(["ps","aux"],stdout=sp.PIPE)
  ps = sp.Popen(["ps","-A","-F","-w","--sort=-rss"],stdout=sp.PIPE)
  ctx["pslist"] = cgi.escape(ps.communicate()[0])  
  ##
  apage = env.get_template("page_pslist")
  return apage.render(ctx)