Python flask.request.args() Examples

The following are 30 code examples of flask.request.args(). 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: google.py    From app with MIT License 12 votes vote down vote up
def google_login():
    # to avoid flask-login displaying the login error message
    session.pop("_flashes", None)

    next_url = request.args.get("next")

    # Google does not allow to append param to redirect_url
    # we need to pass the next url by session
    if next_url:
        session["google_next_url"] = next_url

    google = OAuth2Session(GOOGLE_CLIENT_ID, scope=_scope, redirect_uri=_redirect_uri)
    authorization_url, state = google.authorization_url(_authorization_base_url)

    # State is used to prevent CSRF, keep this for later.
    session["oauth_state"] = state
    return redirect(authorization_url) 
Example #2
Source File: server.py    From grlc with MIT License 8 votes vote down vote up
def query(user, repo, query_name, subdir=None, spec_url=None, sha=None, content=None):
    """Execute SPARQL query for a specific grlc-generated API endpoint"""
    glogger.info("-----> Executing call name at /{}/{}/{}/{} on commit {}".format(user, repo, subdir, query_name, sha))
    glogger.debug("Request accept header: " + request.headers["Accept"])

    requestArgs = request.args
    acceptHeader = request.headers['Accept']
    requestUrl = request.url
    formData = request.form

    query_response, status, headers = utils.dispatch_query(user, repo, query_name, subdir, spec_url,
                                                           sha=sha, content=content, requestArgs=requestArgs,
                                                           acceptHeader=acceptHeader,
                                                           requestUrl=requestUrl, formData=formData)
    if isinstance(query_response, list):
        query_response = jsonify(query_response)

    return make_response(query_response, status, headers)

### Server routes ### 
Example #3
Source File: facebook.py    From app with MIT License 7 votes vote down vote up
def facebook_login():
    # to avoid flask-login displaying the login error message
    session.pop("_flashes", None)

    next_url = request.args.get("next")

    # Facebook does not allow to append param to redirect_uri
    # we need to pass the next url by session
    if next_url:
        session["facebook_next_url"] = next_url

    facebook = OAuth2Session(
        FACEBOOK_CLIENT_ID, scope=_scope, redirect_uri=_redirect_uri
    )
    facebook = facebook_compliance_fix(facebook)
    authorization_url, state = facebook.authorization_url(_authorization_base_url)

    # State is used to prevent CSRF, keep this for later.
    session["oauth_state"] = state
    return redirect(authorization_url) 
Example #4
Source File: index.py    From watchdog with Apache License 2.0 7 votes vote down vote up
def listRemove(self):
    cpe = request.args.get('cpe', type=str)
    cpe = urllib.parse.quote_plus(cpe).lower()
    cpe = cpe.replace("%3a", ":")
    cpe = cpe.replace("%2f", "/")
    lst = request.args.get('list', type=str)
    if cpe and lst:
      result=wl.removeWhitelist(cpe) if lst.lower()=="whitelist" else bl.removeBlacklist(cpe)
      status = "removed_from_list" if (result > 0) else "already_removed_from_list"
    else:
      status = "invalid_cpe"
    returnList = db.getWhitelist() if lst=="whitelist" else db.getBlacklist()
    return jsonify({"status":status, "rules":returnList, "listType":lst.title()})


  # /admin/editInList 
Example #5
Source File: views.py    From jbox with MIT License 7 votes vote down vote up
def github_authorize_callback():
    developer = get_developer()
    if developer is None:
        return redirect(url_for('main.login'))
    resp = github.authorized_response()
    if resp is None:
        return 'Access denied: reason=%s error=%s' % (
            request.args['error_reason'],
            request.args['error_description']
        )
    session['github_token'] = (resp['access_token'], '')
    me = github.get('user')
    user = me.data['login']
    session['user'] = user
    authorization = Authorization(developer=developer, oauth_token=session['github_token'][0], type='github')
    try:
        db.session.add(authorization)
        db.session.commit()
        return redirect(url_for('auth.github_integration'))
    except:
        db.session.rollback()
        abort(500) 
Example #6
Source File: ui.py    From gransk with Apache License 2.0 6 votes vote down vote up
def setup(args, pipeline, runmod, injector):
  """Load configuration"""
  logging.basicConfig(
      format='[%(asctime)s] [%(levelname)s] %(name)s: %(message)s',
      level=logging.INFO,
      datefmt='%Y-%m-%d %H:%M:%S')

  _globals['gransk'] = gransk.api.API(injector)
  _globals['config'] = _globals['gransk'].config

  if pipeline:
    _globals['gransk'].pipeline = pipeline

  if _globals['gransk'].pipeline.get_service('related_entities'):
    _globals['gransk'].pipeline.get_service('related_entities').load_all(_globals['config'])

  if _globals['gransk'].pipeline.get_service('related_documents'):
    _globals['gransk'].pipeline.get_service('related_documents').load_all(_globals['config']) 
Example #7
Source File: Server.py    From uplink with MIT License 6 votes vote down vote up
def repos_for_keyword():
    """
  /repos?keyword=<keyword>

  Finds all repos which contain the given keyword in the name, readme, or description """
    if "keyword" not in request.args:
        return "", 400

    keyword = request.args["keyword"]
    future = _repos_for_keyword(keyword)
    repos = loop.run_until_complete(future)
    return jsonify(repos) 
Example #8
Source File: metagame.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 6 votes vote down vote up
def matchups() -> str:
    hero, enemy = {}, {}
    for k, v in request.args.items():
        if k.startswith('hero_'):
            k = k.replace('hero_', '')
            hero[k] = v
        else:
            k = k.replace('enemy_', '')
            enemy[k] = v
    season_id = request.args.get('season_id')
    results = mus.matchup(hero, enemy, season_id=season_id) if 'hero_person_id' in request.args else {}
    matchup_archetypes = archs.load_archetypes_deckless()
    matchup_archetypes.sort(key=lambda a: a.name)
    matchup_people = list(ps.load_people(where='p.mtgo_username IS NOT NULL'))
    matchup_people.sort(key=lambda p: p.name)
    matchup_cards = cs.load_cards()
    matchup_cards.sort(key=lambda c: c.name)
    view = Matchups(hero, enemy, season_id, matchup_archetypes, matchup_people, matchup_cards, results)
    return view.page() 
Example #9
Source File: index.py    From watchdog with Apache License 2.0 6 votes vote down vote up
def listEdit(self):
    old = request.args.get('oldCPE')
    new = request.args.get('cpe')
    lst = request.args.get('list')
    CPEType = request.args.get('type')
    if old and new:
      result = wl.updateWhitelist(old, new, CPEType) if lst=="whitelist" else bl.updateBlacklist(old, new, CPEType)
      status = "cpelist_updated" if (result) else "cpelist_update_failed"
    else:
      status = "invalid_cpe"
    returnList = list(db.getWhitelist()) if lst=="whitelist" else list(db.getBlacklist())
    return jsonify({"rules":returnList, "status":status, "listType":lst})


  # /admin/listmanagement/<vendor>/<product>
  # /admin/listmanagement/<vendor>
  # /admin/listmanagement 
Example #10
Source File: rest_api_plugin.py    From airflow-rest-api-plugin with Apache License 2.0 6 votes vote down vote up
def refresh_dag(self, base_response):
        logging.info("Executing custom 'refresh_dag' function")
        dag_id = request.args.get('dag_id')
        logging.info("dag_id to refresh: '" + str(dag_id) + "'")
        if self.is_arg_not_provided(dag_id):
            return REST_API_Response_Util.get_400_error_response(base_response, "dag_id should be provided")
        elif " " in dag_id:
            return REST_API_Response_Util.get_400_error_response(base_response, "dag_id contains spaces and is therefore an illegal argument")

        try:
            from airflow.www.views import Airflow
            # NOTE: The request argument 'dag_id' is required for the refresh() function to get the dag_id
            refresh_result = Airflow().refresh()
            logging.info("Refresh Result: " + str(refresh_result))
        except Exception as e:
            error_message = "An error occurred while trying to Refresh the DAG '" + str(dag_id) + "': " + str(e)
            logging.error(error_message)
            return REST_API_Response_Util.get_500_error_response(base_response, error_message)

        return REST_API_Response_Util.get_200_response(base_response=base_response, output="DAG [{}] is now fresh as a daisy".format(dag_id))

    # Custom Function for the refresh_all_dags API
    # This will call the direct function corresponding to the web endpoint '/admin/airflow/refresh_all' that already exists in Airflow 
Example #11
Source File: auth.py    From eve-auth-jwt with MIT License 6 votes vote down vote up
def authorized(self, allowed_roles, resource, method):
        authorized = False

        if request.authorization:
            auth = request.authorization
            authorized = self.check_auth(auth.username, auth.password,
                                         allowed_roles, resource, method)
        else:
            try:
                access_token = request.args['access_token']
            except KeyError:
                access_token = request.headers.get('Authorization', '').partition(' ')[2]
            authorized = self.check_token(access_token, allowed_roles, resource, method)

        return authorized 
Example #12
Source File: ui.py    From gransk with Apache License 2.0 6 votes vote down vote up
def related():
  """Get related documents or entities."""
  if request.args['type'] == 'document':
    service = 'related_documents'
  elif request.args['type'] == 'entity':
    service = 'related_entities'
  else:
    return Response('Invalid type %s' % request.args['type'])

  if not _globals['gransk'].pipeline.get_service(service):
      return Response('{"error": "service not found"}', status=200, mimetype='application/json')

  result = _globals['gransk'].pipeline.get_service(service).get_related_to(
      request.args['id'])

  return Response(json.dumps(result), status=200, mimetype='application/json') 
Example #13
Source File: auth.py    From eve-auth-jwt with MIT License 6 votes vote down vote up
def requires_token(self, audiences=None, allowed_roles=None):
        """
        Decorator for functions that will be protected with token authentication.

        Token must be provvided either through access_token parameter or Authorization
        header.

        See check_token() method for further details.
        """
        def requires_token_wrapper(f):
            @wraps(f)
            def decorated(*args, **kwargs):
                try:
                    token = request.args['access_token']
                except KeyError:
                    token = request.headers.get('Authorization', '').partition(' ')[2]

                if not self._perform_verification(token, audiences, allowed_roles):
                    abort(401)

                return f(*args, **kwargs)
            return decorated
        return requires_token_wrapper 
Example #14
Source File: views.py    From beavy with Mozilla Public License 2.0 5 votes vote down vote up
def extract():
    return extract_info(request.args["url"]) 
Example #15
Source File: public.py    From platform with GNU General Public License v3.0 5 votes vote down vote up
def set_access():
    public_ip = None
    if 'public_ip' in request.args:
        public_ip = request.args['public_ip']
    public.set_access(
        request.args['upnp_enabled'] == 'true',
        request.args['external_access'] == 'true',
        public_ip,
        int(request.args['certificate_port']),
        int(request.args['access_port'])
    )
    return jsonify(success=True), 200 
Example #16
Source File: public.py    From platform with GNU General Public License v3.0 5 votes vote down vote up
def install():
    public.install(request.args['app_id'])
    return 'OK', 200 
Example #17
Source File: public.py    From platform with GNU General Public License v3.0 5 votes vote down vote up
def app_status():
    return jsonify(info=convertible.to_dict(public.get_app(request.args['app_id']))), 200 
Example #18
Source File: views.py    From jbox with MIT License 5 votes vote down vote up
def authorized():
    resp = qq.authorized_response()
    if resp is None:
        return 'Access denied: reason=%s error=%s' % (
            request.args['error_reason'],
            request.args['error_description']
        )
    session['qq_token'] = (resp['access_token'], '')

    # Get openid via access_token, openid and access_token are needed for API calls
    respMe = qq.get('/oauth2.0/me', {'access_token': session['qq_token'][0]})
    openid = json_to_dict(respMe.data)['openid']

    print(openid)

    resp = qq.get('/user/get_user_info', {'access_token': session['qq_token'][0],
                                                 'openid': openid,
                                                 'oauth_consumer_key': os.environ.get("QQ_APP_ID")})

    resp = eval(resp.data.decode())
    developer = None
    if isinstance(resp, dict):
        session['qq_openid'] = resp.get('openid')
        developer = Developer.query.filter_by(platform_id=openid,
                                              platform='qq').first()

        if developer is None:
            dev_key = generate_dev_key()
            developer = Developer(dev_key=dev_key,
                                  platform='qq',
                                  platform_id=openid,
                                  description='')
            developer.insert_to_db()
    if developer is None:
        developer = get_developer()
    username = developer.username
    if username is None or username == '':
        print('login first time. redirect to setting')
        return redirect(url_for('auth.setting'))
    return redirect(url_for('auth.manage')) 
Example #19
Source File: oauth_v2.py    From python-slackclient with MIT License 5 votes vote down vote up
def oauth_callback():
    # Retrieve the auth code and state from the request params
    if "code" in request.args:
        state = request.args["state"]
        if state_service.consume(state):
            code = request.args["code"]
            client = WebClient()  # no prepared token needed for this app
            response = client.oauth_v2_access(
                client_id=client_id,
                client_secret=client_secret,
                redirect_uri=redirect_uri,
                code=code
            )
            logger.info(f"oauth.v2.access response: {response}")
            database.save(response)
            return "Thanks for installing this app!"
        else:
            return make_response(f"Try the installation again (the state value is already expired)", 400)

    error = request.args["error"] if "error" in request.args else ""
    return make_response(f"Something is wrong with the installation (error: {error})", 400)


# ---------------------
# Flask App for Slack events
# --------------------- 
Example #20
Source File: public.py    From platform with GNU General Public License v3.0 5 votes vote down vote up
def remove():
    return jsonify(message=public.remove(request.args['app_id'])), 200 
Example #21
Source File: flask_utils.py    From Quiver-alfred with MIT License 5 votes vote down vote up
def get_next_url(default='/'):
    if request.args.get('next'):
        return request.args['next']
    elif request.form.get('next'):
        return request.form['next']
    return default 
Example #22
Source File: flask_utils.py    From Quiver-alfred with MIT License 5 votes vote down vote up
def get_page(self):
        curr_page = request.args.get(self.page_var)
        if curr_page and curr_page.isdigit():
            return max(1, int(curr_page))
        return 1 
Example #23
Source File: app.py    From dataiku-contrib with Apache License 2.0 5 votes vote down vote up
def resp_from_url(url):
    response = requests.get(url, stream=True, params=request.args)
    return response.content 
Example #24
Source File: index.py    From watchdog with Apache License 2.0 5 votes vote down vote up
def listManagementAdd(self):
    # retrieve the separate item parts
    item     = request.args.get('item', type=str)
    listType = request.args.get('list', type=str)

    pattern = re.compile('^[a-z:/0-9.~_%-]+$')

    if pattern.match(item):
      item = item.split(":")
      added = False
      if len(item) == 1:
        # only vendor, so a check on cpe type is needed
        if self.redisdb.sismember("t:/o", item[0]):
          if self.addCPEToList("cpe:/o:" + item[0], listType): added = True
        if self.redisdb.sismember("t:/a", item[0]):
          if self.addCPEToList("cpe:/a:" + item[0], listType): added = True
        if self.redisdb.sismember("t:/h", item[0]):
          if self.addCPEToList("cpe:/h:" + item[0], listType): added = True
      elif 4 > len(item) > 1:
        # cpe type can be found with a mongo regex query
        result = db.getCVEs(query={'cpe_2_2': {'$regex': item[1]}})
        if result.count() != 0:
          prefix = ((result[0])['cpe_2_2'])[:7]
          if len(item) == 2:
            if self.addCPEToList(prefix + item[0] + ":" + item[1], listType):
              added = True
          if len(item) == 3:
            if self.addCPEToList(prefix + item[0] + ":" + item[1] + ":" + item[2], listType):
              added = True
      status = "added_to_list" if added else "could_not_add_to_list"
    else:
      status = "invalid_cpe"
    j={"status":status, "listType":listType}
    return jsonify(j)



  # /login 
Example #25
Source File: index.py    From watchdog with Apache License 2.0 5 votes vote down vote up
def filter_logic(self, filters, skip, limit=None):
    query = self.generate_full_query(filters)
    limit = limit if limit else self.args['pageLength']
    cve   = db.getCVEs(limit=limit, skip=skip, query=query)
    # marking relevant records
    if current_user.is_authenticated():
        if filters['whitelistSelect'] == "on":   cve = self.list_mark('white', cve)
        if filters['blacklistSelect'] == "mark": cve = self.list_mark('black', cve)
    self.plugManager.mark(cve, **self.pluginArgs)
    cve = list(cve)
    return cve 
Example #26
Source File: index.py    From watchdog with Apache License 2.0 5 votes vote down vote up
def _get_cve_actions(self):
    cve = request.args.get('cve', type=str)
    if not current_user.is_authenticated(): # Don't show actions requiring auth if not authenticated
      actions = [x for x in self.plugManager.getCVEActions(cve, **self.pluginArgs) if not x['auth']]
    else:
      actions = self.plugManager.getCVEActions(cve, **self.pluginArgs)
    return jsonify({"actions": actions})


  # /plugin/<plugin> 
Example #27
Source File: index.py    From watchdog with Apache License 2.0 5 votes vote down vote up
def openPlugin(self, plugin):
    if self.plugManager.requiresAuth(plugin) and not current_user.is_authenticated():
      return render_template("requiresAuth.html")
    else:
      page, args = self.plugManager.openPage(plugin, **self.pluginArgs)
      if page:
        try:
          return render_template(page, **args)
        except jinja2.exceptions.TemplateSyntaxError: return render_template("error.html", status={'except': 'plugin-page-corrupt'})
        except jinja2.exceptions.TemplateNotFound:    return render_template("error.html", status={'except': 'plugin-page-not-found', 'page': page})
      else: abort(404)


  # /plugin/<plugin>/subpage/<page> 
Example #28
Source File: index.py    From watchdog with Apache License 2.0 5 votes vote down vote up
def openPluginSubpage(self, plugin, page):
    if self.plugManager.requiresAuth(plugin) and not current_user.is_authenticated():
      return render_template("requiresAuth.html")
    else:
      page, args = self.plugManager.openSubpage(plugin, page, **self.pluginArgs)
      if page:
        try:
          return render_template(page, **args)
        except jinja2.exceptions.TemplateSyntaxError: return render_template("error.html", status={'except': 'plugin-page-corrupt'})
        except jinja2.exceptions.TemplateNotFound:    return render_template("error.html", status={'except': 'plugin-page-not-found', 'page': page})
      else: abort(404)


  # /plugin/<plugin>/_cve_action/<action> 
Example #29
Source File: index.py    From watchdog with Apache License 2.0 5 votes vote down vote up
def listAdd(self):
    cpe = request.args.get('cpe')
    cpeType = request.args.get('type')
    lst = request.args.get('list')
    if cpe and cpeType and lst:
      status = "added_to_list" if self.addCPEToList(cpe, lst, cpeType) else "already_exists_in_list"
      returnList = db.getWhitelist() if lst=="whitelist" else db.getBlacklist()
      return jsonify({"status":status, "rules":returnList, "listType":lst.title()})
    else: return jsonify({"status": "could_not_add_to_list"})


  # /admin/removeFromList 
Example #30
Source File: index.py    From watchdog with Apache License 2.0 5 votes vote down vote up
def change_pass(self):
    current_pass = request.args.get('current_pass')
    new_pass     = request.args.get('new_pass')
    if current_user.authenticate(current_pass):
      if new_pass:
        db.changePassword(current_user.id , new_pass)
        return jsonify({"status": "password_changed"})
      return jsonify({"status": "no_password"})
    else:
      return jsonify({"status": "wrong_user_pass"})

  # /admin/request_token