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


Python sanitize.strip_html函数代码示例

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


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


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