我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用markupsafe.escape()。
def escape(self, text): """Replace characters with their character references. Replace characters by their named entity references. Non-ASCII characters, if they do not have a named entity reference, are replaced by numerical character references. The return value is guaranteed to be ASCII. """ return self.__escapable.sub(self.__escape, compat.text_type(text) ).encode('ascii') # XXX: This regexp will not match all valid XML entity names__. # (It punts on details involving involving CombiningChars and Extenders.) # # .. __: http://www.w3.org/TR/2000/REC-xml-20001006#NT-EntityRef
def htmlentityreplace_errors(ex): """An encoding error handler. This python `codecs`_ error handler replaces unencodable characters with HTML entities, or, if no HTML entity exists for the character, XML character references. >>> u'The cost was \u20ac12.'.encode('latin1', 'htmlentityreplace') 'The cost was €12.' """ if isinstance(ex, UnicodeEncodeError): # Handle encoding errors bad_text = ex.object[ex.start:ex.end] text = _html_entities_escaper.escape(bad_text) return (compat.text_type(text), ex.end) raise ex
def import_string(import_name, silent=False): """Imports an object based on a string. This is useful if you want to use import paths as endpoints or something similar. An import path can be specified either in dotted notation (``xml.sax.saxutils.escape``) or with a colon as object delimiter (``xml.sax.saxutils:escape``). If the `silent` is True the return value will be `None` if the import fails. :return: imported object """ try: if ':' in import_name: module, obj = import_name.split(':', 1) elif '.' in import_name: items = import_name.split('.') module = '.'.join(items[:-1]) obj = items[-1] else: return __import__(import_name) return getattr(__import__(module, None, None, [obj]), obj) except (ImportError, AttributeError): if not silent: raise
def test_validation_warnings(self, send_confirmation): applicant = factories.ApplicantFactory.create() self.set_form_session_data( counties=['sanfrancisco'], applicant_id=applicant.id) with self.assertLogs( 'project.services.logging_service', logging.INFO) as logs: response = self.client.fill_form( reverse(self.view_name), **mock.fake.sf_pubdef_answers(ssn='')) self.assertRedirects( response, reverse('intake-confirm'), fetch_redirect_response=False) response = self.client.get(response.url) self.assertContains(response, escape(WARNING_FLASH_MESSAGE)) self.assertContains( response, escape( fields.SocialSecurityNumberField.is_recommended_error_message)) send_confirmation.assert_not_called() assertInLogsCount( logs, { 'event_name=application_page_complete': 1, 'event_name=application_started': 0, 'event_name=application_submitted': 0, 'event_name=application_errors': 0, })
def test_sees_expected_message(self): user = self.be_apubdef_user() response = self.client.get(self.url) expected_intro, expected_body = \ TransferService.render_application_transfer_message( form_submission=self.sub, author=user, to_organization=self.to_org, from_organization=self.from_org) self.assertContains(response, escape(expected_intro)) self.assertContains(response, escape(expected_body)) self.assertIn(self.to_org.name, expected_body) self.assertIn(self.from_org.name, expected_intro) self.assertIn(user.profile.name, expected_intro) self.assertContains(response, 'following message will be') self.assertContains(response, 'to the applicant')
def test_shows_flash_messages(self): self.set_form_session_data(counties=['contracosta']) flash_messages = [ "A flying horse is called a pegasus", "A horse with a horn is called a unicorn"] self.send_confirmations.return_value = flash_messages self.client.fill_form( reverse('intake-county_application'), follow=True, **mock.fake.cc_pubdef_answers()) response = self.client.fill_form( reverse('intake-review'), follow=True, submit_action='approve_application' ) for message in flash_messages: self.assertContains( response, escape(message))
def test_shows_flash_messages(self): self.set_form_session_data(counties=['alameda']) flash_messages = [ "A flying horse is called a pegasus", "A horse with a horn is called a unicorn"] self.send_confirmations.return_value = flash_messages self.client.fill_form( reverse('intake-county_application'), follow=True, **mock.fake.ebclc_answers()) response = self.client.fill_form( reverse('intake-review'), follow=True, submit_action='approve_application' ) for message in flash_messages: self.assertContains( response, escape(message))
def test_ebclc_and_santa_clara_can_see_pref_pronouns(self): ebclc = Organization.objects.get(slug='ebclc') santa_clara = Organization.objects.filter( slug__contains='santa_clara').first() self.be_user( User.objects.filter(profile__organization=ebclc).first()) sub = models.FormSubmission.objects.filter( organizations=ebclc).first() response = self.get_page(sub) self.assertContains( response, escape(sub.answers.get('preferred_pronouns'))) self.be_user( User.objects.filter(profile__organization=santa_clara).first()) sub = models.FormSubmission.objects.filter( organizations=santa_clara).first() response = self.get_page(sub) self.assertContains( response, escape(sub.answers.get('preferred_pronouns')))
def test_has_read_only_view_of_outgoing_transfer(self): user = self.be_apubdef_user() outgoing_transfer = models.ApplicationTransfer.objects.filter( status_update__application__organization__profiles__user=user ).first() status_update = outgoing_transfer.status_update submission = \ outgoing_transfer.status_update.application.form_submission response = self.get_page(submission) expected_display_data = [ "{} at {}".format( status_update.author.profile.name, status_update.author.profile.organization.name), "Transferred to", outgoing_transfer.new_application.organization.name, outgoing_transfer.reason, status_update.notification.sent_message ] for expected_data in expected_display_data: self.assertContains(response, escape(expected_data)) self.assertNotContains(response, escape('update-status-button'))
def test_can_see_incoming_transfer_event(self): user = User.objects.filter(profile__organization__slug='ebclc').first() self.be_user(user) incoming_transfer = models.ApplicationTransfer.objects.filter( new_application__organization__profiles__user=user).first() status_update = incoming_transfer.status_update submission = incoming_transfer.new_application.form_submission response = self.get_page(submission) expected_display_data = [ "{} at {}".format( status_update.author.profile.name, status_update.author.profile.organization.name), "Transferred to", incoming_transfer.new_application.organization.name, incoming_transfer.reason, status_update.notification.sent_message ] for expected_data in expected_display_data: self.assertContains(response, escape(expected_data))
def test_can_see_prior_status_updates_on_incoming_transfer(self): user = User.objects.filter(profile__organization__slug='ebclc').first() self.be_user(user) incoming_transfer = models.ApplicationTransfer.objects.filter( new_application__organization__profiles__user=user).first() submission = incoming_transfer.new_application.form_submission response = self.get_page(submission) prior_updates = models.StatusUpdate.objects.filter( application__form_submission=submission, created__lt=incoming_transfer.status_update.created ).exclude(transfer=incoming_transfer) for status_update in prior_updates: expected_display_data = [ "{} at {}".format( status_update.author.profile.name, status_update.author.profile.organization.name), status_update.status_type.display_name, status_update.notification.sent_message ] for expected_data in expected_display_data: self.assertContains(response, escape(expected_data))
def test_user_sees_success_flash_and_new_status_after_submission( self, front): self.be_apubdef_user() review_page = self.create_status_update(follow=True) default_message = \ review_page.context_data['form']['sent_message'].value() response = self.confirm_status_update(sent_message=default_message) self.assertRedirects( response, reverse('intake-app_index'), fetch_redirect_response=False) index = self.client.get(response.url) expected_message = services.status_notifications \ .get_status_update_success_message( self.sub.get_full_name(), self.status_type) self.assertContains( index, escape(expected_message)) self.assertEqual(len(front.mock_calls), 1)
def test_adding(self): # adding two strings should escape the unsafe one unsafe = '<script type="application/x-some-script">alert("foo");</script>' safe = Markup('<em>username</em>') assert unsafe + safe == text_type(escape(unsafe)) + text_type(safe)
def test_escaping(self): # escaping and unescaping assert escape('"<>&\'') == '"<>&'' assert Markup("<em>Foo & Bar</em>").striptags() == "Foo & Bar" assert Markup("<test>").unescape() == "<test>"
def test_escape_silent(self): assert escape_silent(None) == Markup() assert escape(None) == Markup(None) assert escape_silent('<foo>') == Markup(u'<foo>')
def test_markup_leaks(self): counts = set() for count in range(20): for item in range(1000): escape("foo") escape("<foo>") escape(u"foo") escape(u"<foo>") counts.add(len(gc.get_objects())) assert len(counts) == 1, 'ouch, c extension seems to leak objects'
def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(MarkupTestCase)) # this test only tests the c extension if not hasattr(escape, 'func_code'): suite.addTest(unittest.makeSuite(MarkupLeakTestCase)) return suite
def example_form(): form = SignupForm(csrf_enabled=False) if form.validate_on_submit(): flash('Hello, {}. You have successfully signed up' .format(escape(form.name.data))) return redirect(url_for('.index')) return render_template('frontend/signup.html', form=form)
def owner(self, pet_id): try: pet = Pet.nodes.get(**{self.__selection_field__.get("primary"): str(markupsafe.escape(pet_id))}) if (pet): current_owner = pet.owner.get() if (current_owner): return jsonify(owner=current_owner.to_dict()), 200 else: return jsonify(errors=["Selected pet has not been adopted yet!"]), 404 else: return jsonify(errors=["Selected pet does not exists!"]), 404 except: return jsonify(errors=["An error occurred while processing your request."]), 500
def get_header(name): if (name in request.headers): return request.headers.get(markupsafe.escape(name)) else: return None