Here are the examples of the python api aiohttp.web.json_response taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
46 Examples
3
Example 1
def jsonify(request, *args, **kwargs):
"""
jsonify with support for MongoDB ObjectId
"""
dumps = partial(json.dumps, cls=MongoJsonEncoder, indent=True)
return json_response(dict(*args, **kwargs), dumps=dumps)
3
Example 2
@asyncio.coroutine
@use_args(hello_args)
def index(request, args):
"""A welcome page.
"""
return json_response({'message': 'Welcome, {}!'.format(args['name'])})
3
Example 3
@asyncio.coroutine
@use_kwargs(dateadd_args)
def dateadd(request, value, addend, unit):
"""A datetime adder endpoint."""
value = value or dt.datetime.utcnow()
if unit == 'minutes':
delta = dt.timedelta(minutes=addend)
else:
delta = dt.timedelta(days=addend)
result = value + delta
return json_response({'result': result.isoformat()})
3
Example 4
@asyncio.coroutine
def always_error(request):
def always_fail(value):
raise ValidationError('something went wrong')
args = {'text': fields.Str(validate=always_fail)}
parsed = yield from parser.parse(args, request)
return json_response(parsed)
3
Example 5
@asyncio.coroutine
def error400(request):
def always_fail(value):
raise ValidationError('something went wrong', status_code=400)
args = {'text': fields.Str(validate=always_fail)}
parsed = yield from parser.parse(args, request)
return json_response(parsed)
3
Example 6
@asyncio.coroutine
def error_invalid(request):
def always_fail(value):
raise ValidationError('something went wrong', status_code=12345)
args = {'text': fields.Str(validate=always_fail)}
parsed = yield from parser.parse(args, request)
return json_response(parsed)
3
Example 7
@asyncio.coroutine
def echo_nested(request):
args = {
'name': fields.Nested({'first': fields.Str(),
'last': fields.Str()})
}
parsed = yield from parser.parse(args, request)
return json_response(parsed)
3
Example 8
@asyncio.coroutine
def echo_nested_many(request):
args = {
'users': fields.Nested({'id': fields.Int(), 'name': fields.Str()}, many=True)
}
parsed = yield from parser.parse(args, request)
return json_response(parsed)
3
Example 9
def configure_status(request):
"""Return /configure/status
:param request: a web requeest object.
:type request: request | None
"""
log.info("Request for configuration validation made.")
code = 200
messages = Config(CONFIG_PATH).do_validate(include_ssh=True)
if messages:
code = 400
resp = web.json_response(messages, status=code)
return resp
3
Example 10
def configure_type(request):
"""Return /configure/type
:param request: a web requeest object.
:type request: request | None
"""
log.info("Request for configuration type made.")
return web.json_response(backend.determine_config_type())
3
Example 11
def success(request):
"""Return /success
:param request: a web requeest object.
:type request: request | None
"""
log.info("Request for success made.")
msgs, code = backend.success(Config(CONFIG_PATH))
return web.json_response(msgs, status=code)
3
Example 12
def action_current(request):
"""Return the current action /action/current endpoint.
:param request: a web requeest object.
:type request: request | None
"""
return web.json_response({'current_action': current_action})
3
Example 13
async def get(self):
return json_response({
'method': 'get',
'args': dict(self.request.GET),
'headers': dict(self.request.headers),
}, dumps=functools.partial(json.dumps, indent=4))
3
Example 14
async def post(self):
data = await self.request.post()
return json_response({
'method': 'post',
'args': dict(self.request.GET),
'data': dict(data),
'headers': dict(self.request.headers),
}, dumps=functools.partial(json.dumps, indent=4))
3
Example 15
def test_data_and_text_raises_value_error(self):
with pytest.raises(ValueError) as excinfo:
json_response(data='foo', text='bar')
expected_message = (
'only one of data, text, or body should be specified'
)
assert expected_message == excinfo.value.args[0]
3
Example 16
def test_data_and_body_raises_value_error(self):
with pytest.raises(ValueError) as excinfo:
json_response(data='foo', body=b'bar')
expected_message = (
'only one of data, text, or body should be specified'
)
assert expected_message == excinfo.value.args[0]
3
Example 17
async def bookshelf_new(request):
"""
Add the given book to the shelf event lake.
"""
payload = await request.content.read()
# ensure the book gets an id
book = json.loads(payload.decode('utf-8'))
book["id"] = str(uuid.uuid4())
# create an event from this request
event = make_event(name="book-added",
payload=json.dumps(book),
safe=False, idempotent=False)
# let's push it
await send_event(b"bookshelf", event)
return web.json_response(status=201, data=book)
3
Example 18
async def bookshelf_view(request):
"""
View to see the current list of books
in your bookshelf.
"""
return web.json_response(data=list(last_read_books))
3
Example 19
async def register(*, name, email, sha1_pw, oid=None, image=None):
check_string(name=name)
check_email_and_password(email, sha1_pw)
users = await User.findAll('email = ?', [email])
if users:
raise APIValueError('email', 'Email is already in used.')
user = User(name=name.strip(), email=email, password=sha1_pw, image=image or '/static/img/user.png')
await user.save()
if oid:
o = Oauth(id=oid, user_id=user.id)
await o.save()
# register ok, signin
return user.signin(web.json_response({'signin user': user.name}))
3
Example 20
async def authenticate(*, email, sha1_pw):
check_email_and_password(email, sha1_pw)
users = await User.findAll('email = ?', [email])
if len(users) == 0:
raise APIValueError('email', 'Email not exist.')
user = users[0]
# check password
if not user.verify_password(sha1_pw):
raise APIValueError('password', 'Invalid password')
# authenticate ok, signin
return user.signin(web.json_response({'signin user': user.name}))
0
Example 21
def build_error(status=400, msg=None):
if status == 404 and not msg:
msg = 'Not found'
return json_response({'message': msg}, status=status)
0
Example 22
@asyncio.coroutine
@use_kwargs(add_args)
def add(request, x, y):
"""An addition endpoint."""
return json_response({'result': x + y})
0
Example 23
@asyncio.coroutine
def echo(request):
parsed = yield from parser.parse(hello_args, request)
return json_response(parsed)
0
Example 24
@asyncio.coroutine
def echo_query(request):
parsed = yield from parser.parse(hello_args, request, locations=('query', ))
return json_response(parsed)
0
Example 25
@asyncio.coroutine
@use_args(hello_args)
def echo_use_args(request, args):
return json_response(args)
0
Example 26
@asyncio.coroutine
@use_kwargs(hello_args)
def echo_use_kwargs(request, name):
return json_response({'name': name})
0
Example 27
@asyncio.coroutine
@use_args({'value': fields.Int()}, validate=lambda args: args['value'] > 42)
def echo_use_args_validated(request, args):
return json_response(args)
0
Example 28
@asyncio.coroutine
def echo_multi(request):
parsed = yield from parser.parse(hello_multiple, request)
return json_response(parsed)
0
Example 29
@asyncio.coroutine
def echo_many_schema(request):
parsed = yield from parser.parse(hello_many_schema, request, locations=('json', ))
return json_response(parsed)
0
Example 30
Project: webargs
License: View license
Source File: aiohttp_app.py
Function: echo_use_args_with_path_param
License: View license
Source File: aiohttp_app.py
Function: echo_use_args_with_path_param
@asyncio.coroutine
@use_args({'value': fields.Int()})
def echo_use_args_with_path_param(request, args):
return json_response(args)
0
Example 31
Project: webargs
License: View license
Source File: aiohttp_app.py
Function: echo_use_kwargs_with_path_param
License: View license
Source File: aiohttp_app.py
Function: echo_use_kwargs_with_path_param
@asyncio.coroutine
@use_kwargs({'value': fields.Int()})
def echo_use_kwargs_with_path_param(request, value):
return json_response({'value': value})
0
Example 32
@asyncio.coroutine
def echo_headers(request):
parsed = yield from parser.parse(hello_args, request, locations=('headers', ))
return json_response(parsed)
0
Example 33
@asyncio.coroutine
def echo_cookie(request):
parsed = yield from parser.parse(hello_args, request, locations=('cookies', ))
return json_response(parsed)
0
Example 34
@asyncio.coroutine
def echo_match_info(request):
parsed = yield from parser.parse({'mymatch': fields.Int(location='match_info')}, request)
return json_response(parsed)
0
Example 35
@asyncio.coroutine
@use_args(hello_args)
def get(self, request, args):
return json_response(args)
0
Example 36
async def api(request):
name = request.match_info['name']
data = {'name': name}
return web.json_response(data)
0
Example 37
def get_version(args):
resp = web.json_response({'version': gen.calc.entry['must']['dcos_version']})
resp.headers['Content-Type'] = 'application/json'
return resp
0
Example 38
def configure(request):
"""Return /api/v1/configure
:param request: a web requeest object.
:type request: request | None
"""
if request.method == 'POST':
new_config = yield from request.json()
# Save ssh_key, ip_detect as needed
# TODO(cmaloney): make ssh_key derive from ssh_key_path so we can just set ssh_key and skip all this.
new_config = extract_external(new_config, 'ssh_key', 'ssh_key_path', SSH_KEY_PATH, 0o600)
# TODO(cmaloney): change this to ip_detect_contents removing the need for the remapping.
new_config = extract_external(new_config, 'ip_detect_script', 'ip_detect_path', IP_DETECT_PATH, 0o644)
log.info('POST to configure: {}'.format(new_config))
messages = backend.create_config_from_post(new_config, CONFIG_PATH)
# Map back to DC/OS UI configuration parameters.
# TODO(cmaloney): Remove need to remap validation keys. The remapping is making things show up
# under the key of the user config chunk that caused them rather than their particular key so
# num_masters validation for instance shows up under master_list where the user would expect it.
if "ssh_key_path" in messages:
messages["ssh_key"] = messages["ssh_key_path"]
if "ip_detect_contents" in messages:
messages['ip_detect_path'] = messages['ip_detect_contents']
if 'num_masters' in messages:
messages['master_list'] = messages['num_masters']
resp = web.json_response({}, status=200)
if messages:
resp = web.json_response(messages, status=400)
return resp
elif request.method == 'GET':
config = Config(CONFIG_PATH).config
# TODO(cmaloney): should exclude the value entirely if the file doesn't exist.
config['ssh_key'] = try_read_file(SSH_KEY_PATH)
config['ip_detect_script'] = try_read_file(IP_DETECT_PATH)
resp = web.json_response(config)
resp.headers['Content-Type'] = 'application/json'
return resp
0
Example 39
def action_action_name(request):
"""Return /action/<action_name>
:param request: a web requeest object.
:type request: request | None
"""
global current_action
action_name = request.match_info['action_name']
# Update the global action
json_state = read_json_state(action_name)
current_action = action_name
if request.method == 'GET':
log.info('GET {}'.format(action_name))
if json_state:
return web.json_response(json_state)
return web.json_response({})
elif request.method == 'POST':
log.info('POST {}'.format(action_name))
action = action_map.get(action_name)
# If the action name is preflight, attempt to run configuration
# generation. If genconf fails, present the UI with a usable error
# for the end-user
if action_name == 'preflight':
try:
log.warning("GENERATING CONFIGURATION")
backend.do_configure()
except:
genconf_failure = {
"errors": "Configuration generation failed, please see command line for details"
}
return web.json_response(genconf_failure, status=400)
params = yield from request.post()
if json_state:
if action_name == 'deploy' and 'retry' in params:
if 'hosts' in json_state:
failed_hosts = []
for deploy_host, deploy_params in json_state['hosts'].items():
if deploy_params['host_status'] != 'success':
failed_hosts.append(Node(deploy_host, tags=deploy_params['tags']))
log.debug('failed hosts: {}'.format(failed_hosts))
if failed_hosts:
yield from asyncio.async(
action(
Config(CONFIG_PATH),
state_json_dir=STATE_DIR,
hosts=failed_hosts,
try_remove_stale_dcos=True,
**params))
return web.json_response({
'status': 'retried',
'details': sorted(['{}:{}'.format(node.ip, node.port) for node in failed_hosts])
})
if action_name not in remove_on_done:
return web.json_response({'status': '{} was already executed, skipping'.format(action_name)})
running = False
for host, attributes in json_state['hosts'].items():
if attributes['host_status'].lower() == 'running':
running = True
log.debug('is action running: {}'.format(running))
if running:
return web.json_response({'status': '{} is running, skipping'.format(action_name)})
else:
unlink_state_file(action_name)
yield from asyncio.async(action(Config(CONFIG_PATH), state_json_dir=STATE_DIR, options=options, **params))
return web.json_response({'status': '{} started'.format(action_name)})
0
Example 40
async def on_me(self, request):
return web.json_response({
"name": "John Doe",
"id": "12345678901234567"
})
0
Example 41
async def on_my_friends(self, request):
return web.json_response({
"data": [
{
"name": "Bill Doe",
"id": "233242342342"
},
{
"name": "Mary Doe",
"id": "2342342343222"
},
{
"name": "Alex Smith",
"id": "234234234344"
},
],
"paging": {
"cursors": {
"before": "QVFIUjRtc2c5NEl0ajN",
"after": "QVFIUlpFQWM0TmVuaDRad0dt",
},
"next": ("https://graph.facebook.com/v2.7/12345678901234567/"
"friends?access_token=EAACEdEose0cB")
},
"summary": {
"total_count": 3
}})
0
Example 42
def test_content_type_is_application_json_by_default(self):
resp = json_response('')
assert 'application/json' == resp.content_type
0
Example 43
def test_passing_text_only(self):
resp = json_response(text=json.dumps('jaysawn'))
assert resp.text == json.dumps('jaysawn')
0
Example 44
def test_text_is_json_encoded(self):
resp = json_response({'foo': 42})
assert json.dumps({'foo': 42}) == resp.text
0
Example 45
def test_content_type_is_overrideable(self):
resp = json_response({'foo': 42},
content_type='application/vnd.json+api')
assert 'application/vnd.json+api' == resp.content_type
0
Example 46
async def json(self, request):
return aiohttp.web.json_response({
'events': self.get_last_events(request),
}, headers={"Vary": "Accept", 'Access-Control-Allow-Origin': request.headers.get('Origin', '*')})