本文整理汇总了Python中mediagoblin.tools.response.json_response函数的典型用法代码示例。如果您正苦于以下问题:Python json_response函数的具体用法?Python json_response怎么用?Python json_response使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了json_response函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: wrapper
def wrapper(request, *args, **kwargs):
data = request.headers
authorization = decode_authorization_header(data)
if authorization == dict():
error = "Missing required parameter."
return json_response({"error": error}, status=400)
request_validator = GMGRequestValidator()
resource_endpoint = ResourceEndpoint(request_validator)
valid, r = resource_endpoint.validate_protected_resource_request(
uri=request.url,
http_method=request.method,
body=request.data,
headers=dict(request.headers),
)
if not valid:
error = "Invalid oauth prarameter."
return json_response({"error": error}, status=400)
# Fill user if not already
token = authorization[u"oauth_token"]
request.access_token = AccessToken.query.filter_by(token=token).first()
if request.access_token is not None and request.user is None:
user_id = request.access_token.actor
request.user = LocalUser.query.filter_by(id=user_id).first()
return controller(request, *args, **kwargs)
示例2: access_token
def access_token(request):
""" Provides an access token based on a valid verifier and request token """
data = request.headers
parsed_tokens = decode_authorization_header(data)
if parsed_tokens == dict() or "oauth_token" not in parsed_tokens:
error = "Missing required parameter."
return json_response({"error": error}, status=400)
request.resource_owner_key = parsed_tokens["oauth_consumer_key"]
request.oauth_token = parsed_tokens["oauth_token"]
request_validator = GMGRequestValidator(data)
# Check that the verifier is valid
verifier_valid = request_validator.validate_verifier(
token=request.oauth_token,
verifier=parsed_tokens["oauth_verifier"]
)
if not verifier_valid:
error = "Verifier code or token incorrect"
return json_response({"error": error}, status=401)
av = AccessTokenEndpoint(request_validator)
tokens = av.create_access_token(request, {})
return form_response(tokens)
示例3: authorize
def authorize(request, client):
# TODO: Get rid of the JSON responses in this view, it's called by the
# user-agent, not the client.
user_client_relation = OAuthUserClient.query.filter(
(OAuthUserClient.user == request.user)
& (OAuthUserClient.client == client))
if user_client_relation.filter(OAuthUserClient.state ==
u'approved').count():
redirect_uri = None
if client.type == u'public':
if not client.redirect_uri:
return json_response({
'status': 400,
'errors':
[u'Public clients should have a redirect_uri pre-set.']},
_disable_cors=True)
redirect_uri = client.redirect_uri
if client.type == u'confidential':
redirect_uri = request.GET.get('redirect_uri', client.redirect_uri)
if not redirect_uri:
return json_response({
'status': 400,
'errors': [u'No redirect_uri supplied!']},
_disable_cors=True)
code = OAuthCode()
code.user = request.user
code.client = client
code.save()
redirect_uri = ''.join([
redirect_uri,
'?',
urlencode({'code': code.code})])
_log.debug('Redirecting to {0}'.format(redirect_uri))
return redirect(request, location=redirect_uri)
else:
# Show prompt to allow client to access data
# - on accept: send the user agent back to the redirect_uri with the
# code parameter
# - on deny: send the user agent back to the redirect uri with error
# information
form = AuthorizationForm(request.form)
form.client_id.data = client.id
form.next.data = request.url
return render_to_response(
request,
'oauth/authorize.html',
{'form': form,
'client': client})
示例4: post_entry
def post_entry(request):
_log.debug('Posting entry')
if request.method == 'OPTIONS':
return json_response({'status': 200})
if request.method != 'POST':
_log.debug('Must POST against post_entry')
raise BadRequest()
if not check_file_field(request, 'file'):
_log.debug('File field not found')
raise BadRequest()
upload_limit, max_file_size = get_upload_file_limits(request.user)
callback_url = request.form.get('callback_url')
if callback_url:
callback_url = unicode(callback_url)
try:
entry = submit_media(
mg_app=request.app, user=request.user,
submitted_file=request.files['file'],
filename=request.files['file'].filename,
title=unicode(request.form.get('title')),
description=unicode(request.form.get('description')),
license=unicode(request.form.get('license', '')),
upload_limit=upload_limit, max_file_size=max_file_size,
callback_url=callback_url)
return json_response(get_entry_serializable(entry, request.urlgen))
# Handle upload limit issues
except FileUploadLimit:
raise BadRequest(
_(u'Sorry, the file size is too big.'))
except UserUploadLimit:
raise BadRequest(
_('Sorry, uploading this file will put you over your'
' upload limit.'))
except UserPastUploadLimit:
raise BadRequest(
_('Sorry, you have reached your upload limit.'))
except Exception as e:
'''
This section is intended to catch exceptions raised in
mediagoblin.media_types
'''
if isinstance(e, InvalidFileType) or \
isinstance(e, FileTypeNotSupported):
raise BadRequest(unicode(e))
else:
raise
示例5: post_entry
def post_entry(request):
_log.debug('Posting entry')
if request.method == 'OPTIONS':
return json_response({'status': 200})
if request.method != 'POST':
_log.debug('Must POST against post_entry')
raise BadRequest()
if not check_file_field(request, 'file'):
_log.debug('File field not found')
raise BadRequest()
media_file = request.files['file']
media_type, media_manager = sniff_media(media_file)
entry = new_upload_entry(request.user)
entry.media_type = unicode(media_type)
entry.title = unicode(request.form.get('title')
or splitext(media_file.filename)[0])
entry.description = unicode(request.form.get('description'))
entry.license = unicode(request.form.get('license', ''))
entry.generate_slug()
# queue appropriately
queue_file = prepare_queue_task(request.app, entry, media_file.filename)
with queue_file:
queue_file.write(request.files['file'].stream.read())
# Save now so we have this data before kicking off processing
entry.save()
if request.form.get('callback_url'):
metadata = request.db.ProcessingMetaData()
metadata.media_entry = entry
metadata.callback_url = unicode(request.form['callback_url'])
metadata.save()
# Pass off to processing
#
# (... don't change entry after this point to avoid race
# conditions with changes to the document via processing code)
feed_url = request.urlgen(
'mediagoblin.user_pages.atom_feed',
qualified=True, user=request.user.username)
run_process_media(entry, feed_url)
return json_response(get_entry_serializable(entry, request.urlgen))
示例6: host_meta
def host_meta(request):
""" /.well-known/host-meta - provide URLs to resources """
links = []
links.append({
"ref": "registration_endpoint",
"href": request.urlgen(
"mediagoblin.oauth.client_register",
qualified=True
),
})
links.append({
"ref": "http://apinamespace.org/oauth/request_token",
"href": request.urlgen(
"mediagoblin.oauth.request_token",
qualified=True
),
})
links.append({
"ref": "http://apinamespace.org/oauth/authorize",
"href": request.urlgen(
"mediagoblin.oauth.authorize",
qualified=True
),
})
links.append({
"ref": "http://apinamespace.org/oauth/access_token",
"href": request.urlgen(
"mediagoblin.oauth.access_token",
qualified=True
),
})
return json_response({"links": links})
示例7: object
def object(request, raw_obj=False):
""" Lookup for a object type """
object_type = request.matchdict["objectType"]
try:
object_id = int(request.matchdict["id"])
except ValueError:
error = "Invalid object ID '{0}' for '{1}'".format(
request.matchdict["id"],
object_type
)
return json_error(error)
if object_type not in ["image"]:
# not sure why this is 404, maybe ask evan. Maybe 400?
return json_error(
"Unknown type: {0}".format(object_type),
status=404
)
media = MediaEntry.query.filter_by(id=object_id).first()
if media is None:
error = "Can't find '{0}' with ID '{1}'".format(
object_type,
object_id
)
return json_error(
"Can't find '{0}' with ID '{1}'".format(object_type, object_id),
status=404
)
if raw_obj:
return media
return json_response(media.serialize(request))
示例8: object_comments
def object_comments(request):
""" Looks up for the comments on a object """
public_id = request.urlgen(
"mediagoblin.api.object",
object_type=request.matchdict["object_type"],
id=request.matchdict["id"],
qualified=True
)
media = MediaEntry.query.filter_by(public_id=public_id).first()
if media is None:
return json_error("Can't find '{0}' with ID '{1}'".format(
request.matchdict["object_type"],
request.matchdict["id"]
), 404)
comments = media.serialize(request)
comments = comments.get("replies", {
"totalItems": 0,
"items": [],
"url": request.urlgen(
"mediagoblin.api.object.comments",
object_type=media.object_type,
id=media.id,
qualified=True
)
})
comments["displayName"] = "Replies to {0}".format(comments["url"])
comments["links"] = {
"first": comments["url"],
"self": comments["url"],
}
return json_response(comments)
示例9: object_endpoint
def object_endpoint(request):
""" Lookup for a object type """
object_type = request.matchdict["object_type"]
try:
object_id = request.matchdict["id"]
except ValueError:
error = "Invalid object ID '{0}' for '{1}'".format(
request.matchdict["id"],
object_type
)
return json_error(error)
if object_type not in ["image"]:
# not sure why this is 404, maybe ask evan. Maybe 400?
return json_error(
"Unknown type: {0}".format(object_type),
status=404
)
public_id = request.urlgen(
"mediagoblin.api.object",
object_type=object_type,
id=object_id,
qualified=True
)
media = MediaEntry.query.filter_by(public_id=public_id).first()
if media is None:
return json_error(
"Can't find '{0}' with ID '{1}'".format(object_type, object_id),
status=404
)
return json_response(media.serialize(request))
示例10: object_comments
def object_comments(request):
""" Looks up for the comments on a object """
media = object(request, raw_obj=True)
response = media
if isinstance(response, MediaEntry):
comments = response.serialize(request)
comments = comments.get("replies", {
"totalItems": 0,
"items": [],
"url": request.urlgen(
"mediagoblin.federation.object.comments",
objectType=media.objectType,
uuid=media.id,
qualified=True
)
})
comments["displayName"] = "Replies to {0}".format(comments["url"])
comments["links"] = {
"first": comments["url"],
"self": comments["url"],
}
response = json_response(comments)
return response
示例11: request_token
def request_token(request):
""" Returns request token """
try:
data = decode_request(request)
except ValueError:
error = "Could not decode data."
return json_response({"error": error}, status=400)
if data == "":
error = "Unknown Content-Type"
return json_response({"error": error}, status=400)
if not data and request.headers:
data = request.headers
data = dict(data) # mutableifying
authorization = decode_authorization_header(data)
if authorization == dict() or u"oauth_consumer_key" not in authorization:
error = "Missing required parameter."
return json_response({"error": error}, status=400)
# check the client_id
client_id = authorization[u"oauth_consumer_key"]
client = Client.query.filter_by(id=client_id).first()
if client == None:
# client_id is invalid
error = "Invalid client_id"
return json_response({"error": error}, status=400)
# make request token and return to client
request_validator = GMGRequestValidator(authorization)
rv = RequestTokenEndpoint(request_validator)
tokens = rv.create_request_token(request, authorization)
# store the nonce & timestamp before we return back
nonce = authorization[u"oauth_nonce"]
timestamp = authorization[u"oauth_timestamp"]
timestamp = datetime.datetime.fromtimestamp(float(timestamp))
nc = NonceTimestamp(nonce=nonce, timestamp=timestamp)
nc.save()
return form_response(tokens)
示例12: wrapper
def wrapper(request, *args, **kw):
if not request.GET.get('client_id'):
return json_response({
'status': 400,
'errors': [u'No client identifier in URL']},
_disable_cors=True)
client = OAuthClient.query.filter(
OAuthClient.identifier == request.GET.get('client_id')).first()
if not client:
return json_response({
'status': 400,
'errors': [u'No such client identifier']},
_disable_cors=True)
return controller(request, client)
示例13: wrapper
def wrapper(request, *args, **kwargs):
if not request.user.has_privilege(privilege_name):
error = "User '{0}' needs '{1}' privilege".format(
request.user.username,
privilege_name
)
return json_response({"error": error}, status=403)
return controller(request, *args, **kwargs)
示例14: profile_endpoint
def profile_endpoint(request):
""" This is /api/user/<username>/profile - This will give profile info """
user, user_profile = get_profile(request)
if user is None:
username = request.matchdict["username"]
return json_error("No such 'user' with username '{0}'".format(username), status=404)
# user profiles are public so return information
return json_response(user_profile)
示例15: user
def user(request):
""" This is /api/user/<username> - This will get the user """
user, user_profile = profile(request, raw=True)
data = {
"nickname": user.username,
"updated": user.created.isoformat(),
"published": user.created.isoformat(),
"profile": user_profile,
}
return json_response(data)