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

Python sanitize.strip_html函数代码示例

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

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



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

示例1: new_node

def new_node(category, title, user, description=None, parent=None):
    """Create a new project or component.

    :param str category: Node category
    :param str title: Node title
    :param User user: User object
    :param str description: Node description
    :param Node project: Optional parent object
    :return Node: Created node

    """
    category = category
    title = strip_html(title.strip())
    if description:
        description = strip_html(description.strip())

    node = Node(
        title=title,
        category=category,
        creator=user,
        description=description,
        parent=parent
    )

    node.save()

    return node
开发者ID:AllisonLBowers,项目名称:osf.io,代码行数:27,代码来源:__init__.py


示例2: project_new_post

def project_new_post(auth, **kwargs):
    user = auth.user

    data = request.get_json()
    title = strip_html(data.get("title"))
    title = title.strip()
    category = data.get("category", "project")
    template = data.get("template")
    description = strip_html(data.get("description"))
    new_project = {}

    if template:
        original_node = Node.load(template)
        changes = {"title": title, "category": category, "template_node": original_node}

        if description:
            changes["description"] = description

        project = original_node.use_as_template(auth=auth, changes={template: changes})

    else:
        try:
            project = new_node(category, title, user, description)
        except ValidationValueError as e:
            raise HTTPError(http.BAD_REQUEST, data=dict(message_long=e.message))
        new_project = _view_project(project, auth)
    return {"projectUrl": project.url, "newNode": new_project["node"] if new_project else None}, http.CREATED
开发者ID:Alpani,项目名称:osf.io,代码行数:27,代码来源:node.py


示例3: test_bulk_creates_children_and_sanitizes_html_logged_in_owner

    def test_bulk_creates_children_and_sanitizes_html_logged_in_owner(
            self, app, user, project, url):
        title = '<em>Reasoning</em> <strong>Aboot Projects</strong>'
        description = 'A <script>alert("super reasonable")</script> child'

        res = app.post_json_api(url, {
            'data': [{
                'type': 'nodes',
                'attributes': {
                    'title': title,
                    'description': description,
                    'category': 'project',
                    'public': True
                }
            }]
        }, auth=user.auth, bulk=True)
        child_id = res.json['data'][0]['id']
        assert res.status_code == 201
        url = '/{}nodes/{}/'.format(API_BASE, child_id)

        res = app.get(url, auth=user.auth)
        assert res.json['data']['attributes']['title'] == strip_html(title)
        assert res.json['data']['attributes']['description'] == strip_html(
            description)
        assert res.json['data']['attributes']['category'] == 'project'

        project.reload()
        child_id = res.json['data']['id']
        assert child_id == project.nodes[0]._id
        assert AbstractNode.load(child_id).logs.latest(
        ).action == NodeLog.PROJECT_CREATED
开发者ID:leb2dg,项目名称:osf.io,代码行数:31,代码来源:test_node_children_list.py


示例4: test_bulk_creates_children_and_sanitizes_html_logged_in_owner

    def test_bulk_creates_children_and_sanitizes_html_logged_in_owner(self):
        title = '<em>Cool</em> <strong>Project</strong>'
        description = 'An <script>alert("even cooler")</script> child'

        res = self.app.post_json_api(self.url, {
            'data': [{
                'type': 'nodes',
                'attributes': {
                    'title': title,
                    'description': description,
                    'category': 'project',
                    'public': True
                }
            }]
        }, auth=self.user.auth, bulk=True)
        child_id = res.json['data'][0]['id']
        assert_equal(res.status_code, 201)
        url = '/{}nodes/{}/'.format(API_BASE, child_id)

        res = self.app.get(url, auth=self.user.auth)
        assert_equal(res.json['data']['attributes']['title'], strip_html(title))
        assert_equal(res.json['data']['attributes']['description'], strip_html(description))
        assert_equal(res.json['data']['attributes']['category'], 'project')

        self.project.reload()
        child_id = res.json['data']['id']
        assert_equal(child_id, self.project.nodes[0]._id)
        assert_equal(Node.load(child_id).logs[0].action, NodeLog.PROJECT_CREATED)
开发者ID:545zhou,项目名称:osf.io,代码行数:28,代码来源:test_node_children_list.py


示例5: test_bulk_creates_children_and_sanitizes_html_logged_in_owner

    def test_bulk_creates_children_and_sanitizes_html_logged_in_owner(self):
        title = "<em>Cool</em> <strong>Project</strong>"
        description = 'An <script>alert("even cooler")</script> child'

        res = self.app.post_json_api(
            self.url,
            {
                "data": [
                    {
                        "type": "nodes",
                        "attributes": {
                            "title": title,
                            "description": description,
                            "category": "project",
                            "public": True,
                        },
                    }
                ]
            },
            auth=self.user.auth,
            bulk=True,
        )
        child_id = res.json["data"][0]["id"]
        assert_equal(res.status_code, 201)
        url = "/{}nodes/{}/".format(API_BASE, child_id)

        res = self.app.get(url, auth=self.user.auth)
        assert_equal(res.json["data"]["attributes"]["title"], strip_html(title))
        assert_equal(res.json["data"]["attributes"]["description"], strip_html(description))
        assert_equal(res.json["data"]["attributes"]["category"], "project")

        self.project.reload()
        child_id = res.json["data"]["id"]
        assert_equal(child_id, self.project.nodes[0]._id)
        assert_equal(Node.load(child_id).logs[0].action, NodeLog.PROJECT_CREATED)
开发者ID:ccfair,项目名称:osf.io,代码行数:35,代码来源:test_node_children_list.py


示例6: project_new_post

def project_new_post(auth, **kwargs):
    user = auth.user

    title = strip_html(request.json.get('title'))
    template = request.json.get('template')
    description = strip_html(request.json.get('description'))
    title = title.strip()

    if not title or len(title) > 200:
        raise HTTPError(http.BAD_REQUEST)

    if template:
        original_node = Node.load(template)
        changes = {
            'title': title
        }

        if description:
            changes['description'] = description

        project = original_node.use_as_template(
            auth=auth,
            changes={
                template: changes
            })

    else:
        project = new_node('project', title, user, description)

    return {
        'projectUrl': project.url
    }, http.CREATED
开发者ID:akrit19,项目名称:osf.io,代码行数:32,代码来源:node.py


示例7: test_strip_html_on_non_strings_returns_original_value

    def test_strip_html_on_non_strings_returns_original_value(self):
        assert_true(sanitize.strip_html(True))
        assert_false(sanitize.strip_html(False))

        assert_equal(sanitize.strip_html(12), 12)
        assert_equal(sanitize.strip_html(12.3), 12.3)

        dtime = datetime.datetime.now()
        assert_equal(sanitize.strip_html(dtime), dtime)
开发者ID:545zhou,项目名称:osf.io,代码行数:9,代码来源:test_sanitize.py


示例8: test_strip_html

 def test_strip_html(self):
     assert_equal(
         sanitize.strip_html('<foo>bar</foo>'),
         'bar'
     )
     assert_equal(
         sanitize.strip_html(b'<foo>bar</foo>'),
         'bar'
     )
开发者ID:545zhou,项目名称:osf.io,代码行数:9,代码来源:test_sanitize.py


示例9: test_update_user_sanitizes_html_properly

 def test_update_user_sanitizes_html_properly(self):
     """Post request should update resource, and any HTML in fields should be stripped"""
     bad_fullname = 'Malcolm <strong>X</strong>'
     bad_family_name = 'X <script>alert("is")</script> a cool name'
     res = self.app.patch_json_api(self.user_one_url, {
         'fullname': bad_fullname,
         'family_name': bad_family_name,
     }, auth=self.user_one.auth)
     assert_equal(res.status_code, 200)
     assert_equal(res.json['data']['attributes']['fullname'], strip_html(bad_fullname))
     assert_equal(res.json['data']['attributes']['family_name'], strip_html(bad_family_name))
开发者ID:sbt9uc,项目名称:osf.io,代码行数:11,代码来源:test_views.py


示例10: new_private_link

def new_private_link(name, user, nodes, anonymous):
    """Create a new private link.

    :param str name: private link name
    :param User user: User object
    :param list Node node: a list of node object
    :param bool anonymous: make link anonymous or not
    :return PrivateLink: Created private link

    """
    key = str(uuid.uuid4()).replace("-", "")
    if name:
        name = strip_html(name)
        if name is None or not name.strip():
            raise ValidationValueError('Invalid link name.')
    else:
        name = "Shared project link"

    private_link = PrivateLink(
        key=key,
        name=name,
        creator=user,
        nodes=nodes,
        anonymous=anonymous
    )

    private_link.save()

    return private_link
开发者ID:AllisonLBowers,项目名称:osf.io,代码行数:29,代码来源:__init__.py


示例11: test_archive_success_escaped_file_names

    def test_archive_success_escaped_file_names(self):
        file_tree = file_tree_factory(0, 0, 0)
        fake_file = file_factory(name='>and&and<')
        fake_file_name = strip_html(fake_file['name'])
        file_tree['children'] = [fake_file]

        node = factories.NodeFactory(creator=self.user)
        data = {
            ('q_' + fake_file_name): {
                'value': fake.word(),
                'extra': [{
                    'sha256': fake_file['extra']['hashes']['sha256'],
                    'viewUrl': '/project/{0}/files/osfstorage{1}'.format(
                        node._id,
                        fake_file['path']
                    ),
                    'selectedFileName': fake_file_name,
                    'nodeId': node._id
                }]
            }
        }
        schema = generate_schema_from_data(data)
        draft = factories.DraftRegistrationFactory(branched_from=node, registration_schema=schema, registered_metadata=data)

        with test_utils.mock_archive(node, schema=schema, data=data, autocomplete=True, autoapprove=True) as registration:
            with mock.patch.object(BaseStorageAddon, '_get_file_tree', mock.Mock(return_value=file_tree)):
                job = factories.ArchiveJobFactory(initiator=registration.creator)
                archive_success(registration._id, job._id)
                registration.reload()
                for key, question in registration.registered_meta[schema._id].items():
                    assert_equal(question['extra'][0]['selectedFileName'], fake_file_name)
开发者ID:adlius,项目名称:osf.io,代码行数:31,代码来源:test_archiver.py


示例12: project_new_node

def project_new_node(auth, node, **kwargs):
    form = NewNodeForm(request.form)
    user = auth.user
    if form.validate():
        try:
            new_component = new_node(
                title=strip_html(form.title.data),
                user=user,
                category=form.category.data,
                parent=node,
            )
        except ValidationValueError as e:
            raise HTTPError(
                http.BAD_REQUEST,
                data=dict(message_long=e.message)
            )

        message = (
            'Your component was created successfully. You can keep working on the component page below, '
            'or return to the <u><a href="{url}">project page</a></u>.'
        ).format(url=node.url)
        status.push_status_message(message, kind='info', trust=True)

        return {
            'status': 'success',
        }, 201, None, new_component.url
    else:
        # TODO: This function doesn't seem to exist anymore?
        status.push_errors_to_status(form.errors)
    raise HTTPError(http.BAD_REQUEST, redirect_url=node.url)
开发者ID:rmoorman,项目名称:osf.io,代码行数:30,代码来源:node.py


示例13: register_user

def register_user(**kwargs):
    """Register new user account.

    :param-json str email1:
    :param-json str email2:
    :param-json str password:
    :param-json str fullName:
    :raises: HTTPError(http.BAD_REQUEST) if validation fails or user already
        exists

    """
    # Verify email address match
    json_data = request.get_json()
    if str(json_data["email1"]).lower() != str(json_data["email2"]).lower():
        raise HTTPError(http.BAD_REQUEST, data=dict(message_long="Email addresses must match."))
    try:
        full_name = request.json["fullName"]
        full_name = strip_html(full_name)

        user = framework.auth.register_unconfirmed(request.json["email1"], request.json["password"], full_name)
        framework.auth.signals.user_registered.send(user)
    except (ValidationValueError, DuplicateEmailError):
        raise HTTPError(
            http.BAD_REQUEST, data=dict(message_long=language.ALREADY_REGISTERED.format(email=request.json["email1"]))
        )

    if settings.CONFIRM_REGISTRATIONS_BY_EMAIL:
        send_confirm_email(user, email=user.username)
        message = language.REGISTRATION_SUCCESS.format(email=user.username)
        return {"message": message}
    else:
        return {"message": "You may now log in."}
开发者ID:jinluyuan,项目名称:osf.io,代码行数:32,代码来源:views.py


示例14: test_update_collection_sanitizes_html_properly

 def test_update_collection_sanitizes_html_properly(self):
     """Post request should update resource, and any HTML in fields should be stripped"""
     new_title = '<strong>Super</strong><script>alert("even cooler")</script> Cool Project'
     res = self.app.put_json_api(self.url, {
         'data': {
             'id': self.collection._id,
             'type': 'collections',
             'attributes': {
                 'title': new_title,
             }
         }
     }, auth=self.user.auth)
     assert_equal(res.status_code, 200)
     assert_equal(res.content_type, 'application/vnd.api+json')
     assert_equal(res.json['data']['attributes']['title'], strip_html(new_title))
     self.collection.reload()
     assert_equal(self.collection.title, strip_html(new_title))
开发者ID:ZobairAlijan,项目名称:osf.io,代码行数:17,代码来源:test_views.py


示例15: html_and_illegal_unicode_replace

def html_and_illegal_unicode_replace(atom_element):
    """ Replace an illegal for XML unicode character with nothing.
    This fix thanks to Matt Harper from his blog post:
    https://maxharp3r.wordpress.com/2008/05/15/pythons-minidom-xml-and-illegal-unicode-characters/
    """
    if atom_element:
        new_element = RE_XML_ILLEGAL_COMPILED.sub('', atom_element)
        return strip_html(new_element)
    return atom_element
开发者ID:akrit19,项目名称:osf.io,代码行数:9,代码来源:util.py


示例16: test_update_user_sanitizes_html_properly

 def test_update_user_sanitizes_html_properly(self):
     """Post request should update resource, and any HTML in fields should be stripped"""
     bad_fullname = "Malcolm <strong>X</strong>"
     bad_family_name = 'X <script>alert("is")</script> a cool name'
     res = self.app.patch_json_api(
         self.user_one_url,
         {
             "data": {
                 "id": self.user_one._id,
                 "type": "users",
                 "attributes": {"full_name": bad_fullname, "family_name": bad_family_name},
             }
         },
         auth=self.user_one.auth,
     )
     assert_equal(res.status_code, 200)
     assert_equal(res.json["data"]["attributes"]["full_name"], strip_html(bad_fullname))
     assert_equal(res.json["data"]["attributes"]["family_name"], strip_html(bad_family_name))
开发者ID:rdhyee,项目名称:osf.io,代码行数:18,代码来源:test_views.py


示例17: test_field_content_is_sanitized_upon_submission

    def test_field_content_is_sanitized_upon_submission(self):
        bad_text = "<a href='http://sanitized.name'>User_text</a>"
        cleaned_text = sanitize.strip_html(bad_text)

        payload = copy.deepcopy(self.sample_data)
        payload['data']['attributes']['name'] = bad_text

        res = self.app.post_json_api(self.user1_list_url, payload, auth=self.user1.auth)
        assert_equal(res.status_code, 201)
        assert_equal(res.json['data']['attributes']['name'], cleaned_text)
开发者ID:alexschiller,项目名称:osf.io,代码行数:10,代码来源:test_token_list.py


示例18: project_new_post

def project_new_post(auth, **kwargs):
    user = auth.user

    data = request.get_json()
    title = strip_html(data.get('title'))
    title = title.strip()
    category = data.get('category', 'project')
    template = data.get('template')
    description = strip_html(data.get('description'))
    new_project = {}

    if template:
        original_node = Node.load(template)
        changes = {
            'title': title,
            'category': category,
            'template_node': original_node,
        }

        if description:
            changes['description'] = description

        project = original_node.use_as_template(
            auth=auth,
            changes={
                template: changes,
            }
        )

    else:
        try:
            project = new_node(category, title, user, description)
        except ValidationError as e:
            raise HTTPError(
                http.BAD_REQUEST,
                data=dict(message_long=e.message)
            )
        new_project = _view_project(project, auth)
    return {
        'projectUrl': project.url,
        'newNode': new_project['node'] if new_project else None
    }, http.CREATED
开发者ID:adlius,项目名称:osf.io,代码行数:42,代码来源:node.py


示例19: test_update_project_sanitizes_html_properly

 def test_update_project_sanitizes_html_properly(self):
     """Post request should update resource, and any HTML in fields should be stripped"""
     new_title = '<strong>Super</strong> Cool Project'
     new_description = 'An <script>alert("even cooler")</script> project'
     res = self.app.put_json_api(self.public_url, {
         'data': {
             'id': self.public_project._id,
             'type': 'nodes',
             'attributes': {
                 'title': new_title,
                 'description': new_description,
                 'category': self.new_category,
                 'public': True,
             }
         }
     }, auth=self.user.auth)
     assert_equal(res.status_code, 200)
     assert_equal(res.content_type, 'application/vnd.api+json')
     assert_equal(res.json['data']['attributes']['title'], strip_html(new_title))
     assert_equal(res.json['data']['attributes']['description'], strip_html(new_description))
开发者ID:mauromsl,项目名称:osf.io,代码行数:20,代码来源:test_node_detail.py


示例20: deserialize_contributors

def deserialize_contributors(node, user_dicts, auth, validate=False):
    """View helper that returns a list of User objects from a list of
    serialized users (dicts). The users in the list may be registered or
    unregistered users.

    e.g. ``[{'id': 'abc123', 'registered': True, 'fullname': ..},
            {'id': None, 'registered': False, 'fullname'...},
            {'id': '123ab', 'registered': False, 'fullname': ...}]

    If a dict represents an unregistered user without an ID, creates a new
    unregistered User record.

    :param Node node: The node to add contributors to
    :param list(dict) user_dicts: List of serialized users in the format above.
    :param Auth auth:
    :param bool validate: Whether to validate and sanitize fields (if necessary)
    """

    # Add the registered contributors
    contribs = []
    for contrib_dict in user_dicts:
        fullname = contrib_dict["fullname"]
        visible = contrib_dict["visible"]
        email = contrib_dict.get("email")

        if validate is True:
            # Validate and sanitize inputs as needed. Email will raise error if invalid.
            # TODO Edge case bug: validation and saving are performed in same loop, so all in list
            # up to the invalid entry will be saved. (communicate to the user what needs to be retried)
            fullname = sanitize.strip_html(fullname)
            if not fullname:
                raise ValidationValueError("Full name field cannot be empty")
            if email:
                validate_email(email)  # Will raise a ValidationError if email invalid

        if contrib_dict["id"]:
            contributor = User.load(contrib_dict["id"])
        else:
            try:
                contributor = User.create_unregistered(fullname=fullname, email=email)
                contributor.save()
            except ValidationValueError:
                ## FIXME: This suppresses an exception if ID not found & new validation fails; get_user will return None
                contributor = get_user(email=email)

        # Add unclaimed record if necessary
        if not contributor.is_registered and node._primary_key not in contributor.unclaimed_records:
            contributor.add_unclaimed_record(node=node, referrer=auth.user, given_name=fullname, email=email)
            contributor.save()

        contribs.append(
            {"user": contributor, "visible": visible, "permissions": expand_permissions(contrib_dict.get("permission"))}
        )
    return contribs
开发者ID:cslzchen,项目名称:osf.io,代码行数:54,代码来源:contributor.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python time.throttle_period_expired函数代码示例发布时间:2022-05-26
下一篇:
Python sanitize.escape_html函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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