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: 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 #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: 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 #4
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 #5
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 #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: 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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
Source File: web.py    From TedEval with MIT License 5 votes vote down vote up
def subm_xml():
    submFilePath = os.path.dirname(os.path.abspath(__file__)) + "/output/subm_" + str(request.query['m'])  + ".zip"
    archive = zipfile.ZipFile(submFilePath,'r')
    fileName = request.query['sample']
    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 #16
Source File: web.py    From TedEval with MIT License 5 votes vote down vote up
def result_xml():
    submFilePath = os.path.dirname(os.path.abspath(__file__)) + "/output/results_" + str(request.query['m'])  + ".zip"
    archive = zipfile.ZipFile(submFilePath,'r')
    fileName = request.query['name']
    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 #17
Source File: web.py    From mailur with GNU General Public License v3.0 5 votes vote down vote up
def index():
    theme = request.query.get('theme')
    if not request.session:
        args = {'theme': theme} if theme else {}
        login_url = app.get_url('login', **args)
        return redirect(login_url)

    theme = theme or request.session['theme']
    return render_tpl(theme, 'index', preload_data()) 
Example #18
Source File: web.py    From mailur with GNU General Public License v3.0 5 votes vote down vote up
def login_html(theme=None):
    theme = request.query.get('theme') or request.session.get('theme')
    return render_tpl(theme, 'login', {
        'themes': themes(),
        'timezones': list(all_timezones),
    }) 
Example #19
Source File: web.py    From mailur with GNU General Public License v3.0 5 votes vote down vote up
def filters():
    def run():
        query, opts = parse_query(data['query'])
        if opts.get('thread') and opts.get('uids'):
            uids = opts['uids']
            oids = uids and local.pair_parsed_uids(uids)
            query = 'uid %s' % imap.pack_uids(oids)
        try:
            local.sieve_run(query, data['body'])
        except imap.Error as e:
            abort(400, e.args[0].decode())
        local.sync_flags_to_all()

    data = schema.validate(request.json, {
        'type': 'object',
        'properties': {
            'action': {'type': 'string', 'enum': ['save', 'run']},
            'name': {'type': 'string', 'enum': ['auto', 'manual']},
            'body': {'type': 'string'},
            'query': {'type': 'string'},
        },
        'required': ['action', 'name', 'body', 'query']
    })
    if data['action'] == 'save':
        run()
        local.data_filters({data['name']: data['body']})
        return local.sieve_scripts()

    body = data['body']
    if not body:
        return

    run() 
Example #20
Source File: web.py    From mailur with GNU General Public License v3.0 5 votes vote down vote up
def thrs_unlink():
    uids = request.json['uids']
    if not uids:
        return {}
    uids = local.unlink_threads(uids)
    return {'query': ':threads uid:%s' % ','.join(uids)} 
Example #21
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 #22
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 
Example #23
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 #24
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 #25
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 #26
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 #27
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 #28
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 #29
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 #30
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)