Пример #1
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)]
Пример #2
0
    def get_schema(self, lang):
	## 0.  memcache hit -> response
	schema = self.cache_get(lang)
	if schema:
	    return schema
	url = self.format_url(lang)

	## 1. mmemcache miss -> url fetch
	try:
	    schema = jsonloads(urlopen(url).read())
	    app_uri = application_uri(self.request.environ)
	    img_fixes = self.img_fixes
	    for item in schema['result']['items']['item']:
		if item['defindex'] in img_fixes:
		    item['image_url'] = app_uri + img_fixes[item['defindex']]
	except (Exception, ), exc:
	    ## 1a.  fetch failure -> history lookup
	    storage = History.all().filter('url =', url).get()
	    if storage:
		## this assumes that the schema has already been
		## parsed and fixed at least one time.
		schema = jsonloads(storage.payload)
		self.cache_set(schema, lang)
	    else:
		## 1b. total failure
		schema = {}
Пример #3
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)]
Пример #4
0
    def handle_application_error(self, environ, start_response):
        status = "500 Internal Server Error"
        headers = Headers([])

        # Package the exception info as into a special header and
        # send it to the client
        type, exc, tb = sys.exc_info()

        tbfile = StringIO()

        traceback.print_exc(file=tbfile)
        headers['Content-Type'] = 'text/plain; charset=utf-8'

        LOG.debug("Packing traceback context into debug header: %s",
                  self.debug_header)
        debug_header = self.pack_header(Traceback(tb))
        LOG.debug("Debug header (%d bytes): %s",
                  len(debug_header), debug_header)
        headers[self.debug_header] = debug_header

        app_uri = application_uri(environ)
        headers["Location"] = app_uri[:-1] + self.debug_uri

        start_response(status, headers.items())
        return [tbfile.getvalue().encode('utf-8')]
Пример #5
0
def get_request_info(environ: EnvironType) -> ContextType:
    """Extract logging context friendly request and server information.

    Extract all values related to server and to the specific request, such as
    `SERVER_NAME`, `SERVER_PORT`, `PATH_INFO`, `QUERY_STRING`.

    The names in the resulting dictionary are the same, but converted to
    lowercase and prefixed with "request_".

    In addition to these values, two calculated values are also added -
    `request_uri` and `request_application_uri`. These values are calculated
    using `wsgiref.util` functions `request_uri` (with `include_query=True`) and
    `application_uri`.

    :param environ: WSGI environ (as it is passed to WSGI application).
    :return: A logging context friendly mapping of request and server
        information.
    """
    request_info = {
        "request_method": unicode(environ["REQUEST_METHOD"]),
        "request_script_name": unicode(environ["SCRIPT_NAME"]),
        "request_path_info": unicode(environ["PATH_INFO"]),
        "request_query_string": unicode(environ.get("QUERY_STRING", "")),
        "request_server_name": unicode(environ["SERVER_NAME"]),
        "request_server_port": unicode(environ["SERVER_PORT"]),
        "request_server_protocol": unicode(environ["SERVER_PROTOCOL"]),
        "request_content_type": unicode(environ.get("CONTENT_TYPE", "")),
        "request_content_length": unicode(environ.get("CONTENT_LENGTH", "")),
        "request_uri": unicode(util.request_uri(environ, include_query=True)),
        "request_application_uri": unicode(util.application_uri(environ)),
    }
    return request_info
Пример #6
0
    def serve(environ, start_response):

        root = root_url.lstrip('/')

        tail, get = (util.request_uri(environ).split('?') + [''])[:2]
        tail = tail[len(util.application_uri(environ)):]

        result = []

        content_type = 'text/plain'
        status = '200 OK'
        if tail.startswith(root):

            tail = tail[len(root):]

            get = parse_qs(get)
            method = environ['REQUEST_METHOD']

            text, post = '', {}
            if method == 'POST':
                text = environ['wsgi.input'].\
                    read(int(environ.get('CONTENT_LENGTH', 0)))
                post = parse_qs(text)

            response = server.process_request(
                Request(tail, text, get, post, {}))

            content_type = response.content_type
            status = get_http_response_code(response)
            result.append(response.text)

        headers = [('Content-type', content_type)]
        start_response(status, headers)

        return result
Пример #7
0
    def serve(environ, start_response):

        root = root_url.lstrip('/')

        tail, get = (util.request_uri(environ).split('?') + [''])[:2]
        tail = tail[len(util.application_uri(environ)):]

        result = []

        content_type = 'text/plain'
        status = '200 OK'
        if tail.startswith(root):

            tail = tail[len(root):]

            get = parse_qs(get)
            method = environ['REQUEST_METHOD']

            text, post = '', {}
            if method == 'POST':
                text = environ['wsgi.input'].\
                    read(int(environ.get('CONTENT_LENGTH', 0)))
                post = parse_qs(text)

            response = server.process_request(
                Request(tail, text, get, post, {}))

            content_type = response.content_type
            status = get_http_response_code(response)
            result.append(response.text)

        headers = [('Content-type', content_type)]
        start_response(status, headers)

        return result
Пример #8
0
Файл: _wsgi.py Проект: Kjir/pyws
    def serve(environ, start_response):

        root = root_url.lstrip("/")

        tail, get = (util.request_uri(environ).split("?") + [""])[:2]
        tail = tail[len(util.application_uri(environ)) :]

        result = []

        content_type = "text/plain"
        status = "200 OK"
        if tail.lstrip("/").startswith(root):

            tail = tail[len(root) :]

            get = parse_qs(get)
            method = environ["REQUEST_METHOD"]

            text, post = "", {}
            if method == "POST":
                text = environ["wsgi.input"].read(int(environ.get("CONTENT_LENGTH", 0)))
                post = parse_qs(text)

            response = server.process_request(Request(tail, text, get, post, {}))

            content_type = response.content_type
            status = get_http_response_code(response)
            result.append(response.text)

        headers = [("Content-type", content_type)]
        start_response(status, headers)

        return result
Пример #9
0
def view_static(environ, start_response):
    if environ['REQUEST_METHOD'].lower() == 'get':
        uri = request_uri(environ, include_query=False).replace(
            application_uri(environ), '')
        start_response('200 OK,',
                       [('Content-Type', f'text/{uri.split(".")[1]}')])
        with open(uri, 'rt') as response:
            return response.read()
    def redirect_to(self, env, to, params={}):
        home_url = util.application_uri(env)[:-1]
        redirect_url = home_url + to
        status = '303 See Other'
        headers = [('Content-type', 'text/html'), ('Location', redirect_url)]
        headers = set_cookie(headers, self.cookie)
        body = ["<p>リダイレクト中</p>".encode('utf-8')]

        return status, headers, body
Пример #11
0
    def __call__(self, environ, start_response):
        base = application_uri(environ)

        url = urljoin(base, self.path)

        res = Response(url, status=self.code)

        res.headers['location'] = url

        return res(environ, start_response)
Пример #12
0
    def __call__(self, environ, start_response):
        path = environ["PATH_INFO"]
        qs = environ["QUERY_STRING"]

        if path == "/":
            # Step 1: Get a request token. This is a temporary token that is used for
            # having the user authorize an access token and to sign the request to obtain
            # said access token.

            appuri = application_uri(environ)
            if not appuri.endswith("/"):
                appuri += "/"
            oauth_callback = "%scallback" % appuri

            url = "%s?%s" % (self.request_token_url, urllib.urlencode({"oauth_callback": oauth_callback}))
            client = self.oauth.Client(self.consumer)
            resp, content = client.request(url, "GET")
            if resp["status"] != "200":
                raise Exception("Invalid response %s." % resp["status"])

            request_token = dict(parse_qsl(content))

            if "oauth_callback_confirmed" not in request_token or request_token["oauth_callback_confirmed"] != "true":
                raise Exception("Oauth callback must be confirmed.")

            self.request_tokens[request_token["oauth_token"]] = request_token

            # Step 2: Redirect to the provider.

            redirect_url = "%s?oauth_token=%s" % (self.authorize_url, request_token["oauth_token"])
            start_response("302 Found", [("Location", redirect_url)])
            return []
        elif path == "/callback":
            qsdict = dict(parse_qsl(qs))

            if qsdict["oauth_token"] not in self.request_tokens:
                raise Exception("invalid token: %s" % self.request_tokens)

            request_token = self.request_tokens[qsdict["oauth_token"]]
            del self.request_tokens[qsdict["oauth_token"]]

            token = self.oauth.Token(request_token["oauth_token"], request_token["oauth_token_secret"])
            token.set_verifier(qsdict["oauth_verifier"])
            client = self.oauth.Client(self.consumer, token)
            resp, content = client.request(self.access_token_url, "POST")
            if resp["status"] != "200":
                raise Exception("Invalid response %s." % resp["status"])
            access_token = dict(parse_qsl(content))
            environ["oauth.access_token"] = access_token
            return self.onsuccess(environ, start_response)

        start_response("404 Not Found", [("Content-Type", "text/plain")])
        return ["path not found: %s" % path]
    def signup(self, env, params={}):
        home_url = util.application_uri(env)
        try:
            name = params.get('name', 'guest')
            pwd = params.get('password', 'guest')
            params = {}
            # print("name: {}, pure_pwd: {}".format(name, pwd))

            res = get_user(name=name)
            print('signup_user: '******'error': 'user already exiets',
                    'font_color': 'red'
                }
                redirect_url = home_url

            else:
                if (set_user(name, pwd)):
                    print("ユーザーの作成に成功")
                    error_dict = {
                        'error': 'signup success',
                        'font_color': 'green'
                    }
                    redirect_url = home_url

                else:
                    print("ユーザーの作成に失敗")
                    error_dict = {
                        'error': 'signup failed',
                        'font_color': 'red'
                    }
                    redirect_url = home_url

        except Exception as e:
            # print(str(e))
            # logging.error(str(e))
            raise (e)
            return self.internal_server_error(env, params)

        self.sessions[self.session_id] = error_dict
        status = '303 See Other'
        headers = [('Content-type', 'text/html'), ('Location', redirect_url)]
        headers = set_cookie(headers, self.cookie)
        body = ["<p>リダイレクト中</p>".encode('utf-8')]

        return status, headers, body
Пример #14
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 []
Пример #15
0
    def request_context(self, environ):
        """
        :param environ: a WSGI environment
        """
        request = DotDict()
        request.scheme = util.guess_scheme(environ)
        request.uri = util.request_uri(environ)
        request.address = util.application_uri(environ)
        request.path = util.shift_path_info(environ)
        if environ.get('REQUEST_METHOD', None):
            request.method = environ['REQUEST_METHOD']

        if environ.get('CONTENT_TYPE', None):
            self.headers.add_header('CONTENT_TYPE', environ['CONTENT_TYPE'])

        try:
            length = int(environ.get('CONTENT_LENGTH', '0'))
            request.body = environ['wsgi.input'].read(length)
        except ValueError:
            request.body = b''
        return request
Пример #16
0
 def send_podcast(self, environ, podcast_name):
     if podcast_name not in self.podcasts:
         return self.send_not_found(environ)
     baseurl = application_uri(environ) + podcast_name + "/"
     podcast = self.podcasts[podcast_name]
     return "200 OK", [], podcast.xml(baseurl)
Пример #17
0
def application(env, start_response):
    request_uri = util.request_uri(env)
    application_uri = util.application_uri(env)
    request_method = env.get('REQUEST_METHOD', 'GET').upper()
    request_content_type, request_content_args = cgi.parse_header(env.get('CONTENT_TYPE'))
    request_encoding = request_content_args.get('encoding', 'utf-8')
    accept_content_type = env.get('HTTP_ACCEPT')
    request_origin = env.get('HTTP_ORIGIN') or 'localhost'

    def send_json(obj, content_type='application/json'):
        start_response('200 OK', [('Content-Type', content_type), ('Access-Control-Allow-Origin', request_origin)])
        yield json.dumps(obj, indent='  ', sort_keys=True).encode('utf-8')

    def send_error(code, message):
        start_response(code, [('Content-Type', 'text/plain')])
        yield str(message).encode('utf-8')

    def send_file(file_path, content_type='text/html'):
        start_response('200 OK', [('Content-Type', content_type)])
        with open(file_path) as file:
            yield file.read().encode('utf-8')

#    return dump(env, start_response)

    args = parse.parse_qs(env['QUERY_STRING'])

    def arg(key):
        if (key in args):
            return args[key][0]
        return None

    def intarg(key):
        if (key in args):
            try:
                return int(args[key][0])
            except (ValueError):
                pass
        return None

    try:
        request_content_length = int(env.get('CONTENT_LENGTH', 0))
    except (ValueError):
        request_content_length = 0
    request_body = env['wsgi.input'].read(request_content_length).decode(request_encoding)

    if (request_content_type.endswith('/json') or request_content_type.endswith('+json')):
        request_data = json.loads(request_body)
    elif ('application/x-www-form-urlencoded' == request_content_type):
        request_data = parse.parse_qs(request_body)
    elif ('multipart/form-data' == request_content_type):
        if ('boundary' in request_content_args):
            request_content_args['boundary'] = request_content_args['boundary'].encode('ascii')
        request_data = cgi.parse_multipart(io.BytesIO(request_body.encode(request_encoding)), request_content_args)
    else:
        request_data = {}

    def request(key):
        value = request_data.get(key)
        if (not isinstance(value, str) and hasattr(value, '__getitem__')):
            value = value[0]
            if (isinstance(value, bytes)):
                value = value.decode(request_encoding)
        return value

    def request_int(key):
        value = request(key)
        if (value is not None):
            try:
                return int(value)
            except (ValueError):
                pass
        return None

#    print(request_content_type)
#    print(request_encoding)
#    print(repr(request_data))
#    print(repr(args))

    path = util.shift_path_info(env)
    if ('demo' == path):
        path = util.shift_path_info(env)
        if ('password' == path):
            if ('algorithm' in args):
                cleartext = arg('cleartext')
                if (not cleartext):
                    return send_error('400 Bad Request', 'No cleartext specified')

                try:
                    if ('md5_crypt' in args['algorithm']):
                        return send_json(hash.md5_crypt.encrypt(cleartext, salt=arg('salt')))
                    elif ('bcrypt' in args['algorithm']):
                        return send_json(hash.bcrypt.encrypt(cleartext, salt=arg('salt'), rounds=intarg('rounds'), ident='2b'))
                    elif ('sha1_crypt' in args['algorithm']):
                        return send_json(hash.sha1_crypt.encrypt(cleartext, salt=arg('salt'), rounds=intarg('rounds')))
                    elif ('sun_md5_crypt' in args['algorithm']):
                        return send_json(hash.sun_md5_crypt.encrypt(cleartext, salt=arg('salt'), rounds=intarg('rounds')))
                    elif ('sha256_crypt' in args['algorithm']):
                        return send_json(hash.sha256_crypt.encrypt(cleartext, salt=arg('salt'), rounds=intarg('rounds')))
                    elif ('sha512_crypt' in args['algorithm']):
                        return send_json(hash.sha512_crypt.encrypt(cleartext, salt=arg('salt'), rounds=intarg('rounds')))
                    else:
                        return send_error('400 Bad Request', 'Unknown algorithm')
                except Exception as exc:
                    return send_error('400 Bad Request', exc)
            else:
                return send_json(['md5_crypt', 'bcrypt', 'sha1_crypt', 'sun_md5_crypt', 'sha256_crypt', 'sha512_crypt'])
        elif ('hash' == path):
            if ('algorithm' in args):
                data = None
                if ('GET' == request_method):
                    data = arg('data')
                elif (request_method in ('POST', 'PUT')):
                    data = request('data')

                if (not data):
                    return send_error('400 Bad Request', 'No data specified')

                if ('sha256' == arg('algorithm')):
                    hasher = hashlib.sha256()
                    hasher.update(data.encode('utf-8'))
                    return send_json(hasher.hexdigest())
                elif ('sha512' == arg('algorithm')):
                    hasher = hashlib.sha512()
                    hasher.update(data.encode('utf-8'))
                    return send_json(hasher.hexdigest())
                else:
                    return send_error('400 Bad Request', 'Unknown algorithm')
            else:
                return send_json(['sha256', 'sha512'])
        elif ('crc' == path):
            data = arg('data')
            if ('GET' == request_method):
                value = intarg('value')
            elif (request_method in ('POST', 'PUT')):
                value = request_int('value')

            if (not data):
                return send_error('400 Bad Request', 'No data specified')

            crc = zlib.crc32(data.encode('utf-8'), value) if (value is not None) else zlib.crc32(data.encode('utf-8'))
            if ('application/json-patch+json' == accept_content_type):
                patch = [
                    {'op': 'replace', 'path': '/public/output', 'value': crc},
                    {'op': 'replace', 'path': '/readonly/readonlyOutput', 'value': crc},
                    {'op': 'replace', 'path': '/private/value', 'value': crc},
                    {'op': 'replace', 'path': '/return', 'value': crc},
                ]
                return send_json(patch, 'application/json-patch+json')
            else:
                api = {
                    'resources': {
                        'crc': {
                            'hrefTemplate': 'crc/{?data}',
                            'hrefVars': {
                                'data': 'param/hash/data'
                            },
                            'hints': {
                                'allow': ['PUT'],
                                'formats': {
                                    'application/json': {},
                                    'application/prs.remotewebobjectdemo.crc.v1+json-remote': {}
                                }
                            },
                            'functions': {
                                'update': {
                                    'arguments': ['data'],
                                    'format': 'application/json-patch+json',
                                    'method': 'PUT',
                                    'requestBody': ['value']
                                }
                            }
                        }
                    },
                    'state': {
                        'public': {
                            'output': crc
                        },
                        'private': {
                            'value': crc
                        },
                        'readonly': {
                            "readonlyOutput": crc
                        },
                    }
                }
                return send_json(api, 'application/prs.remotewebobjectdemo.crc.v1+json-remote')
        elif ('tick' == path):
            start_response('200 OK', [
                ('Content-Type', 'text/event-stream; charset=utf-8'),
                ('Access-Control-Allow-Origin', request_origin),
                ('Cache-Control', 'no-cache'),
            ])

            def do_tick():
                tick = 0
                while True:
                    time.sleep(1)
                    tick += 1
                    yield "event: tick\ndata: {tick}\n\n".format(tick=tick).encode('utf-8')
            return do_tick()
        elif ('clock' == path):
            start_response('200 OK', [
                ('Content-Type', 'text/event-stream; charset=utf-8'),
                ('Access-Control-Allow-Origin', request_origin),
                ('Cache-Control', 'no-cache'),
            ])

            def do_clock():
                while True:
                    time.sleep(1)
                    now = time.localtime()
                    if (0 == now.tm_sec):
                        event = 'minute'
                    else:
                        event = 'second'
                    data = {'hour': now.tm_hour, 'minute': now.tm_min, 'second': now.tm_sec}
                    yield "event: {event}\ndata: {data}\n\n".format(event=event, data=json.dumps(data)).encode('utf-8')
            return do_clock()
        elif (not path):
            api = {
                'resources': {
                    'password': {
                        'hrefTemplate': 'password/{?cleartext,algorithm,salt,rounds}',
                        'hrefVars': {
                            'cleartext': 'param/pass/cleartext',
                            'algorithm': 'param/pass/algorithm',
                            'salt': 'param/pass/salt',
                            'rounds': 'param/pass/rounds'
                        },
                        'hints': {
                            'allow': ['GET'],
                            'formats': {
                                'application/json': {},
                                'application/prs.remotewebobjectdemo.password.v1+json': {}
                            }
                        },
                        'functions': {
                            'getAlgorithms': {
                                'arguments': [],
                                'format': 'application/prs.remotewebobjectdemo.password.v1+json',
                                'method': 'GET'
                            },
                            'hashPassword': {
                                'arguments': ['cleartext', 'algorithm', 'salt', 'rounds'],
                                'format': 'application/prs.remotewebobjectdemo.password.v1+json',
                                'method': 'GET'
                            }
                        }
                    },
                    'hash': {
                        'hrefTemplate': 'hash/{?algorithm}',
                        'hrefVars': {
                            'data': 'param/hash/data',
                            'algorithm': 'param/hash/algorithm'
                        },
                        'hints': {
                            'allow': ['GET'],
                            'formats': {
                                'application/json': {},
                                'application/prs.remotewebobjectdemo.password.v1+json': {}
                            }
                        },
                        'functions': {
                            'hash256': {
                                'arguments': ['data'],
                                'format': 'application/prs.remotewebobjectdemo.hash.v1+json',
                                'requestFormat': 'application/x-www-form-urlencoded',
                                'method': 'POST',
                                'defaults': {
                                    'algorithm': 'sha256'
                                }
                            },
                            'hash512': {
                                'arguments': ['data'],
                                'format': 'application/prs.remotewebobjectdemo.hash.v1+json',
                                'requestFormat': 'multipart/form-data',
                                'method': 'PUT',
                                'defaults': {
                                    'algorithm': 'sha512'
                                }
                            }
                        }
                    },
                    'crc': {
                        'hrefTemplate': 'crc/{?data,value}',
                        'hrefVars': {
                            'data': 'param/hash/data',
                            'value': 'param/hash/value'
                        },
                        'hints': {
                            'allow': ['GET'],
                            'formats': {
                                'application/json': {},
                                'application/prs.remotewebobjectdemo.crc.v1+json-remote': {}
                            }
                        },
                        'functions': {
                            'crc32': {
                                'arguments': ['data'],
                                'format': 'application/prs.remotewebobjectdemo.crc.v1+json-remote',
                                'method': 'GET'
                            }
                        }
                    },
                    'tick': {
                        'href': 'tick',
                        'events': {
                            'tick': {}
                        }
                    },
                    'clock': {
                        'href': 'clock',
                        'events': {
                            'second': {},
                            'minute': {}
                        }
                    }
                }
            }
            return send_json(api, 'application/prs.remotewebobjectdemo.crc.v1+json-remote')
        else:
            return send_error('404 Not Found', 'Not found')
    elif ('' == path):
        return send_file('index.html')
    elif ('remotewebobject.js' == path):
        return send_file('remotewebobject.js', 'application/javascript')
    elif ('uritemplate.js' == path):
        return send_file('uritemplate.js', 'application/javascript')
    else:
        return send_error('404 Not Found', 'Not found')
    return send_error('500 Internal Server Error', 'unhandled code')
Пример #18
0
def get_feed_request(amtreq, env):

    dqs = parse_qs(env['QUERY_STRING'])

    def getenv (key):
        val = dqs.get(key, [''])[0]
        val = escape(clean(val))
        
        return val
    
    worker= getenv('worker')
    assn_id = getenv('aid')
    request = getenv('request')
    password = getenv('password')

    # Request a document
    # mid-feed?request=doc&assn_id=2135

    # Request worker info
    # mid-feed?request=worker&worker=johnny78&password=<INSERT PASSWORD HERE>
    # (replies with RSS, STATUS feed, TITLE tag of first item gives 0 (not qualified), 1 (qualified), N/A (unknown)

    # Set worker info
    # mid-feed?request=setworker&worker=johnny78&qualified=1&password=<INSERT PASSWORD HERE>
    # use 1 for qualified, 0 for disqualified.
    # reply as in "request worker info"

    # Get next or current assignment with document
    # mid-feed?worker=johnny78&password=<INSERT PASSWORD HERE>
    # Gives RSS feed with one item (the document)

    # Mark assignment as completed
    # mid-feed?worker=johnny78&aid=234&token=ASDJHLWJASDHN&completed=1&password=<INSERT PASSWORD HERE>
    # token, aid and worker must match.
    # replies with RSS STATUS feed, TITLE tag of first item is short key code to be used as AMT confirmation code.
    
    global PASSWORD
    if request == "doc" or password == PASSWORD:
        if request == "doc":
            return 'text/html',get_doc(worker, assn_id)
        elif request == "worker":
            return 'application/rss+xml',get_worker_info(worker)
        elif request == "setworker":
            qualities = {}
            qualities['test_score']        = getenv('test_score')
            qualities['level']             = getenv('level')

            # remove blank fields
            cleanQualities = {}
            for field in qualities:
                if qualities[field] != '':
                    cleanQualities[field] = qualities[field]
            log(cleanQualities)

            return 'application/rss+xml',set_worker_info(worker, cleanQualities)
        elif request == "gettest":
            return 'application/rss+xml',get_test_score(worker)
        elif request == "settest":
            test_score = getenv('score')
            return 'application/rss+xml',set_test_score(worker, test_score)
        elif request == "getresponse":
            return 'application/rss+xml',get_worker_response(assn_id)
        elif request == "setresponse":
            assn_token = getenv('token')
        
            response = {}
            response['initiator']           = getenv('initiator')
            response['targets']             = getenv('targets')
            response['geogLocation']        = getenv('geogLocation')
            response['geogState']           = getenv('geogState')
            response['date']                = getenv('date')
            response['initiatorApology']    = getenv('initiatorApology')
            response['targetProtest']       = getenv('targetProtest')
            response['lineNumber']          = getenv('lineNumber')
            response['targetSupport']       = getenv('targetSupport')
            response['action']              = getenv('action')
            response['initiatorDenial']     = getenv('initiatorDenial')
            response['covertAction']        = getenv('covertAction')
            response['addActionLines']      = getenv('addActionLines')
            response['initiatorFatalities'] = getenv('initiatorFatalities')
            response['targetFatalities']    = getenv('targetFatalities')
            response['groups']              = getenv('groups')
            response['initiatorRole']       = getenv('initiatorRole')
            response['targetRole']          = getenv('targetRole')
            
            # remove blank fields
            cleanResponse = {}
            for field in response:
                if response[field] != '':
                    cleanResponse[field] = response[field]
            log(cleanResponse)
            return 'application/rss+xml',set_worker_response(assn_id, assn_token, cleanResponse)
        elif request == "status":
            qualified = getenv('qualified')
            completed = getenv('completed')
            table = getenv('table')
            return 'text/html',get_status(worker=worker, qualified=qualified, completed=completed, table=table)
        else:    
            completed = getenv('completed')
            assn_token = getenv('token')
            return 'application/rss+xml',get_feed(amtreq, worker, assn_id, assn_token, completed, application_uri(env))
    else:
        return 'application/rss+xml', make_error_rss("Must give correct password for this request.")
Пример #19
0
 def send_podcast(self, environ, podcast_name):
     if podcast_name not in self.podcasts:
         return self.send_not_found(environ)
     baseurl = application_uri(environ) + podcast_name + "/"
     podcast = self.podcasts[podcast_name]
     return "200 OK", [], podcast.xml(baseurl)
Пример #20
0
 def on_view_not_found(self, environ, start_response):
     """ called when action is not found """
     start_response(
         "404 Not Found",
         [('Content-type', 'text/plain')])
     return [b"Not Found ", application_uri(environ).encode('utf-8')]
Пример #21
0
    try:
        import swat
    except ImportError, 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)]


if __name__ == '__main__':
    from wsgiref import simple_server
Пример #22
0
 def __init__(self, environ, urlmapper):
     self.environ = environ
     self.urlmapper = urlmapper
     self.application_uri = application_uri(environ)
Пример #23
0
    def app_url(self):
	return application_uri(self.request.environ)
Пример #24
0
def form(environ, start_response):
    start_response("200 OK", [("Content-type", "text/html;charset=utf-8")])
    url = application_uri(environ)
    return [form_body.format(url=url).encode("utf-8")]
Пример #25
0
def form(environ, start_response):
    start_response("200 OK", [("Content-type", "text/html;charset=utf-8")])
    url = application_uri(environ)
    return [form_body.format(url=url).encode('utf-8')]
Пример #26
0
 def fake_app(req):
     return util.application_uri(req.environ)
Пример #27
0
 def __init__(self, environ: Dict[str, Any], urlmapper: URLMapper) -> None:
     self.environ = environ
     self.urlmapper = urlmapper
     self.application_uri = application_uri(environ)
 def checkAppURI(self, uri, **kw):
     util.setup_testing_defaults(kw)
     self.assertEqual(util.application_uri(kw), uri)
Пример #29
0
def app(environ, start_response):
    uri = request_uri(environ,
                      include_query=False).replace(application_uri(environ),
                                                   '')
    yield urls.get(uri, view_404)(environ, start_response).encode('utf-8')
Пример #30
0
 def fake_app(req):
     return util.application_uri(req.environ)
Пример #31
0
    try:
        import swat
    except ImportError, 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)]


if __name__ == '__main__':
    from wsgiref import simple_server
    httpd = simple_server.make_server('localhost', 8090, __call__)
Пример #32
0
 def checkAppURI(self,uri,**kw):
     util.setup_testing_defaults(kw)
     self.assertEqual(util.application_uri(kw),uri)
Пример #33
0
 def application_uri(self):
     """The base URI of the application (wsgiref.application_uri)."""
     if self._application_uri is None:
         self._application_uri = application_uri(self.environ)
     return self._application_uri