Python bottle.request.query() Examples

The following are 30 code examples of bottle.request.query(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module bottle.request , or try the search function .
Example #1
Source File: main.py    From python-examples with MIT License 6 votes vote down vote up
def file():
    print('[bottle] url: /upload')
    

    print('[bottle] query:', request.query.keys())
    print('[bottle] forms:', request.forms.keys())
    print('[bottle] files:', request.files.keys())
    
    files = request.files.getall('file')
    print('[bottle] files:', files)
    
    save_path = "./save_file"
    if not os.path.exists(save_path):
        os.mkdir(save_path)
    
    File(files).start()

    print('[bottle] redirect: /')
    redirect('/')
    # print('after redirect') # never executed 
Example #2
Source File: app.py    From browsertrix with MIT License 6 votes vote down vote up
def get_params():
    url = request.query.get('url')

    archive = request.query.get('archive')

    browser_type = request.query.get('browser', 'chrome')

    if not url:
        raise HTTPError(status=400, body='No url= specified')

    if archive not in theconfig['archives']:
        raise HTTPError(status=400, body='No archive {0}'.format(archive))

    if not url.startswith(('http://', 'https://')):
        url = 'http://' + url

    return browser_type, archive, url 
Example #3
Source File: bambleweeny.py    From bambleweeny with MIT License 6 votes vote down vote up
def get_token():
	# Get JSON Payload
	try:
		payload = json.load(request.body)
		username = payload["username"]
		password = payload["password"]
		pwhash = _get_password_hash(password)
	except:
		response.status = 400
		return dict({"message":"No valid JSON found in post body or mandatory fields missing."})

	user_list = rc.scan_iter("USER:*")
	for user in user_list:
		user_record = json.loads(rc.get(user))
		if user_record["username"] == username and user_record["hash"] == pwhash:
			user_token = _issue_token(user=username, id=user[5:], expiry=token_expiry_seconds)
			if 'raw' in request.query:
				return(user_token)
			else:
				return(dict(token_type="bearer", access_token=user_token))

	response.status = 401
	return(dict(info="could not authorize user"))

# Test Auth Token 
Example #4
Source File: web.py    From TedEval with MIT License 6 votes vote down vote up
def index():
    
    _,images_list = get_samples()

    page = 1
    if 'p' in request.query:
        page = int(request.query['p'])
        
    subm_data = get_all_submissions()

    vars = {
            'url':url, 
            'acronym':acronym, 
            'title':title,
            'images':images_list,
            'method_params':method_params,
            'page':page,
            'subm_data':subm_data,
            'submit_params':submit_params,
            'instructions':instructions,
            'extension':gt_ext
            }
    return template('index',vars) 
Example #5
Source File: web.py    From TedEval with MIT License 6 votes vote down vote up
def gt_image():
    imagesFilePath = os.path.dirname(os.path.abspath(__file__)) + "/gt/gt.zip"
    archive = zipfile.ZipFile(imagesFilePath,'r')
    fileName = request.query['sample']
    ext = fileName.split('.')[-1]
    if ext=="jpg":
        header = "image/jpeg"
    elif ext == "gif":
        header = "image/gif"    
    elif ext == "png":
        header = "image/png"            
    
    data = archive.read(fileName)
    body = data
    headers = dict()
    headers['Content-Type'] = header
    if 'c' in request.query:
        headers['Cache-Control'] = "public, max-age=3600"
    return HTTPResponse(body, **headers) 
Example #6
Source File: database.py    From maloja with GNU General Public License v3.0 6 votes vote down vote up
def db_search(query,type=None):
	if type=="ARTIST":
		results = []
		for a in ARTISTS:
			#if query.lower() in a.lower():
			if simplestr(query) in simplestr(a):
				results.append(a)

	if type=="TRACK":
		results = []
		for t in TRACKS:
			#if query.lower() in t[1].lower():
			if simplestr(query) in simplestr(t[1]):
				results.append(get_track_dict(t))

	return results


####
## Useful functions
####

# makes a string usable for searching (special characters are blanks, accents and stuff replaced with their real part) 
Example #7
Source File: web.py    From TedEval with MIT License 6 votes vote down vote up
def subm_image():
    submFilePath = os.path.dirname(os.path.abspath(__file__)) + "/output/subm_" + str(request.query['m'])  + ".zip"
    archive = zipfile.ZipFile(submFilePath,'r')
    fileName = request.query['sample']
    ext = fileName.split('.')[-1]
    if ext=="jpg":
        header = "image/jpeg"
    elif ext == "gif":
        header = "image/gif"    
    elif ext == "png":
        header = "image/png"            
    
    data = archive.read(fileName)
    body = data
    headers = dict()
    headers['Content-Type'] = header
    if 'c' in request.query:
        headers['Cache-Control'] = "public, max-age=3600"
    return HTTPResponse(body, **headers) 
Example #8
Source File: web.py    From mailur with GNU General Public License v3.0 5 votes vote down vote up
def raw_part(uid, part, filename=None):
    box = request.query.get('box', local.SRC)
    uid = str(uid)
    msg, content_type = local.raw_part(uid, box, part)
    if msg is None:
        return abort(404)
    response.content_type = content_type
    return msg 
Example #9
Source File: web.py    From mailur with GNU General Public License v3.0 5 votes vote down vote up
def reply(uid=None):
    forward = uid and request.query.get('forward')
    draft_id = message.gen_draftid()
    local.data_drafts({draft_id: {
        'draft_id': draft_id,
        'parent': uid,
        'forward': forward,
        'time': time.time(),
    }})
    return {
        'draft_id': draft_id,
        'query_edit': 'draft:%s' % draft_id,
        'url_send': app.get_url('send', draft_id=draft_id),
    } 
Example #10
Source File: web.py    From mailur with GNU General Public License v3.0 5 votes vote down vote up
def avatars():
    hashes = set(request.query['hashes'].split(','))
    size = request.query.get('size', 20)
    default = request.query.get('default', 'identicon')
    cls = request.query.get('cls', '.pic-%s')

    response.content_type = 'text/css'
    return '\n'.join((
        '%s {background-image: url(data:image/gif;base64,%s);}'
        % ((cls % h), i.decode())
    ) for h, i in fetch_avatars(hashes, size, default)) 
Example #11
Source File: web.py    From mailur with GNU General Public License v3.0 5 votes vote down vote up
def avatar(hash):
    size = request.query.get('size', 20)
    default = request.query.get('default', 'identicon')
    gravatar_url = get_gravatar_url(hash, size, default)
    return proxy_by_nginx(gravatar_url) 
Example #12
Source File: web.py    From mailur with GNU General Public License v3.0 5 votes vote down vote up
def proxy():
    url = request.query.get('url')
    if not url:
        return abort(400)

    return proxy_by_nginx(url) 
Example #13
Source File: server.py    From maloja with GNU General Public License v3.0 5 votes vote down vote up
def dynamic_image():
	keys = FormsDict.decode(request.query)
	relevant, _, _, _ = uri_to_internal(keys)
	result = resolveImage(**relevant)
	if result == "": return ""
	redirect(result,307) 
Example #14
Source File: database.py    From maloja with GNU General Public License v3.0 5 votes vote down vote up
def search(**keys):
	query = keys.get("query")
	max_ = keys.get("max")
	if max_ is not None: max_ = int(max_)
	query = query.lower()

	artists = db_search(query,type="ARTIST")
	tracks = db_search(query,type="TRACK")



	# if the string begins with the query it's a better match, if a word in it begins with it, still good
	# also, shorter is better (because longer titles would be easier to further specify)
	artists.sort(key=lambda x: ((0 if x.lower().startswith(query) else 1 if " " + query in x.lower() else 2),len(x)))
	tracks.sort(key=lambda x: ((0 if x["title"].lower().startswith(query) else 1 if " " + query in x["title"].lower() else 2),len(x["title"])))

	# add links
	artists_result = []
	for a in artists:
		result = {"name":a}
		result["link"] = "/artist?" + compose_querystring(internal_to_uri({"artist":a}))
		result["image"] = "/image?" + compose_querystring(internal_to_uri({"artist":a}))
		artists_result.append(result)

	tracks_result = []
	for t in tracks:
		result = t
		result["link"] = "/track?" + compose_querystring(internal_to_uri({"track":t}))
		result["image"] = "/image?" + compose_querystring(internal_to_uri({"track":t}))
		tracks_result.append(result)

	return {"artists":artists_result[:max_],"tracks":tracks_result[:max_]} 
Example #15
Source File: dockerhub_status_image_api.py    From dockerhub-build-status-image with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_build_status(organization, repository):
    tag = request.query.get("tag", DEFAULT_TAG)
    status = get_status(organization, repository, tag)
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
    if status is None:
        return {"request": "error", "description": "tag {} not found".format(tag)}
    return {"request": "ok", "status": status} 
Example #16
Source File: dockerhub_status_image_api.py    From dockerhub-build-status-image with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_svg():
    organization = request.query.get("organization", DEFAULT_ORGANIZATION)
    repository = request.query["repository"]
    tag = request.query.get("tag", DEFAULT_TAG)
    text = request.query.get("text", DEFAULT_TEXT)
    status = get_status(organization, repository, tag)
    response.content_type = "image/svg+xml"
    if status < 0:
        code = "error"
        color = "#c41"
    else:
        code = "ok"
        color = "#4c1"
    response.set_header('Cache-Control', 'public, max-age=3600')
    return SVG.format(color=color, text=text, status=code) 
Example #17
Source File: app.py    From GNIBappointments with MIT License 5 votes vote down vote up
def verification():
    """verification protocol for Facebook bot"""
    if request.query.get('hub.verify_token', None) is None:
        return
    if request.query.get('hub.challenge', None) is None:
        return
    token = request.query['hub.verify_token']
    if token == VERIFICATION_TOKEN:
        return request.query['hub.challenge'] 
Example #18
Source File: smserverlogic.py    From service-manager with Apache License 2.0 5 votes vote down vote up
def process_request(self):
        service = request.query['service']
        if not service in self.application.service_mappings:
            raise BadRequestException("Service '%s' cannot be found in 'service_mappings.json', please update this file" % service)
        service_alias = self.application.service_mappings[service]
        if not service_alias in self.application.services:
            raise BadRequestException("Service '%s' cannot be found in 'services.json', please update this file" % service_alias)
        if not "versionEnv" in self.application.services[service_alias]:
            raise BadRequestException("'versionEnv' cannot be found for service '%s', please update 'services.json'" % service_alias)
        return {"variable": self.application.services[service_alias]["versionEnv"]} 
Example #19
Source File: app.py    From opentapioca with Apache License 2.0 5 votes vote down vote up
def jsonp(view):
    """
    Decorator for views that return JSON
    """
    def wrapped(*posargs, **kwargs):
        args = {}
        # if we access the args via get(),
        # we can get encoding errors...
        for k in request.forms:
            args[k] = getattr(request.forms, k)
        for k in request.query:
            args[k] = getattr(request.query, k)
        callback = args.get('callback')
        status_code = 200
        try:
            result = view(args, *posargs, **kwargs)
        except (KeyError) as e:#ValueError, AttributeError, KeyError) as e:
            import traceback, sys
            traceback.print_exc(file=sys.stdout)
            result = {'status':'error',
                    'message':'invalid query',
                    'details': str(e)}
            status_code = 403
        if callback:
            result = '%s(%s);' % (callback, json.dumps(result))

        if status_code == 200:
            return result
        else:
            abort(status_code, result)

    return wrapped 
Example #20
Source File: app.py    From opentapioca with Apache License 2.0 5 votes vote down vote up
def annotate_api(args):
    text = args['query']
    if not classifier:
        mentions = tagger.tag_and_rank(text)
    else:
        mentions = classifier.create_mentions(text)
        classifier.classify_mentions(mentions)

    return {
        'text':text,
        'annotations': [m.json() for m in mentions]
    } 
Example #21
Source File: contentcontroller.py    From conifer with Apache License 2.0 5 votes vote down vote up
def do_put_record(self):
        reqid = request.query.getunicode('reqid')
        info = self.browser_mgr.init_remote_browser_session(reqid=reqid)
        if not info:
            return self._raise_error(400, 'invalid_connection_source')

        user = info['the_user']
        collection = info['collection']
        recording = info['recording']

        kwargs = dict(user=user.name,
                      coll=collection.my_id,
                      rec=recording.my_id,
                      type='put_record')

        url = request.query.getunicode('target_uri')

        params = {'url': url}

        upstream_url = self.get_upstream_url('', kwargs, params)

        headers = {'Content-Type': request.environ.get('CONTENT_TYPE', 'text/plain')}

        r = requests.put(upstream_url,
                         data=request.body,
                         headers=headers,
                        )
        try:
            res = r.json()
            if res['success'] != 'true':
                print(res)
                return {'error_message': 'put_record_failed'}

            warc_date = res.get('WARC-Date')

        except Exception as e:
            print(e)
            return {'error_message': 'put_record_failed'}

        return res 
Example #22
Source File: main.py    From python-examples with MIT License 5 votes vote down vote up
def index():
    """ 
    <form> with 'enctype="multipart/form-data"' gives files in request.files
    <form> with 'enctype="multipart/form-data"' gives files in request.query
    
    """
    
    print('[bottle] url: /')
    return '''
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="text" name="string"><br/>
<input type="file" name="file"/><br/>
<button type="submit">SEND</button>
</form>
''' 
Example #23
Source File: web.py    From TedEval with MIT License 5 votes vote down vote up
def gt_video():
    imagesFilePath = os.path.dirname(os.path.abspath(__file__)) + "/gt/images.zip"
    archive = zipfile.ZipFile(imagesFilePath,'r')
    fileName = request.query['sample']
    ext = fileName.split('.')[-1]
    header = "video/mp4"

    data = archive.read(fileName)
    body = data
    headers = dict()
    headers['Content-Type'] = header
    if 'c' in request.query:
        headers['Cache-Control'] = "public, max-age=3600"
    return HTTPResponse(body, **headers) 
Example #24
Source File: bambleweeny.py    From bambleweeny with MIT License 5 votes vote down vote up
def _authenticate():
	# Token can be in query string or AUTH header
	if 'token' in request.query:
		access_token = request.query["token"]
	else:
		bearer = request.environ.get('HTTP_AUTHORIZATION','')
		access_token=bearer[7:]

	# Extract the data from the token
	data = _get_token_data(token=access_token)

	# If there was an error, end here
	if data["error"] != "0":
		return(dict(data))

	# Was the token issued by this cluster?
	if data["cluster_id"] != cluster_id:
		return(dict(data))

	# Is the access token still valid?
	token_timestamp = data["timestamp"]
	current_time = int(time.time())
	delta = current_time - token_timestamp
	if delta > token_expiry_seconds:
		# expired
		data["authenticated"] = "False"
		data["info"] = "Token expired"
	else:
		# valid
		data["authenticated"] = "True"
		data["info"] = "Session expires in " + str(token_expiry_seconds - delta) + " seconds."
		# Set response header: username
		response.headers["B9Y-AUTHENTICATED-USER"] = data["user"]

	return(dict(data)) 
Example #25
Source File: api.py    From awe with MIT License 5 votes vote down vote up
def _get_elements(self):
        query = request.query
        include_data = query.get('include_data', '').lower() == 'true'
        include_props = query.get('include_props', '').lower() == 'true'
        return {
            'elements': {
                eid: self._get_element(eid, include_data=include_data, include_props=include_props)
                for eid in self._registry.elements
            }
        } 
Example #26
Source File: web.py    From TedEval with MIT License 5 votes vote down vote up
def method():
    
    _,images_list = get_samples()
    
    results = None
    page = 1
    subm_data = {}
    
    if 'm' in request.query:
        id = request.query['m']
        submFilePath = os.path.dirname(os.path.abspath(__file__)) + "/output/results_" + id   + ".zip"

        if os.path.isfile(submFilePath):
            results = zipfile.ZipFile(submFilePath,'r')
            
        if 'p' in request.query:
            page = int(request.query['p'])
        
        subm_data = get_submission(id)
        
        if results is None or subm_data is None:
            redirect('/')
    else:
        redirect('/')

    vars = {
        'url':url, 
        'acronym':acronym, 
        'title':title,
        'images':images_list,
        'method_params':method_params,
        'sample_params':sample_params,
        'results':results,
        'page':page,
        'subm_data':subm_data
    }
    return template('method',vars) 
Example #27
Source File: web.py    From TedEval with MIT License 5 votes vote down vote up
def get_sample_info():
    
    methodId = request.query['m']    
    submFilePath = os.path.dirname(os.path.abspath(__file__)) + "/output/results_" + methodId + ".zip"
    archive = zipfile.ZipFile(submFilePath,'r')
    id = get_sample_id_from_num(int(request.query['sample']))
    results = json.loads(archive.read(id + ".json"))
    return json.dumps(results) 
Example #28
Source File: web.py    From TedEval with MIT License 5 votes vote down vote up
def image_thumb():

    sample = int(request.query['sample'])
    fileName,data = get_sample_from_num(sample)
    ext = fileName.split('.')[-1]
    
    f = BytesIO(data)	
    image = Image.open(f)

    maxsize = (205, 130)
    image.thumbnail(maxsize)
    output = BytesIO()
	
    if ext=="jpg":
            im_format = "JPEG"
            header = "image/jpeg"
            image.save(output,im_format, quality=80, optimize=True, progressive=True)
    elif ext == "gif":
            im_format = "GIF"
            header = "image/gif"
            image.save(output,im_format)
    elif ext == "png":
            im_format = "PNG"
            header = "image/png"
            image.save(output,im_format, optimize=True)
    
    contents = output.getvalue()
    output.close()
    
    body = contents
    headers = dict()
    headers['Content-Type'] = header
    if 'c' in request.query:
        headers['Cache-Control'] = "public, max-age=3600"
    
    return HTTPResponse(body, **headers) 
Example #29
Source File: web.py    From TedEval with MIT License 5 votes vote down vote up
def gt_file():
    imagesFilePath = os.path.dirname(os.path.abspath(__file__)) + "/gt/gt.zip"
    archive = zipfile.ZipFile(imagesFilePath,'r')
    fileName = request.query['sample']
    ext = fileName.split('.')[-1]
    if ext=="xml":
        header = "text/xml"

    data = archive.read(fileName)
    body = data
    headers = dict()
    headers['Content-Type'] = header
    if 'c' in request.query:
        headers['Cache-Control'] = "public, max-age=3600"
    return HTTPResponse(body, **headers) 
Example #30
Source File: web.py    From mailur with GNU General Public License v3.0 5 votes vote down vote up
def raw(uid):
    box = request.query.get('box', local.SRC)
    uid = str(uid)
    if request.query.get('parsed') or request.query.get('p'):
        box = local.ALL
        uid = local.pair_origin_uids([uid])[0]

    msg = local.raw_msg(uid, box)
    if msg is None:
        return abort(404)
    response.content_type = 'text/plain'
    return msg