Пример #1
0
def remote_webapp (environ, start_response):
    routes = {
        'buttons': view_buttons,
        'inputs': view_inputs,
        'press': lambda: press(shift_path_info (environ)),
        'status': projector_status,
        'input': lambda: set_input(shift_path_info (environ)),
        'on': on,
        'off': off,
        '': index
    }

    result = None
    base_path = shift_path_info (environ)
    if base_path not in routes:
        status = '404 Not Found'
        headers = [('Content-type', 'text/html')]
        result = str(WebException (status))
    else:
        try:
            handler = routes[base_path]
            result = handler()
            status = '200 OK'  # HTTP Status
            if type(result) != str and type(result) != unicode:
                headers = [('Content-type', 'text/html')] 
            else:
                headers = [('Content-type', 'application/json')]
        except WebException, ex:
            status = ex.code
            headers = [('Content-type', 'text/html')] 
            result = str(ex)
        except:
Пример #2
0
 def __call__(self, environ, start_response):
     if self.prefix and not environ['PATH_INFO'].startswith(self.prefix):
         return self._error(start_response, 400, "bad request")
     shift_path_info(environ)
     qs = parse_qs(environ.get('QUERY_STRING'), strict_parsing=True)
     if 'auth_token' not in qs:
         if self.need_auth(environ):
             return self._error(start_response, 401, "unauthorized",
                                "Missing Authentication Token.")
     else:
         token = qs['auth_token'][0]
         try:
             self.verify_token(environ, token)
         except Unauthorized:
             return self._error(
                 start_response, 401, "unauthorized",
                 "Incorrect password or login.")
         # remove auth token from query string.
         del qs['auth_token']
         qs_str = ''
         if qs:
             qs_str = reduce(lambda x, y: '&'.join([x, y]),
                             map(lambda (x, y): '='.join([x, str(y)]),
                                 qs.iteritems()))
         environ['QUERY_STRING'] = qs_str
     return self.app(environ, start_response)
Пример #3
0
 def dispatch(self, env, start_resp):
     "Dispatch both on resources and sub applications"
     reqmeth = env['REQUEST_METHOD']
     script_name = env.get('SCRIPT_NAME', '')
     path_info = env.get('PATH_INFO', '')
     fullpath = script_name + path_info
     for (path, meth), obj in self._registry.iteritems():
         mo = re.match(path, path_info)
         print 'checking %s with %s, %s' % (path_info, path, mo)
         if mo:
             if not isinstance(obj, self.Binding): # assume WSGI app
                 shift_path_info(env) # subdispatch
                 res = obj
             else: # true resource
                 resource = obj.resource
                 if resource is None:
                     res = Response('Unbound Resource', '500 ERR')
                 elif meth not in ('ALL', reqmeth):
                     res = Response('Method Not Allowed', '405 ERR')
                 else: # call the resource
                     res = safecall(
                         self.call_hook, resource, self.Request(env), 
                         mo.groups(), obj.content_type, path)
             break
     else: # no match, no break
         res = Response('Unknown resource %r' % fullpath, '404 Not Found')
     return res(env, start_resp)
Пример #4
0
def static(environ, start_response):
    # shift PATH_INFO /static/foo ----> /foo
    # then skip first '/'
    # and merge with static_root
    shift_path_info(environ)
    filename = os.path.abspath(os.path.join(static_root,
                                            environ['PATH_INFO'][1:]))
    return sendfile(fname, start_response)
Пример #5
0
 def __call__(self, environ, start_response):
     """Dispatch to the method named by the next bit of PATH_INFO."""
     name = shift_path_info(dict(SCRIPT_NAME=environ["SCRIPT_NAME"], PATH_INFO=environ["PATH_INFO"]))
     callable = getattr(self, name or "index", None)
     if callable is not None and self._is_exposed(callable):
         shift_path_info(environ)
         return callable(environ, start_response)
     else:
         return self._not_found(environ, start_response)
Пример #6
0
def select_app(environ,start_response):
	active_app=apps[None]
	path=environ['PATH_INFO']
	for app in apps:
		if app is None: continue
		if path=='/'+app or path.startswith('/'+app+'/'):
			shift_path_info(environ)
			active_app=apps[app]
			break
	return active_app(environ,start_response)
Пример #7
0
 def __call__(self, environ, start_response):
     """do WSGI request dispatching"""
     spi = int(self.config.get("shift_path_info", 0))
     for i in range(0,spi):
         shift_path_info(environ)
     request = self.request_class(environ)
     try:
         response = self.process_request(request)
     except Exception, e:    
         response = self.handle_exception(request, e)
Пример #8
0
def simple_dispatch(environ, start_response):
    status = '200 OK' # HTTP Status
    headers = [('Content-type', 'text/html')] # HTTP Headers
    start_response(status, headers)
    environ["parsed_params"] = urlparse.parse_qs(environ["QUERY_STRING"],keep_blank_values=True)
    # a wsgi app is supposed to return an iterable;
    # yielding lets you stream, rather than generate everything at once.
#    yield repr(environ)
    dbname = shift_path_info(environ)
    myname = environ["SCRIPT_NAME"]
    print >> environ['wsgi.errors'], dbname
    if not dbname: return
    else:
        dbfile = "/var/lib/philologic/databases/" + dbname + "/toms.db"
    toms = SqlToms(dbfile,7)
    print >> environ['wsgi.errors'],"opened toms"
    obj = []
    count = 0

    while True:
        p = shift_path_info(environ)
        if p:
            obj.append(p)
        else:
            break
    yield "looking up %s" % str(obj)
    filename = ""
    start = 0
    end = 0
    length = 0
    for r in range(1,len(obj) + 1):
        parent = obj[:r]
        yield str(parent)
        if parent in toms:
            yield "retreiving %s" % repr(parent)
            o = toms[parent]
            filename = o["filename"] or filename
            start = o["start"] or start
            end = o["end"] or end
    yield repr((filename,length,start,end))
    file = "/var/lib/philologic/databases/%s/TEXT/%s" % (dbname,filename)
    fh = open(file)
    fh.seek(start)
    chunk = fh.read(end - start)
    if "word_offset" in environ["parsed_params"]:
        word_offset =  int(environ["parsed_params"]["word_offset"][0])
        if word_offset >= start and word_offset <= end:
            breakpoint = word_offset - start
            left = chunk[:breakpoint]
            rest = chunk[breakpoint:]
            word,right = re.split("[\s.;:,<>?!]",rest,1)    
            yield f.format(left + "<span rend='preserve' class='hilite'>" + word + "</span> " + right)
            return
    yield f.format(chunk)
Пример #9
0
 def handle_request(self, env, start):
     parts = env["PATH_INFO"].split("/")[1:]
     locale = None
     if len(parts):
         locale = to_gettext_locale(parts[0])
     if locale:
         env = dict(env)
         shift_path_info(env)
         self.maybe_apply_translation(env, locale)
         if "translation" in env or locale == NULL_LOCALE:
             return self.file_server.handle_request(env, start)
Пример #10
0
 def app(environ, start_response):
     parts = environ['PATH_INFO'].split('/')[1:]
     if len(parts) >= 2 and parts[0] == multiplex_dir:
         app = multiplex_apps.get(parts[1])
         if len(parts) > 2 and app:
             shift_path_info(environ)
             shift_path_info(environ)
             return app(environ, start_response)
         else:
             start_response('404 Not Found',
                            [('Content-Type', 'text/plain')])
             return ['Not Found']
     return default_app(environ, start_response)
Пример #11
0
 def __call__(self, environ, start_response):
     """Dispatch to the method named by the next bit of PATH_INFO."""
     # Predict the path shift to get the callable name.
     name = shift_path_info(dict(SCRIPT_NAME=environ['SCRIPT_NAME'],
                                 PATH_INFO=environ['PATH_INFO']))
     # If there is such a callable and it is exposed...
     callable = getattr(self, name or 'index', None)
     if callable is not None and self._is_exposed(callable):
         # ... shift the path and call the callable.
         shift_path_info(environ)
         return callable(environ, start_response)
     else:
         # ... or call self._not_found (
         return self._not_found(environ, start_response)
Пример #12
0
    def __init__(self, environ):
        ctrlr_class = shift_path_info(environ)
        ctrlr_action = shift_path_info(environ)
        
        if ctrlr_class == '' or ctrlr_class == None:
            ctrlr_class = 'home'
        
        if ctrlr_action == '' or ctrlr_action == None:
            ctrlr_action = 'index'

        # Class Members
        self.ctrlr_file = 'controller.' + ctrlr_class
        self.ctrlr_class = ctrlr_class
        self.ctrlr_action = ctrlr_action
Пример #13
0
def application(env, start):
    env['htmlpad.etherpad'] = 'etherpad.mozilla.org:9000'
    ## ianb: cwd sensitive:
    static_files_dir = os.path.join('htmlpad.org', 'static-files')

    # Clearing the template cache on each request allows developers
    # to iterate quickly.
    htmlpad.template_cache = {}

    if env['PATH_INFO'].startswith('/static-files/'):
        shift_path_info(env)
        return static_file(env, start, static_files_dir)
    else:
        return htmlpad.application(env, start)
Пример #14
0
def strip_app(environ,start_response):
	if environ['PATH_INFO']=='/':
		environ['PATH_INFO']='/index.html'
	if environ['PATH_INFO'].startswith('/api'):
		shift_path_info(environ)
	else:
		try:
			filename=os.path.join(os.getcwd(),'client','html',environ['PATH_INFO'][1:])
			f=open(filename,'rb')
		except fnfError:
			start_response("404 NOT FOUND",[])
			return []
		start_response("200 OK",[])
		return f
	return matomat_wsgi.application(environ,start_response)
Пример #15
0
def __call__(environ, start_response):
    """Handle a HTTP request."""
    from wsgiref.util import application_uri, shift_path_info
    from urlparse import urljoin

    try:
        import swat
    except ImportError as e:
        print("NO SWAT: %r" % e)
        have_swat = False
    else:
        have_swat = True

    orig_path = environ['PATH_INFO']
    name = shift_path_info(environ)

    if name == "":
        if have_swat:
            start_response('301 Redirect',
                [('Location', urljoin(application_uri(environ), 'swat')),])
            return []
        else:
            return render_placeholder(environ, start_response)
    elif have_swat and name == "swat":
        return swat.__call__(environ, start_response)
    else:
        status = '404 Not found'
        response_headers = [('Content-type', 'text/html')]
        start_response(status, response_headers)
        return ["The path %s (%s) was not found" % (orig_path, name)]
Пример #16
0
    def handle(self, request):
        '''Handle a request, parse and validate arguments and dispatch the request'''

        entity = pop_path_info(request.environ)
        if not entity:
            return self.handle_index()

        if entity not in [ 'release', 'release-group' ]:
            return Response (
                status=400, response=
                "Only release and release-group entities are currently supported")

        req_mbid = shift_path_info(request.environ)
        if not req_mbid:
            return Response (status=400, response="no MBID specified.")
        if not re.match('[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$', req_mbid):
            return Response (status=400, response="invalid MBID specified.")

        mbid = self.resolve_mbid (entity, req_mbid)
        filename = pop_path_info(request.environ)

        if entity == 'release-group':
            return self.handle_release_group (request, mbid, filename)
        else:
            return self.handle_release (request, mbid, filename)
Пример #17
0
Файл: web.py Проект: dpla/akara
    def post_resource():
        ctype = environ.get('CONTENT_TYPE', 'application/unknown')
        clen = int(environ.get('CONTENT_LENGTH', None))
        if not clen:
            start_response("411 Length Required", [('Content-Type','text/plain')])
            return ["Length Required"]
        key = shift_path_info(environ)
        now = datetime.now().isoformat()
        md = {
            CREATED: now,
            UPDATED: now,
            CONTENT_LENGTH: clen,
            CONTENT_TYPE: ctype,
        }
        #md = self.standard_index
        content = environ['wsgi.input'].read(clen)
        id = drv.create_resource(content, metadata=md)
        msg = 'Adding %i' % id
        new_uri = str(id)

        headers = [('Content-Type', 'text/plain')]
        headers.append(('Location', new_uri))
        headers.append(('Content-Location', new_uri))

        #environ['akara.etag'] = compute_etag(content)
        headers.append(('Content-Length', str(len(msg))))
        start_response("201 Created", headers)
        
        return msg
Пример #18
0
def app(environ, start_response):
    path = shift_path_info(environ)
    print(path)
    if path == 'api':
        return mxreverse(environ, start_response)
    start_response('301 Moved', [('Location', '/page/index.html')])
    return [b'']
Пример #19
0
def get_file(environ, start_response):
    '''
    GETting the collection resource itself returns a simple file listing.
    
    GETting a subsidiary resource returns the file
    '''
    print >> sys.stderr, 'GRIPPO', environ['PATH_INFO']
    if environ['PATH_INFO'] == '/':
        #Get index
        start_response(status_response(httplib.OK), [("Content-Type", "text/plain")])
        return '\n'.join(os.listdir(BASE)) + '\n'
    resource_fname = shift_path_info(environ)
    #Not needed because the shift_path_info will ignore anything after the '/' and they'll probably get a 404
    #'..' will not be expanded by os.path.join
    #if "/" in resource_fname:
    #    start_response(status_response(httplib.BAD_REQUEST), [("Content-Type", "text/plain")])
    #    return 'You must not include forward slashes in your request (%s)'%resource_fname
    resource_path = os.path.join(BASE, resource_fname)
    print >> sys.stderr, 'Getting the file at: ', resource_fname
    try:
        f = open(resource_path, 'rb')
        #FIXME: do it chunk by chunk
        rbody = f.read()
        #FIXME: work out content type mappings (perhaps by file extension)
        start_response(status_response(httplib.OK), [("Content-Type", "text/plain")])
        return rbody
    except IOError:
        rbody = four_oh_four.substitute(fronturl=request_uri(environ), backurl=resource_fname)
        start_response(status_response(httplib.NOT_FOUND), [("Content-Type", "text/html")])
        return rbody
Пример #20
0
def switch(env, conn):
    id_ = shift_path_info(env)
    if id_ != None and id_ != "":
        switch = conn.db.rfstats.find_one(id_)
        return (200, json.dumps(switch["data"], default=bson.json_util.default), JSON)
    else:
        return (404, "Switch not specified", JSON)
Пример #21
0
def messages(env, conn):
    channel = shift_path_info(env)
    if channel != None and channel != "":
        # TODO: escape parameters
        messages = []
        try:
            table = getattr(conn.db, channel);
        except:
            return (404, "Invalid channel", JSON)

        request = parse_qs(env["QUERY_STRING"])
        limit = 50
        query = {}
        if "limit" in request:
            limit = request["limit"][0]
        if "types" in request:
            types = request["types"][0]
            query["$or"] = []
            for type_ in types.split(","):
                try:
                    value = int(type_)
                except:
                    continue
                query["$or"].append({"type": value})

        for doc in table.find(query, limit=limit, sort=[("$natural", pymongo.DESCENDING)]):
            messages.append(doc)

        return (200, json.dumps(messages, default=bson.json_util.default), JSON)


    else:
        return (404, "Channel not specified", JSON)
Пример #22
0
def bookings_room_page(environ):
    """Provide a list of bookings by room, showing user and date/time
    """
    room_id = int(shift_path_info(environ))
    room = get_room(room_id)
    html = "<table>"
    html += "<tr><td>User</td><td>Date</td><td>Times</td></tr>"
    for booking in get_bookings_for_room(room_id):
        html += "<tr><td>{user_name}</td><td>{booked_on}</td><td>{booked_from} - {booked_to}</td></tr>".format(
            user_name=booking['user_name'],
            booked_on=booking['booked_on'],
            booked_from=booking['booked_from'] or "",
            booked_to=booking['booked_to'] or ""
        )
    html += "</table>"
    html += "<hr/>"
    html += '<form method="POST" action="/add-booking">'
    html += '<input type="hidden" name="room_id" value="{room_id}"/>'.format(room_id=room_id)
    html += '<label for="user_id">User:</label>&nbsp;<select name="user_id">'
    for user in get_users():
        html += '<option value="{id}">{name}</option>'.format(**user)
    html += '</select>'
    html += '&nbsp;|&nbsp;'
    html += '<label for="booked_on">On</label>&nbsp;<input type="text" name="booked_on" value="{today}"/>'.format(today=datetime.date.today())
    html += '&nbsp;<label for="booked_from">between</label>&nbsp;<input type="text" name="booked_from" />'
    html += '&nbsp;<label for="booked_to">and</label>&nbsp;<input type="text" name="booked_to" />'
    html += '<input type="submit" name="submit" value="Add Booking"/></form>'
    return page("Bookings for %s" % room['name'], html)
Пример #23
0
 def checkShift(self,sn_in,pi_in,part,sn_out,pi_out):
     env = {'SCRIPT_NAME':sn_in,'PATH_INFO':pi_in}
     util.setup_testing_defaults(env)
     self.assertEqual(util.shift_path_info(env),part)
     self.assertEqual(env['PATH_INFO'],pi_out)
     self.assertEqual(env['SCRIPT_NAME'],sn_out)
     return env
Пример #24
0
    def handle(self, request):
        """Handle a request, parse and validate arguments and dispatch the request."""
        entity = pop_path_info(request.environ)

        if request.method == "OPTIONS":
            return self.handle_options(request, entity)

        if not entity:
            return self.handle_index()
        elif entity == "robots.txt":
            return self.handle_robots()
        elif entity == "main.css":
            return self.handle_css()
        elif entity == "img":
            return self.handle_svg_img(pop_path_info(request.environ))
        elif entity == "js":
            return self.handle_js(pop_path_info(request.environ))
        elif entity == "api":
            return self.handle_api(request)

        self.validate_entity(entity)

        req_mbid = shift_path_info(request.environ)
        self.validate_mbid(req_mbid)

        mbid = self.resolve_mbid(entity, req_mbid)
        filename = pop_path_info(request.environ)

        if entity == "release-group":
            return self.handle_release_group(request, mbid, filename)
        else:
            return self.handle_release(request, mbid, filename)
Пример #25
0
 def serve_under_prefix(self, environ, start_response):
     prefix = shift_path_info(environ)
     if prefix != self.PREFIX:
         start_response('404 Not Found', [])
         return []
     else:
         return self.application(environ, start_response)
Пример #26
0
 def checkShift(self, sn_in, pi_in, part, sn_out, pi_out):
     env = {"SCRIPT_NAME": sn_in, "PATH_INFO": pi_in}
     util.setup_testing_defaults(env)
     self.assertEqual(util.shift_path_info(env), part)
     self.assertEqual(env["PATH_INFO"], pi_out)
     self.assertEqual(env["SCRIPT_NAME"], sn_out)
     return env
Пример #27
0
def webapp(environ, start_response):
    """Serve simple pages, based on whether the URL requests
    users, rooms or bookings. For now, just serve the Home page
    """
    setup_testing_defaults(environ)

    #
    # Assume we're going to serve a valid HTML page
    #
    status = '200 OK'
    headers = [('Content-type', 'text/html; charset=utf-8')]
    #
    # Pick up the first segment on the path and pass
    # the rest along.
    #
    # ie if we're looking for /users/1/bookings,
    # param1 will be "users", and the remaining path will
    # be "/1/bookings".
    #
    param1 = shift_path_info(environ)
    if param1 == "":
        data = index_page(environ)
    elif param1 == "users":
        data = users_page(environ)
    elif param1 == "rooms":
        data = rooms_page(environ)
    else:
        status = '404 Not Found'
        data = "Not Found: %s" % param1

    start_response(status, headers)
    return [data.encode("utf-8")]
Пример #28
0
 def __call__(self, env, resp):
     name = shift_path_info(env)
     app = self.pages.get(name)
     if not app:
         resp('404 ERR', [('Content-type', 'text/plain')])
         return ['Page %s not found' % name]
     return app(env, resp)
Пример #29
0
 def _wsgi_app(self, environ, start_response):
     if self._apps:
         app_route = shift_path_info(environ)
         if app_route in self._apps:
             environ['SCRIPT_NAME'] = ''
             return self._apps[app_route](environ, start_response)
     start_response('404 NOT FOUND', [('Content-type', 'text/plain'), ])
     return ['no application deployed'.encode('utf-8')]
Пример #30
0
def application(env, resp):
    """Return the JQuery-enhanced HTML page  and dispatch on the 
    static directory too"""
    name = shift_path_info(env)
    if name == 'static':
        return static(env, resp)
    resp('200 OK', [('Content-type', 'text/html')])
    return [html % (js, body)]
Пример #31
0
def scope_app(environ, start_response):
    root = shift_path_info(environ)
    index, count = map(int, root.split('of'))

    url = 'http:/' + environ['PATH_INFO']
    if 'QUERY_STRING' in environ:
        url += '?' + environ['QUERY_STRING']

    start_response("200 OK", [('Content-Type', "text/xml")])
    return parse_scope(url, index, count)
Пример #32
0
def Dispatcher(env, resp):
    '''Send requests to handlers based on the first path component.'''
    page = util.shift_path_info(env)
    if page in DISPATCH:
        return DISPATCH[page](env, resp)
    else:
        status = '404 Not Found'
        headers = [('Content-type', 'text/plain')]
        resp(status, headers)
        return ['Not Found: ' + page]
Пример #33
0
 def handle(environ, start_response):
     chunk_num = shift_path_info(environ)
     msg = self.messages[chunk_msg]
     chunks = msg.setdefault("chunks", {})
     with closing(stream_from_wsgi_environ(environ)) as stream:
         data = stream.read()
     chunks[chunk_num] = zlib.compress(data) if not environ.get(
         'HTTP_CONTENT_ENCODING', None) else data
     start_response('202 Accepted', [])
     return []
Пример #34
0
 def __call__(self, environ, start_response):
     orig_path = environ.get('PATH_INFO')
     orig_script_name = environ.get('SCRIPT_NAME')
     path_part = (shift_path_info(environ) or '').lower()
     if path_part in self._other_apps:
         return self._other_apps[path_part](environ, start_response)
     else:
         environ['PATH_INFO'] = orig_path
         environ['SCRIPT_NAME'] = orig_script_name
         return self._root_app(environ, start_response)
Пример #35
0
    def shift(self):
        environ = self.environ
        part = shift_path_info(environ)
        if part or part is None:
            return part

        # We got an empty string, so we just hit a trailing slash;
        # replace it with the default method:
        environ['SCRIPT_NAME'] += self.policy.defaultMethod
        return self.policy.defaultMethod
Пример #36
0
 def _wsgi_app(self, environ, start_response):
     if self._apps:
         app_route = shift_path_info(environ)
         if app_route in self._apps:
             environ['SCRIPT_NAME'] = ''
             return self._apps[app_route](environ, start_response)
     start_response('404 NOT FOUND', [
         ('Content-type', 'text/plain'),
     ])
     return ['no application deployed'.encode('utf-8')]
Пример #37
0
def philo_dispatcher(environ, start_response):
    environ["parsed_params"] = urlparse.parse_qs(environ["QUERY_STRING"],
                                                 keep_blank_values=True)
    cgi = environ["parsed_params"]

    dbname = shift_path_info(environ)
    environ["philologic_dbname"] = dbname
    myname = environ["SCRIPT_NAME"]
    print >> sys.stderr, myname
    dbfile = "/var/lib/philologic/databases/" + dbname
    print >> sys.stderr, dbfile
    try:
        db = PhiloDB(dbfile, 7)
    except OperationalError:
        return

    environ["philologic_dbname"] = dbname

    if environ["PATH_INFO"]:
        print >> sys.stderr, "scanning path info"
        scanned = environ["PATH_INFO"].split("/")
        scanned = [i for i in scanned if i is not ""]
        print >> sys.stderr, "%s scanned." % repr(scanned)
        if "children" in scanned:
            environ["philologic_id"] = environ["PATH_INFO"]
            return object_children_service(environ, start_response)
        elif "form" in scanned:
            return form_service(environ, start_response)
        elif scanned:
            environ["philologic_id"] = environ["PATH_INFO"]
            print >> sys.stderr, "passing to object formatter"
            return object_service(environ, start_response)

    if "query" in cgi and cgi["query"][0]:
        if "report" in cgi:
            if cgi["report"][0] == "frequency":
                if "json" in cgi:
                    if "field" in cgi and cgi["field"][0] == "collocates":
                        from colloc_json_service import colloc_json_service
                        return colloc_json_service(environ, start_response)
                    return freq_json_service(environ, start_response)
                return freq_service(environ, start_response)
            elif cgi["report"][0] == "collocation":
                if "json" in cgi:
                    from colloc_json_service import colloc_json_service
                    return colloc_json_service(environ, start_response)
                return colloc_service(environ, start_response)
            return conc_service(environ, start_response)
        elif "colloc_filter" in cgi:
            return colloc_filter_service(environ, start_response)
        else:
            return conc_service(environ, start_response)

    else:
        return cite_list_service(environ, start_response)
Пример #38
0
    def handle_options(self, request, entity):
        """Repond to OPTIONS requests with a status code of 200 and the allowed
        request methods.
        """
        if request.environ["SERVER_PROTOCOL"] != "HTTP/1.1":
            # OPTIONS does not exist in HTTP/1.0
            raise NotImplemented()
        if entity:
            if not entity == '*':
                self.validate_entity(entity)
            elif pop_path_info(request.environ) is not None:
                # There's more than a single asterisk in the request uri
                raise BadRequest()
            else:
                return Response(status=200,
                                headers=[("Allow", "GET, HEAD, OPTIONS")])

            req_mbid = shift_path_info(request.environ)
            self.validate_mbid(req_mbid)

            image_id = shift_path_info(request.environ)

            if image_id and image_id is not None:
                image_id = splitext(image_id)[0]
                _split = image_id.split('-')
                if len(_split) > 0:
                    id_text = _split[0]

                try:
                    int(id_text)
                except ValueError:
                    if id_text not in ('front', 'back'):
                        raise BadRequest()
                    else:
                        get_sentry().captureException()

                if len(_split) > 1:
                    size = _split[1]
                    if size not in ('250', '500'):
                        raise BadRequest()

        return Response(status=200, headers=[("Allow", "GET, HEAD, OPTIONS")])
Пример #39
0
 def __call__(self, environ, start_response):
     if self.prefix and not environ['PATH_INFO'].startswith(self.prefix):
         return self._error(start_response, 400, "bad request")
     auth = environ.get('HTTP_AUTHORIZATION')
     if not auth:
         return self._error(start_response, 401, "unauthorized",
                            "Missing Basic Authentication.")
     scheme, encoded = auth.split(None, 1)
     if scheme.lower() != 'basic':
         return self._error(start_response, 401, "unauthorized",
                            "Missing Basic Authentication")
     user, password = encoded.decode('base64').split(':', 1)
     try:
         self.verify_user(environ, user, password)
     except Unauthorized:
         return self._error(start_response, 401, "unauthorized",
                            "Incorrect password or login.")
     del environ['HTTP_AUTHORIZATION']
     shift_path_info(environ)
     return self.app(environ, start_response)
Пример #40
0
def dump(env, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    yield b'<pre>'
    for key in env:
        yield key.encode('utf-8') + b':' + str(env[key]).encode('utf-8') + b'\n'

    yield b'\n'
    yield b'request_uri=' + util.request_uri(env).encode('utf-8') + b'\n'
    yield b'application_uri=' + util.application_uri(env).encode('utf-8') + b'\n'

    path = util.shift_path_info(env)
    while (path):
        yield b'path=' + path.encode('utf-8') + b'\n'
        path = util.shift_path_info(env)

    args = parse.parse_qs(env['QUERY_STRING'])
    for key in args:
        yield key.encode('utf-8') + b': ' + b' '.join([value.encode('utf-8') for value in args[key]])

    return []
Пример #41
0
 def endpoint_lookup(self, environ, start_response):
     org_code = shift_path_info(environ)
     workflow_id = shift_path_info(environ)
     if not org_code or not workflow_id:
         return _not_found(environ, start_response)
     result = {
         "query_id":
         "{ts:%Y%m%d%H%M%S%f}_{rnd:06x}_{ts:%s}".format(
             ts=datetime.datetime.now(), rnd=random.randint(0, 0xffffff)),
         "results": [{
             "address":
             "{}HC001".format(org_code),
             "description":
             "{} {} endpoint".format(org_code, workflow_id),
             "endpoint_type":
             "MESH"
         }]
     }
     return _ok('application/json', [json.dumps(result).encode('UTF-8')],
                start_response)
Пример #42
0
def bookings_page(environ):
    """Provide a list of all bookings by a user or room, showing
    the other thing (room or user) and the date/time
    """
    category = shift_path_info(environ)
    if category == "user":
        return bookings_user_page(environ)
    elif category == "room":
        return bookings_room_page(environ)
    else:
        return "No such booking category"
Пример #43
0
def rezervacije_page(environ):
   
    category = shift_path_info(environ)
    if not category:
        return all_rezervacije_page(environ)
    elif category == "korisnik":
        return rezervacije_korisnik_page(environ)
    elif category == "restoran":
        return rezervacije_restorani_page(environ)
    else:
        return "page not found"
Пример #44
0
    def _dispatch(self, env, start_response):

        part = shift_path_info(env)

        method = getattr(
            self, '_%s_%s' % (env['REQUEST_METHOD'], part.replace('.', '_')),
            None)
        if len(env['PATH_INFO'].split('/')) == 1 and method:
            return method(env, start_response)

        start_response(utils.status(404), [])
        return []
Пример #45
0
    def handle(self, environ):
        '''Handle a request, parse and validate arguments and dispatch the request'''

        entity = shift_path_info(environ)
	if not entity:
            return self.handle_index()

        mbid = shift_path_info(environ)
        if not mbid:
            return ["400 no MBID specified.", ""]
        if not re.match('[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$', mbid):
            return ["400 invalid MBID specified.", ""]

        filename = shift_path_info(environ)
        if not filename:
            return self.handle_dir(entity, mbid)

        if not entity or entity != 'release':
            return ["400 Only release entities are supported currently", ""]

        (code, response) = self.handle_redirect(entity, mbid.lower(), filename.encode('utf8')) 
        return code, response
Пример #46
0
    def get_resource():
        key = shift_path_info(environ)

        content1, metadata = drv.get_resource(key)
        if content1 is None:
            #404 error
            start_response('404 Not Found', [('content-type', 'text/html')])
            response = four_oh_four.substitute(url=request_uri(environ))
            return response

        start_response('200 OK',
                       [('content-type', str(metadata[CONTENT_TYPE]))])
        return content1.encode('utf-8')
Пример #47
0
def handle_namespace(environ, computer, namespace):
    if not namespace:
        wmi_connection = wmi.WMI(computer, namespace="root/cimv2")
        for setting in wmi_connection.Win32_WMISetting():
            namespace = setting.ASPScriptDefaultNamespace
            break

    wmi_connection = wmi.WMI(computer, namespace=namespace, find_classes=True)
    wmi_class = shift_path_info(environ)
    if wmi_class:
        doc_wmi_class(computer, namespace, wmi_class, wmi_connection)
    else:
        doc_namespace(computer, namespace, wmi_connection)
Пример #48
0
    def outbox(self, environ, start_response):
        chunk_msg = shift_path_info(environ)
        if chunk_msg == 'tracking':
            return self.tracking(environ, start_response)
        if chunk_msg:
            return self.upload_chunk(chunk_msg)(environ, start_response)
        try:
            recipient = environ["HTTP_MEX_TO"]
            sender = environ["HTTP_MEX_FROM"]
            mailbox_id = environ["mesh.mailbox"]
            assert mailbox_id == sender
        except Exception as e:
            traceback.print_exc()
            start_response("417 Expectation Failed",
                           [('Content-Type', 'application/json')])
            return [
                json.dumps({
                    "errorCode": "02",
                    "errorDescription": str(e),
                    "errorEvent": "COLLECT",
                    "messageID": "99999"
                })
            ]

        mailbox = self.messages.setdefault(recipient, OrderedDict())
        with closing(stream_from_wsgi_environ(environ)) as stream:
            data = stream.read()
        if not data:
            start_response("417 Expectation Failed",
                           [('Content-Type', 'application/json')])
            return [
                json.dumps({
                    "errorCode": "02",
                    "errorDescription":
                    "Data file is missing or inaccessible.",
                    "errorEvent": "COLLECT",
                    "messageID": "99999"
                }).encode("utf-8")
            ]
        headers = {
            _OPTIONAL_HEADERS[key]: value
            for key, value in environ.items() if key in _OPTIONAL_HEADERS
        }
        msg_id = self.make_message_id()
        headers['Mex-MessageID'] = msg_id
        mailbox[msg_id] = {"headers": headers, "data": data}
        self.messages[msg_id] = mailbox[msg_id]
        return _ok("application/json",
                   [json.dumps({
                       "messageID": msg_id
                   }).encode("UTF-8")], start_response)
Пример #49
0
def target(environ):
    wiki_id = shift_path_info(environ)
    full_incoming_request = request_uri(environ)
    if wiki_id not in TARGET_WIKIS:
        raise BadTargetError(fronturl=request_uri(environ), target=wiki_id)
    original_page = join(TARGET_WIKIS[wiki_id].rstrip('/') + '/',
                         environ['PATH_INFO'].lstrip('/'))
    #relative_to_wrapped = relativize(, full_incoming_request)
    if len(environ['PATH_INFO']) > 0:
        wrapped_wiki_base = full_incoming_request[:-len(environ['PATH_INFO'])]
    else:
        wrapped_wiki_base = full_incoming_request
    return wiki_id, TARGET_WIKIS[wiki_id], TARGET_WIKI_OPENERS.get(
        wiki_id), original_page, wrapped_wiki_base
Пример #50
0
def bookings_room_page(environ):
    """Provide a list of bookings by room, showing user and date/time
    """
    room_id = int(shift_path_info(environ))
    html = "<table>"
    html += "<tr><td>User</td><td>Date</td><td>Times</td></tr>"
    for booking in get_bookings_for_room(room_id):
        html += "<tr><td>{user_name}</td><td>{booked_on}</td><td>{booked_from} - {booked_to}</td></tr>".format(
            user_name=booking['user_name'],
            booked_on=booking['booked_on'],
            booked_from=booking['booked_from'] or "",
            booked_to=booking['booked_to'] or "")
    html += "</table>"
    return page("Bookings for room %d" % room_id, html)
Пример #51
0
def bookings_user_page(environ):
    """Provide a list of bookings by user, showing room and date/time
    """
    user_id = int(shift_path_info(environ))
    html = "<table>"
    html += "<tr><td>Room</td><td>Date</td><td>Times</td></tr>"
    for booking in get_bookings_for_user(user_id):
        html += "<tr><td>{room_name}</td><td>{booked_on}</td><td>{booked_from} - {booked_to}</td></tr>".format(
            room_name=booking['room_name'],
            booked_on=booking['booked_on'],
            booked_from=booking['booked_from'] or "",
            booked_to=booking['booked_to'] or "")
    html += "</table>"
    return page("Bookings for user %d" % user_id, html)
Пример #52
0
def webapp(environ, start_response):
    """Serve simple pages, based on whether the URL requests
    users, rooms or bookings. For now, just serve the Home page
    """
    setup_testing_defaults(environ)

    #
    # Assume we're going to serve a valid HTML page
    #
    status = '200 OK'
    headers = [('Content-type', 'text/html; charset=utf-8')]
    #
    # Pick up the first segment on the path and pass
    # the rest along.
    #
    # ie if we're looking for /users/1/bookings,
    # param1 will be "users", and the remaining path will
    # be "/1/bookings".
    #
    param1 = shift_path_info(environ)
    if param1 == "":
        data = index_page(environ)
    elif param1 == "users":
        data = users_page(environ)
    elif param1 == "rooms":
        data = rooms_page(environ)
    elif param1 == "bookings":
        data = bookings_page(environ)
    elif param1 == "add-user":
        add_user(environ)
        status = "301 Redirect"
        headers.append(("Location", "/users"))
        data = ""
    elif param1 == "add-room":
        add_room(environ)
        status = "301 Redirect"
        headers.append(("Location", "/rooms"))
        data = ""
    elif param1 == "add-booking":
        add_booking(environ)
        status = "301 Redirect"
        headers.append(("Location", environ.get("HTTP_REFERER", "/bookings")))
        data = ""
    else:
        status = '404 Not Found'
        data = "Not Found: %s" % param1

    start_response(status, headers)
    return [data.encode("utf-8")]
Пример #53
0
def scope_app(environ, start_response):
    root = shift_path_info(environ)
    if root == 'obj':
        return object_app(environ, start_response)

    search_params = {}  # parse query string
    qs = environ.get('QUERY_STRING', "").split('&')
    ql = [map(unquote_plus, comp.split('=', 1)) for comp in qs if '=' in comp]
    search_params.update(ql)

    search_params['media'] = "photos"
    search_params['sort'] = "date-posted-asc"

    start_response("200 OK", [('Content-Type', "text/xml")])
    return FlickrObjList(search_params)
Пример #54
0
 def getsubpage(self, root, env, resp):
     script_name = util.shift_path_info(env)
     if not script_name:  # We've arrived!
         resp('200 OK', [('content-type', 'text/html')])
         return root
     try:
         page = getattr(root, script_name)
     except AttributeError:
         resp('404 Not Found', [('content-type', 'text/plain')])
         return lambda: ['missing page %r' % script_name]
     exposed = getattr(page, 'exposed', False)
     if not exposed:
         resp('404 Not Found', [('content-type', 'text/plain')])
         return lambda: ['%r is not exposed!' % script_name]
     return self.getsubpage(page, env, resp)
Пример #55
0
 def __call__(self, environ, start_response):
     headers = []
     for middleware in self.settings.MIDDLEWARE_CLASSES:
         Middleware = dynamic_import(middleware)
         middleware_instance = Middleware(environ, start_response)
         if middleware_instance.is_valid():
             return middleware_instance.get_response()
     url = "/{0}".format(shift_path_info(environ))
     headers.append(('Content-type', 'text/html'))
     view = self.urls.get(url)
     if view:
         start_response("200 OK", headers)
         return view()
     start_response("404 Not Found", headers)
     return "Erro 404 - Page not found"
Пример #56
0
    def _dispatch(self, env, start_response):

        if len(env['PATH_INFO'].split('/')) > 2:
            part = shift_path_info(env)

            if part in self.services:
                return self.services[part]._dispatch(env, start_response)

            elif part in self.devices:
                return self.devices[part]._dispatch(env, start_response)

            start_response(utils.status(404), [])
            return []

        return super(BaseDevice, self)._dispatch(env, start_response)
Пример #57
0
def app(environ, start_response):
    computer = shift_path_info(environ)
    if computer == "favicon.ico":
        start_response("404 Not Found", [("Content-Type", "text/plain")])
        return []
    elif computer:
        start_response("200 OK",
                       [("Content-Type", "text/html; charset=utf-8")])
        handle_computer(environ, computer)
        return (unicode(d).encode("utf8") + unicode("\n").encode("utf8")
                for d in doc)
    else:
        start_response("301 Moved Permanently",
                       [("Location", "/localhost"),
                        ("Content-Type", "text/plain")])
        return ["Redirected to /localhost"]
Пример #58
0
def scope_app(environ, start_response):
    root = shift_path_info(environ)
    if root == 'obj':
	return object_app(environ, start_response)

    querydict = {}
    qs = environ.get('QUERY_STRING', '').split('&')
    ql = [ map(unquote_plus, comp.split('=', 1)) for comp in qs if '=' in comp ]
    for k,v in ql: querydict.setdefault(k, []).append(v)

    image_id = 'com.ibm.mirage.sha1id/' + root.lower()

    start_response("200 OK", [('Content-Type', "text/xml")])
    return MirageListVerbose(image_id,
			     querydict.get('path', ['*']),
			     querydict.get('user', None))
Пример #59
0
 def web_handler(self, environ, start_response):
   """Application called when we interact with the webserver."""
   pth = shift_path_info(environ)
   if pth == '':#Root page
     response_body = self.index()
   else:
     response_body = self.device_operation(pth, environ)
   
   status = '200 OK'
   
   # Now content type is text/html
   response_headers = [('Content-Type', 'text/html'),
                  ('Content-Length', str(len(response_body)))]
   start_response(status, response_headers)
   
   return [response_body]
Пример #60
0
        def handle(environ, start_response):
            requested_mailbox = shift_path_info(environ)
            authorization_header = environ.get("HTTP_AUTHORIZATION", "")
            if not authorization_header.startswith("NHSMESH "):
                return _not_authorized(environ, start_response)

            auth_data = authorization_header[8:]
            mailbox, nonce, nonce_count, ts, hashed = auth_data.split(":")
            expected_password = "******"
            hash_data = ":".join(
                [mailbox, nonce, nonce_count, expected_password, ts])
            myhash = hmac.HMAC(self._shared_key, hash_data.encode("ASCII"),
                               sha256).hexdigest()
            if myhash == hashed and mailbox == requested_mailbox:
                environ["mesh.mailbox"] = mailbox
                return handler(environ, start_response)
            else:
                return _forbidden(environ, start_response)