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

Python transforms.send_json_response函数代码示例

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

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



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

示例1: put

    def put(self):
        """Store a question in the datastore in response to a PUT."""
        request = transforms.loads(self.request.get('request'))
        key = request.get('key')

        if not self.assert_xsrf_token_or_fail(
                request, self.XSRF_TOKEN, {'key': key}):
            return

        if not CourseOutlineRights.can_edit(self):
            transforms.send_json_response(
                self, 401, 'Access denied.', {'key': key})
            return

        payload = request.get('payload')
        question_dict = transforms.loads(payload)
        question_dict['description'] = question_dict['description'].strip()

        question_dict, errors = self.import_and_validate(question_dict, key)

        if errors:
            self.validation_error('\n'.join(errors), key=key)
            return

        if key:
            question = QuestionDTO(key, question_dict)
        else:
            question = QuestionDTO(None, question_dict)

        question.type = self.TYPE
        key_after_save = QuestionDAO.save(question)

        transforms.send_json_response(
            self, 200, 'Saved.', payload_dict={'key': key_after_save})
开发者ID:AppScale,项目名称:coursebuilder,代码行数:34,代码来源:question_editor.py


示例2: get

    def get(self):
        """GET method is called when the page with the questionnaire loads."""

        key = self.request.get('key')

        if not self.assert_xsrf_token_or_fail(
                self.request, QUESTIONNAIRE_XSRF_TOKEN_NAME, {}):
            return

        user = self.get_user()
        if user is None:
            return

        student = models.Student.get_enrolled_student_by_user(user)
        if student is None:
            return

        entity = StudentFormEntity.load_or_default(student, key)
        if entity.value is None:
            return

        form_dict = transforms.loads(entity.value)

        transforms.send_json_response(
            self, 200, None,
            payload_dict=transforms.dict_to_json(form_dict))
开发者ID:JuanCarlosllh,项目名称:GCB-Modding-Introduction,代码行数:26,代码来源:questionnaire.py


示例3: put

    def put(self):
        """A PUT REST method shared by all unit types."""
        request = transforms.loads(self.request.get('request'))
        key = request.get('key')

        if not self.assert_xsrf_token_or_fail(
                request, 'put-unit', {'key': key}):
            return

        if not CourseOutlineRights.can_edit(self):
            transforms.send_json_response(
                self, 401, 'Access denied.', {'key': key})
            return

        unit = courses.Course(self).find_unit_by_id(key)
        if not unit:
            transforms.send_json_response(
                self, 404, 'Object not found.', {'key': key})
            return

        payload = request.get('payload')
        errors = []

        try:
            updated_unit_dict = transforms.json_to_dict(
                transforms.loads(payload), self.SCHEMA_DICT)
            self.apply_updates(unit, updated_unit_dict, errors)
        except (TypeError, ValueError), ex:
            errors.append(str(ex))
开发者ID:mmoylan,项目名称:course-builder,代码行数:29,代码来源:unit_lesson_editor.py


示例4: put

    def put(self):
        """Store a question group in the datastore in response to a PUT."""
        request = transforms.loads(self.request.get('request'))
        key = request.get('key')

        if not self.assert_xsrf_token_or_fail(
                request, self.XSRF_TOKEN, {'key': key}):
            return

        if not CourseOutlineRights.can_edit(self):
            transforms.send_json_response(
                self, 401, 'Access denied.', {'key': key})
            return

        payload = request.get('payload')
        question_group_dict = transforms.json_to_dict(
            transforms.loads(payload),
            self.get_schema().get_json_schema_dict())

        validation_errors = self.validate(question_group_dict, key)
        if validation_errors:
            self.validation_error('\n'.join(validation_errors), key=key)
            return

        assert self.SCHEMA_VERSION == question_group_dict.get('version')

        if key:
            question_group = QuestionGroupDTO(key, question_group_dict)
        else:
            question_group = QuestionGroupDTO(None, question_group_dict)

        key_after_save = QuestionGroupDAO.save(question_group)
        transforms.send_json_response(
            self, 200, 'Saved.', payload_dict={'key': key_after_save})
开发者ID:Domofera,项目名称:Domofera_MOOC,代码行数:34,代码来源:question_group_editor.py


示例5: get

    def get(self):
        """Handles REST GET verb and returns an object as JSON payload."""
        key = self.request.get('key')
        if not ConfigPropertyRights.can_view():
            transforms.send_json_response(
                self, 401, 'Access denied.', {'key': key})
            return

        item = None
        if key and key in config.Registry.registered.keys():
            item = config.Registry.registered[key]
        if not item:
            self.redirect('/admin?action=settings')

        try:
            entity = config.ConfigPropertyEntity.get_by_key_name(key)
        except db.BadKeyError:
            entity = None

        entity_dict = {'name': key, 'label': item.label}
        if entity and not entity.is_draft:
            entity_dict['value'] = transforms.string_to_value(
                entity.value, item.value_type)
        else:
            entity_dict['value'] = item.default_value
        json_payload = transforms.dict_to_json(entity_dict)
        transforms.send_json_response(
            self, 200, 'Success.',
            payload_dict=json_payload,
            xsrf_token=crypto.XsrfTokenManager.create_xsrf_token(
                'config-property-put'))
开发者ID:google,项目名称:coursebuilder-core,代码行数:31,代码来源:config.py


示例6: get

    def get(self):
        """Get a students progress."""

        #teachers aren't course admins, so we probably shouldn't check for that
        # if not roles.Roles.is_course_admin(self.app_context):
        #     transforms.send_json_response(self, 401, 'Access denied.', {})
        #     return

        key = self.request.get('student')
        errors = []

        student = Student.get_by_email(key.strip())
        course = self.get_course()

        if student:
            units = teacher_parsers.StudentProgressTracker.get_detailed_progress(student, course)
        else:
            errors.append('An error occurred retrieving student data. Contact your course administrator.')
            self.validation_error('\n'.join(errors))
            return

        payload_dict = {
            'units': units,
            'student_name': student.name,
            'student_email': student.email
        }

        transforms.send_json_response(
            self, 200, '', payload_dict=payload_dict,
            xsrf_token=crypto.XsrfTokenManager.create_xsrf_token(
                self.XSRF_TOKEN))
开发者ID:ehiller,项目名称:CourseBuilderTeacherDashboard,代码行数:31,代码来源:teacher_rest_handlers.py


示例7: get

    def get(self):
        """Handles REST GET verb and returns an object as JSON payload."""

        if not CourseOutlineRights.can_view(self):
            transforms.send_json_response(self, 401, "Access denied.", {})
            return

        course = courses.Course(self)
        outline_data = []
        for unit in course.get_units():
            lesson_data = []
            for lesson in course.get_lessons(unit.unit_id):
                lesson_data.append({"title": lesson.title, "id": lesson.lesson_id})
            unit_title = unit.title
            if verify.UNIT_TYPE_UNIT == unit.type:
                unit_title = "Unit %s - %s" % (unit.index, unit.title)
            outline_data.append({"title": unit_title, "id": unit.unit_id, "lessons": lesson_data})

        transforms.send_json_response(
            self,
            200,
            "Success.",
            payload_dict={"outline": outline_data},
            xsrf_token=XsrfTokenManager.create_xsrf_token("unit-lesson-reorder"),
        )
开发者ID:henrymp,项目名称:coursebuilder,代码行数:25,代码来源:unit_lesson_editor.py


示例8: get

    def get(self):
        """Handles REST GET verb and returns an object as JSON payload."""

        if not CourseOutlineRights.can_view(self):
            transforms.send_json_response(self, 401, 'Access denied.', {})
            return

        course = courses.Course(self)
        outline_data = []
        for unit in course.get_units():
            lesson_data = []
            for lesson in course.get_lessons(unit.unit_id):
                lesson_data.append({
                    'title': lesson.title,
                    'id': lesson.lesson_id})
            unit_title = unit.title
            if verify.UNIT_TYPE_UNIT == unit.type:
                unit_title = 'Unit %s - %s' % (unit.index, unit.title)
            outline_data.append({
                'title': unit_title,
                'id': unit.unit_id,
                'lessons': lesson_data})

        transforms.send_json_response(
            self, 200, None,
            payload_dict={'outline': outline_data},
            xsrf_token=XsrfTokenManager.create_xsrf_token(
                'unit-lesson-reorder'))
开发者ID:graemian,项目名称:ami-mooc-pilot,代码行数:28,代码来源:unit_lesson_editor.py


示例9: delete

    def delete(self):
        """Handles REST DELETE verb."""

        request = transforms.loads(self.request.get('request'))
        key = request.get('key')
        transforms.send_json_response(
            self, 401, 'Access denied.', {'key': key})
开发者ID:Domofera,项目名称:Domofera_MOOC,代码行数:7,代码来源:course_settings.py


示例10: post

    def post(self):
        # Receive a payload of the form:
        #     {
        #       "location": url_for_rest_handler,
        #       "key": the key of the object being edited,
        #       "state": object_holding_editor_state
        #     }

        request = transforms.loads(self.request.get('request'))
        if not self.assert_xsrf_token_or_fail(request, self.XSRF_TOKEN, {}):
            return

        user = self.get_user()
        if user is None:
            self.error(401)
            return

        if not roles.Roles.is_course_admin(self.app_context):
            transforms.send_json_response(self, 401, 'Access denied.', {})
            return

        payload = transforms.loads(request.get('payload'))

        key_name = EditorPrefsDao.create_key_name(
            user.user_id(), payload['location'], payload['key'])
        editor_prefs = EditorPrefsDto(key_name, payload['state'])
        EditorPrefsDao.save(editor_prefs)

        transforms.send_json_response(self, 200, 'Saved.', payload_dict={})
开发者ID:google,项目名称:coursebuilder-core,代码行数:29,代码来源:oeditor.py


示例11: put

    def put(self):
        """A PUT REST method shared by all unit types."""
        request = transforms.loads(self.request.get("request"))
        key = request.get("key")

        if not self.assert_xsrf_token_or_fail(request, "put-unit", {"key": key}):
            return

        if not self.can_edit(self.app_context):
            transforms.send_json_response(self, 401, "Access denied.", {"key": key})
            return

        unit = courses.Course(self).find_unit_by_id(key)
        if not unit:
            transforms.send_json_response(self, 404, "Object not found.", {"key": key})
            return

        payload = request.get("payload")
        errors = []

        course = courses.Course(self)
        try:
            schema = self.get_schema(course, key)
            updated_unit_dict = transforms.json_to_dict(transforms.loads(payload), schema.get_json_schema_dict())
            schema.redact_entity_to_schema(updated_unit_dict)
            self.apply_updates(unit, updated_unit_dict, errors)
        except (TypeError, ValueError), ex:
            errors.append(str(ex))
开发者ID:danieldalonzo,项目名称:coursebuilder-core,代码行数:28,代码来源:unit_lesson_editor.py


示例12: get

 def get(self):
     """Provides empty initial content for asset upload editor."""
     # TODO(jorr): Pass base URI through as request param when generalized.
     json_payload = {'file': '', 'base': ALLOWED_ASSET_UPLOAD_BASE}
     transforms.send_json_response(
         self, 200, 'Success.', payload_dict=json_payload,
         xsrf_token=XsrfTokenManager.create_xsrf_token('asset-upload'))
开发者ID:CSavvy,项目名称:coursebuilder,代码行数:7,代码来源:filer.py


示例13: get

    def get(self):
        """Respond to the REST GET verb with the contents of the item."""
        key = self.request.get('key')
        if not roles.Roles.is_course_admin(self.app_context):
            transforms.send_json_response(
                self, 401, 'Access denied.', {'key': key})
            return

        if key:
            item = self.DAO.load(key)
            if item is None:
                transforms.send_json_response(
                    self, 404, 'Not found.', {'key': key})
                return
            version = item.dict.get('version')
            if version not in self.SCHEMA_VERSIONS:
                transforms.send_json_response(
                    self, 400, 'Version %s not supported.' % version,
                    {'key': key})
                return
            display_dict = copy.copy(item.dict)
            display_dict['id'] = item.id
            common_utils.run_hooks(self.PRE_LOAD_HOOKS, item, display_dict)
            payload_dict = self.transform_for_editor_hook(display_dict)
        elif self.CAN_CREATE:
            payload_dict = self.get_default_content()
        else:
            transforms.send_json_response(
                self, 404, 'Key is required in URL.', {})
            return

        transforms.send_json_response(
            self, 200, 'Success',
            payload_dict=payload_dict,
            xsrf_token=XsrfTokenManager.create_xsrf_token(self.XSRF_TOKEN))
开发者ID:2023SS,项目名称:coursebuilder-core,代码行数:35,代码来源:dto_editor.py


示例14: validation_error

 def validation_error(self, message, key=None):
     """Deliver a validation message."""
     if key:
         transforms.send_json_response(
             self, 412, message, payload_dict={'key': key})
     else:
         transforms.send_json_response(self, 412, message)
开发者ID:joseespino,项目名称:Google-Course-Builder-1.6.0-Modified-,代码行数:7,代码来源:utils.py


示例15: get

    def get(self):
        """Get the data to populate the question editor form."""
        key = self.request.get('key')

        if not CourseOutlineRights.can_view(self):
            transforms.send_json_response(
                self, 401, 'Access denied.', {'key': key})
            return

        if key:
            question = QuestionDAO.load(key)
            payload_dict = question.dict
        else:
            payload_dict = {
                'version': self.SCHEMA_VERSION,
                'question': '',
                'description': '',
                'graders': [
                    {
                        'score': '1.0',
                        'matcher': 'case_insensitive',
                        'response': '',
                        'feedback': ''}]}

        transforms.send_json_response(
            self, 200, 'Success',
            payload_dict=payload_dict,
            xsrf_token=XsrfTokenManager.create_xsrf_token(self.XSRF_TOKEN))
开发者ID:AppScale,项目名称:coursebuilder,代码行数:28,代码来源:question_editor.py


示例16: assert_xsrf_token_or_fail

 def assert_xsrf_token_or_fail(self, token_dict, action, args_dict):
     """Asserts that current request has proper XSRF token or fails."""
     token = token_dict.get("xsrf_token")
     if not token or not XsrfTokenManager.is_xsrf_token_valid(token, action):
         transforms.send_json_response(self, 403, "Bad XSRF token. Please reload the page and try again", args_dict)
         return False
     return True
开发者ID:diego-G,项目名称:gdefier,代码行数:7,代码来源:utils.py


示例17: get

    def get(self):
        """Provides empty initial content for asset upload editor."""
        # TODO(jorr): Pass base URI through as request param when generalized.
        key = self.request.get('key')
        base = asset_paths.AllowedBases.match_allowed_bases(key)
        if not base:
            transforms.send_json_response(
                self, 400, 'Malformed request.', {'key': key})
            return

        json_payload = {
            'key': key,
            'base': base,
        }
        fs = self.app_context.fs.impl
        if fs.isfile(fs.physical_to_logical(key)):
            json_payload['asset_url'] = key
            # TODO(davyrisso): Remove when cached assets issues are solved.
            # We add a random seed to the URL to force a reload, we also append
            # the URL because oeditor expects it to end with the filename.
            suffix = ('?seed=%s&url=%s' % (
                str(random.randint(0, 100000)), json_payload['asset_url']))
            json_payload['asset_url'] += suffix
        else:
            json_payload['asset_url'] = asset_paths.relative_base(base)
        transforms.send_json_response(
            self, 200, 'Success.', payload_dict=json_payload,
            xsrf_token=XsrfTokenManager.create_xsrf_token(self.XSRF_TOKEN_NAME))
开发者ID:google,项目名称:coursebuilder-core,代码行数:28,代码来源:filer.py


示例18: get

    def get(self):
        key = self.request.get('key')
        if not key:
            self.abort(404)

        # check availability
        item = drive_models.DriveSyncDAO.load(key)
        if item is None or not self.check_availability(item.availability):
            self.abort(404)

        # find the synced content
        chunk = models.ContentChunkDAO.get_one_by_uid(
            models.ContentChunkDAO.make_uid(item.type, key))
        if chunk is None:
            self.abort(404)

        self.response.headers['Last-Modified'] = str(item.last_synced)
        # TODO(nretallack): implement if-modified-since check here

        if chunk.content_type == 'application/json':
            transforms.send_json_response(
                self, 200, 'ok', payload_dict=json.loads(chunk.contents))
        else:
            self.response.headers['Content-Type'] = str(chunk.content_type)
            self.response.write(chunk.contents)
开发者ID:2023SS,项目名称:coursebuilder-core,代码行数:25,代码来源:handlers.py


示例19: put

    def put(self):
        """Handles REST PUT verb with JSON payload."""
        request = transforms.loads(self.request.get('request'))
        key = request.get('key')
        edit_mode = request.get('mode')

        if GLOBAL_DEBUG:
            logging.warning('***RAM*** put request = ' + str(request))

        if not self.assert_xsrf_token_or_fail(
                request, 'teacher-put', {'key': key}):
            return

        if not TeacherRights.can_edit(self):
            transforms.send_json_response(
                self, 401, 'MobileCSP: Admin access denied.', {'key': key})
            return

        entity = TeacherEntity.get(key)
        if not entity:
            transforms.send_json_response(
                self, 404, 'MobileCSP: Teacher Entity not found.', {'key': key})
            return

        schema = TeacherItemRESTHandler.SCHEMA()

        payload = request.get('payload')
        update_dict = transforms.json_to_dict(
            transforms.loads(payload), schema.get_json_schema_dict())

        #  Get the teacher's user_id
        user = Student.get_first_by_email(update_dict['email'])[0]  # returns a tuple
        if not user:
            transforms.send_json_response(
                self, 404, 'MobileCSP: No registered user found for ' + update_dict['email'], {'key': key})
            return

        # Check that the teacher isn't already registered
        if update_dict['mode'] == 'Add':
            teachers = TeacherEntity.get_teachers()
            for teacher in teachers:
                if teacher.email == update_dict['email']:
                    transforms.send_json_response(
                        self, 404, 'MobileCSP: User is already registered as a teacher ' + update_dict['email'], {'key': key})
                    return

        if GLOBAL_DEBUG:
            logging.debug('****RAM**** teacher id ' + str(user.user_id))

        # Store the user_id
        update_dict['user_id'] = user.user_id

        transforms.dict_to_entity(entity, update_dict)

        entity.put()

        transforms.send_json_response(self, 200, 'Saved.')
开发者ID:ram8647,项目名称:gcb-mobilecsp,代码行数:57,代码来源:teacher_entity.py


示例20: post

    def post(self):
        name = COURSE_EXPLORER_SETTINGS.name
        request = transforms.loads(self.request.get('request'))

        if not self.assert_xsrf_token_or_fail(
                request, self.ACTION, {}):
            return

        if not roles.Roles.is_course_admin(self.app_context):
            transforms.send_json_response(
                self, 401, 'Access denied.', {})
            return

        raw_data = transforms.loads(request.get('payload'))
        raw_data.pop('logo', None)
        try:
            data = transforms.json_to_dict(
                raw_data, schema_provider(None).get_json_schema_dict())
        except (TypeError, ValueError) as err:
            self.validation_error(err.replace('\n', ' '))
            return

        logo = self.request.POST.get('logo')
        logo_uploaded = isinstance(logo, cgi.FieldStorage)
        if logo_uploaded:
            data['logo_bytes_base64'] = base64.b64encode(logo.file.read())
            data['logo_mime_type'] = logo.type

        with common_utils.Namespace(appengine_config.DEFAULT_NAMESPACE_NAME):
            entity = config.ConfigPropertyEntity.get_by_key_name(name)

            if entity is None:
                entity = config.ConfigPropertyEntity(key_name=name)
                old_value = None
            else:
                old_value = entity.value

            # Don't delete the logo.
            if not logo_uploaded and old_value:
                old_dict = transforms.loads(old_value)
                if (
                        'logo_bytes_base64' in old_dict and
                        'logo_mime_type' in old_dict):
                    data['logo_bytes_base64'] = old_dict['logo_bytes_base64']
                    data['logo_mime_type'] = old_dict['logo_mime_type']

            entity.value = transforms.dumps(data)
            entity.is_draft = False
            entity.put()

            # is this necessary?
            models.EventEntity.record(
                'put-property', users.get_current_user(), transforms.dumps({
                    'name': name,
                    'before': str(old_value), 'after': str(entity.value)}))

        transforms.send_file_upload_response(self, 200, 'Saved.')
开发者ID:google,项目名称:coursebuilder-core,代码行数:57,代码来源:settings.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python user.User类代码示例发布时间:2022-05-27
下一篇:
Python transforms.loads函数代码示例发布时间: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