当前位置: 首页>>代码示例>>Python>>正文


Python response.json函数代码示例

本文整理汇总了Python中sanic.response.json函数的典型用法代码示例。如果您正苦于以下问题:Python json函数的具体用法?Python json怎么用?Python json使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了json函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: handle_request

async def handle_request(request):
    urls = request.args.getlist('url')
    callback = request.args.get('callback')
    if urls:
        if len(urls) > 10:
            return response.json([{
                'ok': False,
                'error': 'Max 10 URLs allowed'
            }], status=400)
        async with aiohttp.ClientSession() as session:
            head_infos = await asyncio.gather(*[
                head(session, url) for url in urls
            ])
            if callback and is_valid_callback(callback):
                return response.text(
                    '{}({})'.format(callback, json.dumps(head_infos, indent=2)),
                    content_type='application/javascript',
                    headers={'Access-Control-Allow-Origin': '*'},
                )
            else:
                return response.json(
                    head_infos,
                    headers={'Access-Control-Allow-Origin': '*'},
                )
    else:
        return response.html(INDEX)
开发者ID:simonw,项目名称:json-head,代码行数:26,代码来源:json_head.py

示例2: reset

async def reset(request, token):
    try:
        reset = db.session.query(PasswordReset).filter_by(UUID=token).first()
        if not reset:
            return response.json({"error": "Invalid reset token"}, 404)

        if not reset.isValid:
            return response.json({"error": "Reset token has already been used"}, 404)

        if pendulum.now("UTC") > pendulum.instance(reset.expireTime):
            return response.json({"error": "Reset token has expired."}, 400)

        # Invalidate all resets for this user
        # db.session.query(PasswordReset).filter_by(userId=reset.userId).update(
        #     {"isValid": False}
        # )
        db.session.commit()

        user = utils.get_account_by_id(reset.userId)
        userData = user.serialize()
        userData["jwt"] = user.gen_token(expire_hours=1)
        userData["message"] = "Valid token provided. Prompt user to change password"

        return response.json(userData, 200)

    except Exception as e:
        return utils.exeption_handler(e, "Password reset confirmation failed", 500)
开发者ID:Gingernaut,项目名称:microAuth,代码行数:27,代码来源:email.py

示例3: get_wallet

async def get_wallet(request, account_id):
    """Get a single wallet.

    Can be user or taxbank.
    """
    account = await request.app.db.fetchrow("""
    SELECT account_id, account_type, amount
    FROM account_amount
    WHERE account_id = $1
    """, account_id)

    if not account:
        raise AccountNotFoundError('Account not found')

    daccount = dict(account)
    if account['account_type'] == AccountType.USER:
        wallet = await request.app.db.fetchrow("""
        SELECT taxpaid, steal_uses, steal_success, ubank
        FROM wallets_taxpaid
        WHERE user_id=$1
        """, account_id)

        daccount.update(dict(wallet))
        return response.json(daccount)

    return response.json(daccount)
开发者ID:lkmnds,项目名称:jose,代码行数:26,代码来源:josecoin.py

示例4: score

async def score(request):
    from auth import get_hash, get_random_base64, validate_hash
    instance = request.app.config['LAZY_UMONGO']
    req_data = await request.app.config['REQDATA_EXTRACTOR'](request)
    if not (await request.app.config['HAS_AUTHORIZATION'](req_data, instance)):
        return _response.json({"error":"Missing authorization"}, status=403)

    username = req_data.get('username', '')
    user = await instance.User.find_one({'username':username})
    node_id = req_data.get('node_id', '')
    prev_score = user.online_scores[node_id]
    action = req_data.get('action', '')

    if action == '4':
        new_score = max(0, prev_score - 0.5)
        user.dictset('online_scores', node_id, new_score)
        await user.commit()
    elif action == '5':
        new_score = max(0, prev_score - 0.1)
        user.dictset('online_scores', node_id, new_score)
        await user.commit()
    elif action == '6':
        new_score = min(1, prev_score + 0.1)
        user.dictset('online_scores', node_id, new_score)
        await user.commit()
    elif action == '9':
        new_score = min(1, prev_score + 0.5)
        user.dictset('online_scores', node_id, new_score)
        await user.commit()
    else:
        return _response.json({'error':'Invalid action'}, status=400)
    return _response.json({'successful':True, 'new_score':new_score})
开发者ID:yamatteo,项目名称:yama,代码行数:32,代码来源:user_api.py

示例5: wrapped

 async def wrapped(req, *args, **kwargs):
     try:
         return await func(req, *args, **kwargs)
     except SanicException as http_error:
         return json({"error": str(http_error)}, http_error.status_code)
     except IntegrityConstraintViolationError as sql_error:
         return json({"error": sql_error.args[0]}, 400)
开发者ID:Julien00859,项目名称:Bomberman,代码行数:7,代码来源:middlewares.py

示例6: put

    async def put(self, request, id):
        try:
            user = utils.get_account_by_id(id)

            if not user:
                return response.json({"error": "User not found"}, 404)

            user.modifiedTime = pendulum.now("UTC")
            cleanData = utils.format_body_params(request.json)

            if not cleanData:
                return response.json(
                    {"error": "No valid data provided for update"}, 400
                )

            if cleanData.get("password"):
                providedPass = cleanData.get("password")
                if len(providedPass) < request.app.config["MIN_PASS_LENGTH"]:
                    return response.json(
                        {"error": "New password does not meet length requirements"}, 400
                    )

                user.password = utils.encrypt_pass(providedPass)

            if request.json.get("userRole"):
                user.userRole = cleanData.get("userRole").upper()

            if cleanData.get("emailAddress"):
                newEmail = cleanData.get("emailAddress")

                if (
                    utils.email_account_exists(newEmail)
                    and utils.get_account_by_email(newEmail).id != user.id
                ):
                    return response.json(
                        {"error": "Email address associated with another account"}, 400
                    )

                user.emailAddress = newEmail

            if cleanData.get("firstName"):
                user.firstName = cleanData.get("firstName")

            if cleanData.get("lastName"):
                user.lastName = cleanData.get("lastName")

            if cleanData.get("phoneNumber"):
                user.phoneNumber = cleanData.get("phoneNumber")

            if cleanData.get("isVerified"):
                user.isVerified = cleanData.get("isVerified")

            db.session.commit()
            res = user.serialize()
            res["success"] = "Account updated"
            return response.json(res, 200)

        except Exception as e:
            return utils.exeption_handler(e, "Account update failed", 400)
开发者ID:Gingernaut,项目名称:microAuth,代码行数:59,代码来源:admins.py

示例7: all_nodes

async def all_nodes(request):
    instance = request.app.config['LAZY_UMONGO']
    req_data = await request.app.config['REQDATA_EXTRACTOR'](request)
    if not (await request.app.config['HAS_AUTHORIZATION'](req_data, instance)):
        return _response.json({"error":"Missing authorization"}, status=403)

    node_list = instance.Node.find({}).to_list(app.config['MAX_LIST_LENGTH'])
    node_list = [ c.dump() for c in node_list ]
    return _response.json({'successful':True, 'node_list':node_list})
开发者ID:yamatteo,项目名称:yama,代码行数:9,代码来源:user_api.py

示例8: policy

async def policy(request, name):
    l = []
    if name == "hot":
        l = hot.get()
    elif name == "new":
        l = hot.new()
    if l:
        return json(l)
    else:
        return json({})
开发者ID:youdian,项目名称:tushare,代码行数:10,代码来源:app.py

示例9: get_years

def get_years(request: Request) -> json:
    data, errors = Usercode().load(request.json)
    if not errors:
        if not data['usercode']:
            token = request.cookies.get('token')
            data['usercode'] = Config.current.tokens.find_one({'_id': token})['user_id']
        user = get_user_info(data['usercode'])
        years = list(map(lambda x: x, user['content']))
        return json(years)
    return json({'alert': parse_errors(errors)}, 403)
开发者ID:tarikbauer,项目名称:react_sanic,代码行数:10,代码来源:api.py

示例10: many_questions

async def many_questions(request):
    instance = request.app.config['LAZY_UMONGO']
    req_data = await request.app.config['REQDATA_EXTRACTOR'](request)
    if not (await request.app.config['HAS_AUTHORIZATION'](req_data, instance)):
        return _response.json({"error":"Missing authorization"}, status=403)

    question_id_list = req_data.get('question_id_list', [])
    question_list = instance.Question.find({'_id': {'$in':question_id_list}}).to_list(app.config['MAX_LIST_LENGTH'])
    question_list = [ c.dump() for c in question_list ]
    return _response.json({'successful':True, 'question_list':question_list})
开发者ID:yamatteo,项目名称:yama,代码行数:10,代码来源:user_api.py

示例11: get

    async def get(self, request):
        try:
            userId = utils.get_id_from_jwt(request)
            user = utils.get_account_by_id(userId)
            if not user:
                return response.json({"error": "User not found"}, 404)
            return response.json(user.serialize(), 200)

        except Exception as e:
            return utils.exeption_handler(e, "User not found", 400)
开发者ID:Gingernaut,项目名称:microAuth,代码行数:10,代码来源:users.py

示例12: delete_account

async def delete_account(request, account_id: int):
    try:
        await request.app.db.execute("""
        DELETE FROM accounts
        WHERE account_id = $1
        """, account_id)

        return response.json({'success': True})
    except Exception as err:
        log.exception('error while deleting')
        return response.json({'success': False, 'err': repr(err)})
开发者ID:lkmnds,项目名称:jose,代码行数:11,代码来源:josecoin.py

示例13: question_info

async def question_info(request):
    instance = request.app.config['LAZY_UMONGO']
    req_data = await request.app.config['REQDATA_EXTRACTOR'](request)
    if not (await request.app.config['HAS_AUTHORIZATION'](req_data, instance)):
        return _response.json({"error":"Missing authorization"}, status=403)

    question_id = req_data.get('question_id', '')
    question = instance.question.find_one({'_id':question_id})
    if question:
        return _response.json({'successful':True, 'question':question.dump()})
    else:
        return _response.json({'error':"Some unexpected error occurred"}, status=400)
开发者ID:yamatteo,项目名称:yama,代码行数:12,代码来源:user_api.py

示例14: decorated_function

        async def decorated_function(request, *args, **kwargs):
            userId = get_id_from_jwt(request)

            if not userId:
                return response.json({"error": "Not Authorized"}, 401)

            if requireAdmin == True:
                user = get_account_by_id(userId)
                if not user or user.userRole != "ADMIN":
                    return response.json({"error": "Not Authorized"}, 401)

            return await f(request, *args, **kwargs)
开发者ID:Gingernaut,项目名称:microAuth,代码行数:12,代码来源:utils.py

示例15: get_subjects

def get_subjects(request: Request) -> json:
    data, errors = Usercode().load(request.json)
    if not errors:
        if not data['usercode']:
            token = request.cookies.get('token')
            data['usercode'] = Config.current.tokens.find_one({'_id': token})['user_id']
        subjects = []
        user = get_user_info(data['usercode'])
        for year in user['content']:
            subjects.extend(list(map(lambda x: list(x.keys())[0], user['content'][year]['scores'])))
        return json(subjects)
    return json({'alert': parse_errors(errors)}, 403)
开发者ID:tarikbauer,项目名称:react_sanic,代码行数:12,代码来源:api.py


注:本文中的sanic.response.json函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。