• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python response.json函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: get

 async def get(self, request, id):
     try:
         user = User.get(User.id == id)
         return json({
             '_message': 'User fetched successfully!',
             'user': user
         })
     except User.DoesNotExist:
         return json({
             '_message': 'User does not exist',
             'user': None
         })
开发者ID:nirgn975,项目名称:Angular2-Django-cluster,代码行数:12,代码来源:view.py


示例17: kill_user

async def kill_user(request):
    if os.getenv("ALLOW_PATCH_SUPER")!='yes':
        raise Exception("You are not super patch enabled")
    reqdata = get_reqdata(request)
    username = reqdata.get('username', None)
    if username is None:
        return response.json({'error':'Missing username'}, status=400)
    try:
        user = User.objects.get({'username':username})
        user.delete()
        return response.json({})
    except:
        return response.json({'warning':'Nobody died'}, status=210)
开发者ID:yamatteo,项目名称:yama,代码行数:13,代码来源:patch.py


示例18: login

def login(request: Request) -> json:
    data, errors = Login().load(request.json)
    if not errors:
        response = Config.current.users.find_one({'_id': data['usercode']}) or \
                   Config.current.admins.find_one({'_id': data['usercode']})
        if not response:
            return json({'alert': ['User not registered']}, 403)
        if response['password'] != encrypt_password(data['password']):
            return json({'alert': ['Password does not match']}, 403)
        token = uuid.uuid4().hex
        Config.current.tokens.insert_one({'_id': token, 'created_at': datetime.utcnow(), 'user_id': data['usercode']})
        return json({'token': token, 'username': response['username']})
    return json({'alert': parse_errors(errors)}, 403)
开发者ID:tarikbauer,项目名称:react_sanic,代码行数:13,代码来源:api.py


示例19: post

 async def post(self, request):
     try:
         new_user = User.create(**loads(request.body))
         return json({
             '_message': 'User created successfully!',
             'user': new_user,
         })
     except IntegrityError as e:
         if "email" in str(e):
             return json({
                 '_message': 'Should fill out email field',
                 'user': None,
             })
开发者ID:nirgn975,项目名称:Angular2-Django-cluster,代码行数:13,代码来源:view.py


示例20: user_info

async def user_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)

    username = req_data.get('username', '')
    user = instance.User.find_one({'username':username})
    if user:
        user_data = user.dump()
        del user_data['salt']
        del user_data['password_hash']
        return _response.json({'successful':True, 'user':user_data})
    else:
        return _response.json({'error':"Some unexpected error occurred"}, status=400)
开发者ID:yamatteo,项目名称:yama,代码行数:15,代码来源:user_api.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python response.text函数代码示例发布时间:2022-05-27
下一篇:
Python sanic.Sanic类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap