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 |
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 |
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 |
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 |
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 |
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: auth.py From eve-auth-jwt with MIT License | 6 votes |
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 #7
Source File: auth.py From eve-auth-jwt with MIT License | 6 votes |
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 #8
Source File: Server.py From uplink with MIT License | 6 votes |
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 #9
Source File: ui.py From gransk with Apache License 2.0 | 6 votes |
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 #10
Source File: ui.py From gransk with Apache License 2.0 | 6 votes |
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 #11
Source File: index.py From watchdog with Apache License 2.0 | 6 votes |
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 #12
Source File: metagame.py From Penny-Dreadful-Tools with GNU General Public License v3.0 | 6 votes |
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 #13
Source File: rest_api_plugin.py From airflow-rest-api-plugin with Apache License 2.0 | 6 votes |
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 #14
Source File: views_api.py From everyclass-server with Mozilla Public License 2.0 | 5 votes |
def get_advice(): args = request.args answers = [] for k, v in args.items(): answers.append(Answer(int(k), list(map(int, v.split(','))))) return generate_success_response(course_service.get_advice_result(AnswerSheet(answers)))
Example #15
Source File: views.py From everyclass-server with Mozilla Public License 2.0 | 5 votes |
def register_by_password_status(): """AJAX 刷新教务验证状态""" if not request.args.get("request", None) or not isinstance(request.args["request"], str): return "Invalid request" try: success, message, identifier = user_service.register_by_password_status_refresh(request.args.get("request")) if success: # write login state to session flash(MSG_REGISTER_SUCCESS) if SESSION_PWD_VER_REQ_ID in session: del session[SESSION_PWD_VER_REQ_ID] _set_current_user(identifier) # potential uncaught error return jsonify({"message": "SUCCESS"}) elif message in ("PASSWORD_WRONG", "INTERNAL_ERROR", "INVALID_REQUEST_ID"): return jsonify({"message": message}) else: return jsonify({"message": "NEXT_TIME"}) except everyclass.server.user.exceptions.IdentityVerifyRequestNotFoundError: return "Invalid request" except user_service.IdentityVerifyMethodNotExpectedError: return "Invalid request" except everyclass.server.user.exceptions.AlreadyRegisteredError: # 已经注册成功,但不知为何(可能是网络原因)进入了中间状态,没有执行下面的删除 session 的代码,并且用户刷新页面 if SESSION_PWD_VER_REQ_ID in session: del session[SESSION_PWD_VER_REQ_ID] flash(MSG_ALREADY_REGISTERED) return redirect(url_for('user.login'))
Example #16
Source File: views.py From MPContribs with MIT License | 5 votes |
def rootfind(a, b, args, funciso_here): solutioniso = 0 try: solutioniso = brentq( funciso_here, 0.01, 0.49, args=args ) # works for most cases except ValueError: # starting values a,b for cases where 0.01/0.49 are not sign changing try: solutioniso = brentq(funciso_here, a, b, args=args) except ValueError: solutioniso = None # if no solution can be found return solutioniso
Example #17
Source File: zmirror.py From zmirror with MIT License | 5 votes |
def response_text_basic_rewrite(*args, **kwargs): # coverage: exclude """本函数在v0.28.3被移除, 对本函数的调用会被映射出去 如果需要查看本函数代码, 请查看git历史到 v0.28.3 以前 """ from warnings import warn warn("This function is deprecated since v0.28.3, use response_text_basic_mirrorlization() instead", DeprecationWarning) return response_text_basic_mirrorlization(*args, **kwargs)
Example #18
Source File: auth.py From eve-auth-jwt with MIT License | 5 votes |
def authenticate(self): """ Indicate to the client that it needs to authenticate via a 401. """ if request.headers.get('Authorization') or request.args.get('access_token'): realm = 'Bearer realm="%s", error="invalid_token"' % __package__ else: realm = 'Bearer realm="%s"' % __package__ resp = Response(None, 401, {'WWW-Authenticate': realm}) abort(401, description='Please provide proper credentials', response=resp)
Example #19
Source File: server.py From grlc with MIT License | 5 votes |
def api_docs_param(): """Grlc API page for specifications loaded via http.""" # Get queries provided by params spec_url = request.args['specUrl'] glogger.info("Spec URL: {}".format(spec_url)) return api_docs_template() # Spec generation, JSON
Example #20
Source File: server.py From grlc with MIT License | 5 votes |
def swagger_spec_param(): """Swagger spec for specifications loaded via http.""" spec_url = request.args['specUrl'] glogger.info("Spec URL: {}".format(spec_url)) return swagger_spec(user=None, repo=None, spec_url=spec_url) # Callname execution
Example #21
Source File: server.py From grlc with MIT License | 5 votes |
def query_param(query_name): """SPARQL query execution for specifications loaded via http.""" spec_url = request.args['specUrl'] glogger.debug("Spec URL: {}".format(spec_url)) return query(user=None, repo=None, query_name=query_name, spec_url=spec_url) ############################## ### Routes for GitHub APIs ### ############################## # Spec generation, front-end
Example #22
Source File: gquery.py From grlc with MIT License | 5 votes |
def guess_endpoint_uri(rq, gh_repo): """ Guesses the endpoint URI from (in this order): - An endpoint parameter in URL - An #+endpoint decorator - A endpoint.txt file in the repo Otherwise assigns a default one """ auth = (static.DEFAULT_ENDPOINT_USER, static.DEFAULT_ENDPOINT_PASSWORD) if auth == ('none', 'none'): auth = None if has_request_context() and "endpoint" in request.args: endpoint = request.args['endpoint'] glogger.info("Endpoint provided in request: " + endpoint) return endpoint, auth # Decorator try: decorators = get_yaml_decorators(rq) endpoint = decorators['endpoint'] auth = None glogger.info("Decorator guessed endpoint: " + endpoint) except (TypeError, KeyError): # File try: endpoint_content = gh_repo.getTextFor({'download_url': 'endpoint.txt'}) endpoint = endpoint_content.strip().splitlines()[0] auth = None glogger.info("File guessed endpoint: " + endpoint) # TODO: except all is really ugly except: # Default endpoint = static.DEFAULT_ENDPOINT auth = (static.DEFAULT_ENDPOINT_USER, static.DEFAULT_ENDPOINT_PASSWORD) if auth == ('none', 'none'): auth = None glogger.warning("No endpoint specified, using default ({})".format(endpoint)) return endpoint, auth
Example #23
Source File: main.py From iris with MIT License | 5 votes |
def do_tag(): f = retrieve(request.args['plugin']) if f is not None: project_id = request.args['project_id'] f.do_tag(project_id) return 'ok', 200
Example #24
Source File: srv.py From rate.sx with MIT License | 5 votes |
def answer(topic = None): """ Main rendering function, it processes incoming weather queries. Depending on user agent it returns output in HTML or ANSI format. Incoming data: request.args request.headers request.remote_addr request.referrer request.query_string """ user_agent = request.headers.get('User-Agent', '').lower() html_needed = is_html_needed(user_agent) options = parse_query(request.args) hostname = request.headers['Host'] if request.headers.getlist("X-Forwarded-For"): ip = request.headers.getlist("X-Forwarded-For")[0] if ip.startswith('::ffff:'): ip = ip[7:] else: ip = request.remote_addr if topic is None: topic = ":firstpage" answer = cmd_wrapper(topic, hostname=hostname, request_options=options, html=is_html_needed(user_agent)) if ip not in SKIP_LOGGING_FOR_THIS_IPS: log_query(ip, hostname, topic, user_agent) return answer
Example #25
Source File: views.py From CTask with GNU General Public License v3.0 | 5 votes |
def show_jobs(): '''获取所有jobs信息''' response = {} try: jid = request.args.get('id') if jid == None: ret_list = scheduler.get_jobs() else: ret_list = [scheduler.get_job(jid)] inof_list = [] for ret in ret_list: fields = ret.trigger.fields cron = {} for field in fields: cron[field.name] = str(field) cron_list = [cron['second'],cron['minute'],cron['hour'],cron['day'],cron['month'],cron['day_of_week']] info = { 'id':ret.id, 'next_run_time':ret.next_run_time, 'cmd':ret.kwargs.get('cmd'), #'func':ret.func_ref, 'status':'running' if ret.next_run_time != None else 'stop', 'cron':' '.join(cron_list) } inof_list.append(info) response['status'] = 0 response['data'] = inof_list response['count'] = len(inof_list) except Exception as e: response['msg'] = str(e) return json.dumps(response,cls=DateEncoder)
Example #26
Source File: views.py From CTask with GNU General Public License v3.0 | 5 votes |
def job_log(): '''获取所有job log信息''' response = {} try: ret = get_job_logs(request.args) response['status'] = 0 response['data'] = ret response['count'] = len(ret) except Exception as e: response['msg'] = str(e) return json.dumps(response,cls=DateEncoder)
Example #27
Source File: Server.py From uplink with MIT License | 5 votes |
def users_for_repo(user, repo_name): """ /users/<user>/repo/<repo_name>[?oldest-age=<age in weeks>] Returns list of users who have commited in the resource user/repo in the last given amount of weeks """ oldest_age = ( 55 if "oldest-age" not in request.args else request.args["oldest-age"] ) future = _users_for_repo(user, repo_name, oldest_age=oldest_age) users = loop.run_until_complete(future) return jsonify(users)
Example #28
Source File: Server.py From uplink with MIT License | 5 votes |
def users_for_keyword(): """ /users?keyword=<keyword>[?oldest-age=<age in weeks>] Find the top users who have commited in repositories matching the keyword in the last month """ if "keyword" not in request.args: return "", 400 keyword = request.args["keyword"] oldest_age = ( 55 if "oldest-age" not in request.args else request.args["oldest-age"] ) repos_future = _repos_for_keyword(keyword) repos = loop.run_until_complete(repos_future) # gather futures for getting users from each repo users_futures = [] users = set() for repo in repos: user, repo_name = repo.split("/") users_futures.append( _users_for_repo(user, repo_name, oldest_age=oldest_age) ) # barrier on all the users futures users_results = loop.run_until_complete(asyncio.wait(users_futures)) # gather the results for users_result in users_results: for task in users_result: if task.result(): users.update(set(task.result())) return jsonify(list(users))
Example #29
Source File: __init__.py From PT-help with MIT License | 5 votes |
def geo(): if not request.args: return no_args_waring else: ip = request.args.get("ip") ret_dict = { "stats": "Fail", "ip": ip, "loc": "Not Find IP address." if ip is None else None } ret_dict.update(ip_query.searchIp(ip)) return jsonify(ret_dict)
Example #30
Source File: bench_test.py From pyspider with Apache License 2.0 | 5 votes |
def bench_test(): total = int(request.args.get('total', 10000)) show = int(request.args.get('show', 20)) nlist = [random.randint(1, total) for _ in range(show)] result = [] result.append("<html><head></head><body>") args = dict(request.args) for nl in nlist: args['n'] = nl argstr = urlencode(sorted(args.items()), doseq=True) result.append("<a href='/bench?{0}'>follow {1}</a><br>".format(argstr, nl)) result.append("</body></html>") return "".join(result)