Here are the examples of the python api flask.request.method.lower taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
20 Examples
3
Example 1
def dispatch_request(self, *args, **kwargs):
method = getattr(self, request.method.lower(), None)
if method is None and request.method == 'HEAD':
method = getattr(self, 'get', None)
assert method is not None, 'Unimplemented method %r' % request.method
response = method(*args, **kwargs)
if isinstance(response, Response):
return response
data, code, headers = unpack(response)
response = output_json(data, code, headers)
response.headers['Content-type'] = 'application/json'
return response
3
Example 2
def api_list(self):
if not getattr(self, 'check_%s' % request.method.lower())():
return self.response_forbidden()
if request.method == 'GET':
return self.object_list()
elif request.method == 'POST':
return self.create()
3
Example 3
Project: frasco Source File: views.py
def exec_after_request_actions(actions, response, **kwargs):
"""Executes actions of the "after" and "after_METHOD" groups.
A "response" var will be injected in the current context.
"""
current_context["response"] = response
groups = ("after_" + flask.request.method.lower(), "after")
try:
rv = execute_actions(actions, limit_groups=groups, **kwargs)
except ReturnValueException as e:
rv = e.value
if rv:
return rv
return response
3
Example 4
Project: ggrc-core Source File: log_event.py
def log_event():
'''Log javascript client errors to syslog via application logger.'''
method = request.method.lower()
if method == 'post':
severity = request.json['log_event']['severity']
description = request.json['log_event']['description']
logger.error('Javascript Client: %s %s', severity, description)
return current_app.make_response(('', 200, []))
raise NotImplementedError()
3
Example 5
def dispatch_request(self, *args, **kwargs):
method = request.method.lower()
if method == 'get':
if self.pk in kwargs and kwargs[self.pk] is not None:
return self.get(*args, **kwargs)
else:
# No `pk` given; fallthrough for now
pass
else:
# Method not supported; fallthrough for now
pass
raise NotImplementedError()
3
Example 6
def dispatch_request(self, **kwargs):
"""Dispatches requests to the corresponding method name.
Similar to the :class:`flask.views.MethodView` implementation: GET requests
are passed to :meth:`get`, POST to :meth:`post`, etc.
"""
meth = getattr(self, request.method.lower(), None)
if meth is None and request.method == 'HEAD':
meth = getattr(self, 'get', None)
return meth(**kwargs)
3
Example 7
Project: jones Source File: web.py
@app.route('/service/<string:service>/', defaults={'env': None},
methods=ALL_METHODS)
@app.route('/service/<string:service>/<path:env>/', methods=ALL_METHODS)
def services(service, env):
jones = Jones(service, get_zk())
environment = Env(env)
return SERVICE[request.method.lower()](environment, jones)
2
Example 8
Project: cookiecutter-webapp Source File: base.py
def enforce_json_post_put_patch_requests():
"""
Incoming POST, PUT and PATCH requests should have Content-Type set to
'application/json' or else a 415 - Unsupported Media Type is returned.
"""
options = request_options.parse_args()
content_type, options = parse_options_header(options.get("Content-Type"))
content_json = content_type == 'application/json'
post_put_or_patch = request.method.lower() in ['post', 'put', 'patch']
if post_put_or_patch and not content_json:
abort(415)
0
Example 9
Project: flask-restful Source File: __init__.py
def dispatch_request(self, *args, **kwargs):
# Taken from flask
#noinspection PyUnresolvedReferences
meth = getattr(self, request.method.lower(), None)
if meth is None and request.method == 'HEAD':
meth = getattr(self, 'get', None)
assert meth is not None, 'Unimplemented method %r' % request.method
for decorator in self.method_decorators:
meth = decorator(meth)
resp = meth(*args, **kwargs)
if isinstance(resp, ResponseBase): # There may be a better way to test
return resp
representations = self.representations or OrderedDict()
#noinspection PyUnresolvedReferences
mediatype = request.accept_mimetypes.best_match(representations, default=None)
if mediatype in representations:
data, code, headers = unpack(resp)
resp = representations[mediatype](data, code, headers)
resp.headers['Content-Type'] = mediatype
return resp
return resp
0
Example 10
Project: frasco Source File: views.py
def exec_before_request_actions(actions, **kwargs):
"""Execute actions in the "before" and "before_METHOD" groups
"""
groups = ("before", "before_" + flask.request.method.lower())
return execute_actions(actions, limit_groups=groups, **kwargs)
0
Example 11
Project: frasco Source File: views.py
def exec_request_actions(actions, **kwargs):
"""Execute actions in the None and METHOD groups
"""
groups = (None, flask.request.method.lower())
return execute_actions(actions, limit_groups=groups, **kwargs)
0
Example 12
def dispatch_request(self):
try:
if request.method.lower() not in ('get', 'post'):
raise HttpError(MethodNotAllowed(['GET', 'POST'], 'GraphQL only supports GET and POST requests.'))
data = self.parse_body(request)
show_graphiql = self.graphiql and self.can_display_graphiql(data)
query, variables, operation_name = self.get_graphql_params(request, data)
execution_result = self.execute_graphql_request(
data,
query,
variables,
operation_name,
show_graphiql
)
if execution_result:
response = {}
if execution_result.errors:
response['errors'] = [self.format_error(e) for e in execution_result.errors]
if execution_result.invalid:
status_code = 400
else:
status_code = 200
response['data'] = execution_result.data
result = self.json_encode(request, response)
else:
result = None
if show_graphiql:
return render_graphiql(
graphiql_version=self.graphiql_version,
query=query,
variables=variables,
operation_name=operation_name,
result=result
)
return Response(
status=status_code,
response=result,
content_type='application/json'
)
except HttpError as e:
return Response(
self.json_encode(request, {
'errors': [self.format_error(e)]
}),
status=e.response.code,
headers={'Allow': ['GET, POST']},
content_type='application/json'
)
0
Example 13
def execute_graphql_request(self, data, query, variables, operation_name, show_graphiql=False):
if not query:
if show_graphiql:
return None
raise HttpError(BadRequest('Must provide query string.'))
try:
source = Source(query, name='GraphQL request')
ast = parse(source)
validation_errors = validate(self.schema, ast)
if validation_errors:
return ExecutionResult(
errors=validation_errors,
invalid=True,
)
except Exception as e:
return ExecutionResult(errors=[e], invalid=True)
if request.method.lower() == 'get':
operation_ast = get_operation_ast(ast, operation_name)
if operation_ast and operation_ast.operation != 'query':
if show_graphiql:
return None
raise HttpError(MethodNotAllowed(
['POST'], 'Can only perform a {} operation from a POST request.'.format(operation_ast.operation)
))
try:
return self.execute(
ast,
root_value=self.get_root_value(request),
variable_values=variables or {},
operation_name=operation_name,
context_value=self.get_context(request),
middleware=self.middleware,
executor=self.executor
)
except Exception as e:
return ExecutionResult(errors=[e], invalid=True)
0
Example 14
Project: flask-limiter Source File: test_flask_ext.py
def test_pluggable_views(self):
app, limiter = self.build_app(
global_limits=["1/hour"]
)
class Va(View):
methods = ['GET', 'POST']
decorators = [limiter.limit("2/second")]
def dispatch_request(self):
return request.method.lower()
class Vb(View):
methods = ['GET']
decorators = [limiter.limit("1/second, 3/minute")]
def dispatch_request(self):
return request.method.lower()
class Vc(View):
methods = ['GET']
def dispatch_request(self):
return request.method.lower()
app.add_url_rule("/a", view_func=Va.as_view("a"))
app.add_url_rule("/b", view_func=Vb.as_view("b"))
app.add_url_rule("/c", view_func=Vc.as_view("c"))
with hiro.Timeline().freeze() as timeline:
with app.test_client() as cli:
self.assertEqual(200, cli.get("/a").status_code)
self.assertEqual(200, cli.get("/a").status_code)
self.assertEqual(429, cli.post("/a").status_code)
self.assertEqual(200, cli.get("/b").status_code)
timeline.forward(1)
self.assertEqual(200, cli.get("/b").status_code)
timeline.forward(1)
self.assertEqual(200, cli.get("/b").status_code)
timeline.forward(1)
self.assertEqual(429, cli.get("/b").status_code)
self.assertEqual(200, cli.get("/c").status_code)
self.assertEqual(429, cli.get("/c").status_code)
0
Example 15
Project: flask-limiter Source File: test_flask_ext.py
def test_pluggable_method_views(self):
app, limiter = self.build_app(
global_limits=["1/hour"]
)
class Va(MethodView):
decorators = [limiter.limit("2/second")]
def get(self):
return request.method.lower()
def post(self):
return request.method.lower()
class Vb(MethodView):
decorators = [limiter.limit("1/second, 3/minute")]
def get(self):
return request.method.lower()
class Vc(MethodView):
def get(self):
return request.method.lower()
class Vd(MethodView):
decorators = [limiter.limit("1/minute", methods=['get'])]
def get(self):
return request.method.lower()
def post(self):
return request.method.lower()
app.add_url_rule("/a", view_func=Va.as_view("a"))
app.add_url_rule("/b", view_func=Vb.as_view("b"))
app.add_url_rule("/c", view_func=Vc.as_view("c"))
app.add_url_rule("/d", view_func=Vd.as_view("d"))
with hiro.Timeline().freeze() as timeline:
with app.test_client() as cli:
self.assertEqual(200, cli.get("/a").status_code)
self.assertEqual(200, cli.get("/a").status_code)
self.assertEqual(429, cli.get("/a").status_code)
self.assertEqual(429, cli.post("/a").status_code)
self.assertEqual(200, cli.get("/b").status_code)
timeline.forward(1)
self.assertEqual(200, cli.get("/b").status_code)
timeline.forward(1)
self.assertEqual(200, cli.get("/b").status_code)
timeline.forward(1)
self.assertEqual(429, cli.get("/b").status_code)
self.assertEqual(200, cli.get("/c").status_code)
self.assertEqual(429, cli.get("/c").status_code)
self.assertEqual(200, cli.get("/d").status_code)
self.assertEqual(429, cli.get("/d").status_code)
self.assertEqual(200, cli.post("/d").status_code)
self.assertEqual(200, cli.post("/d").status_code)
0
Example 16
Project: flask-limiter Source File: test_flask_ext.py
def test_flask_restful_resource(self):
app, limiter = self.build_app(
global_limits=["1/hour"]
)
api = restful.Api(app)
class Va(Resource):
decorators = [limiter.limit("2/second")]
def get(self):
return request.method.lower()
def post(self):
return request.method.lower()
class Vb(Resource):
decorators = [limiter.limit("1/second, 3/minute")]
def get(self):
return request.method.lower()
class Vc(Resource):
def get(self):
return request.method.lower()
api.add_resource(Va, "/a")
api.add_resource(Vb, "/b")
api.add_resource(Vc, "/c")
with hiro.Timeline().freeze() as timeline:
with app.test_client() as cli:
self.assertEqual(200, cli.get("/a").status_code)
self.assertEqual(200, cli.get("/a").status_code)
self.assertEqual(429, cli.get("/a").status_code)
self.assertEqual(429, cli.post("/a").status_code)
self.assertEqual(200, cli.get("/b").status_code)
timeline.forward(1)
self.assertEqual(200, cli.get("/b").status_code)
timeline.forward(1)
self.assertEqual(200, cli.get("/b").status_code)
timeline.forward(1)
self.assertEqual(429, cli.get("/b").status_code)
self.assertEqual(200, cli.get("/c").status_code)
self.assertEqual(429, cli.get("/c").status_code)
0
Example 17
def get_request_data():
"""
Get request data based on request.method
If method is GET or DELETE, get data from request.args
If method is POST, PATCH or PUT, get data from request.form or request.json
"""
method = request.method.lower()
if method in ["get", "delete"]:
return request.args
elif method in ["post", "put", "patch"]:
if request.mimetype == 'application/json':
try:
return request.get_json()
except:
abort(400, "InvalidData", "invalid json content")
else:
return request.form
else:
return None
0
Example 18
def make_view(self, action_group):
"""
Create a view function
Check permission and Dispatch request to action by request.method
"""
def view(*args, **kwargs):
try:
httpmathod = request.method.lower()
if httpmathod not in action_group:
abort(405)
resp = self._before_request()
if resp is None:
fn = action_group[httpmathod]
resp = fn(get_request_data())
except Exception as ex:
resp = self._handle_error(ex)
if resp is None:
raise
resp = self._after_request(*unpack(resp))
return export(*resp)
return view
0
Example 19
Project: Flask-ACL Source File: extension.py
def route_acl(self, *acl, **options):
"""Decorator to attach an ACL to a route.
E.g::
@app.route('/url/to/view')
@authz.route_acl('''
ALLOW WHEEL ALL
DENY ANY ALL
''')
def my_admin_function():
pass
"""
def _route_acl(func):
func.__acl__ = acl
@functools.wraps(func)
def wrapped(*args, **kwargs):
permission = 'http.' + request.method.lower()
local_opts = options.copy()
local_opts.setdefault('default', current_app.config['ACL_ROUTE_DEFAULT_STATE'])
self.assert_can(permission, func, **local_opts)
return func(*args, **kwargs)
return wrapped
return _route_acl
0
Example 20
def dispatch_request(self, *args, **kwargs):
# Taken from flask
meth = getattr(self, request.method.lower(), None)
if meth is None and request.method == 'HEAD':
meth = getattr(self, 'get', None)
assert meth is not None, 'Unimplemented method %r' % request.method
for decorator in self.method_decorators:
meth = decorator(meth)
self.validate_payload(meth)
resp = meth(*args, **kwargs)
if isinstance(resp, Response): # There may be a better way to test
return resp
representations = self.representations or {}
mediatype = request.accept_mimetypes.best_match(representations, default=None)
if mediatype in representations:
data, code, headers = unpack(resp)
resp = representations[mediatype](data, code, headers)
resp.headers['Content-Type'] = mediatype
return resp
return resp