src
stringlengths 721
1.04M
|
---|
import copy
import datetime
import json
import uuid
from django.core.exceptions import NON_FIELD_ERRORS
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.validators import MaxValueValidator, RegexValidator
from django.forms import (
BooleanField, CharField, CheckboxSelectMultiple, ChoiceField, DateField,
DateTimeField, EmailField, FileField, FloatField, Form, HiddenInput,
ImageField, IntegerField, MultipleChoiceField, MultipleHiddenInput,
MultiValueField, NullBooleanField, PasswordInput, RadioSelect, Select,
SplitDateTimeField, SplitHiddenDateTimeWidget, Textarea, TextInput,
TimeField, ValidationError, forms,
)
from django.forms.renderers import DjangoTemplates, get_default_renderer
from django.forms.utils import ErrorList
from django.http import QueryDict
from django.template import Context, Template
from django.test import SimpleTestCase
from django.utils.datastructures import MultiValueDict
from django.utils.safestring import mark_safe
class Person(Form):
first_name = CharField()
last_name = CharField()
birthday = DateField()
class PersonNew(Form):
first_name = CharField(widget=TextInput(attrs={'id': 'first_name_id'}))
last_name = CharField()
birthday = DateField()
class MultiValueDictLike(dict):
def getlist(self, key):
return [self[key]]
class FormsTestCase(SimpleTestCase):
# A Form is a collection of Fields. It knows how to validate a set of data and it
# knows how to render itself in a couple of default ways (e.g., an HTML table).
# You can pass it data in __init__(), as a dictionary.
def test_form(self):
# Pass a dictionary to a Form's __init__().
p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9'})
self.assertTrue(p.is_bound)
self.assertEqual(p.errors, {})
self.assertTrue(p.is_valid())
self.assertHTMLEqual(p.errors.as_ul(), '')
self.assertEqual(p.errors.as_text(), '')
self.assertEqual(p.cleaned_data["first_name"], 'John')
self.assertEqual(p.cleaned_data["last_name"], 'Lennon')
self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9))
self.assertHTMLEqual(
str(p['first_name']),
'<input type="text" name="first_name" value="John" id="id_first_name" required />'
)
self.assertHTMLEqual(
str(p['last_name']),
'<input type="text" name="last_name" value="Lennon" id="id_last_name" required />'
)
self.assertHTMLEqual(
str(p['birthday']),
'<input type="text" name="birthday" value="1940-10-9" id="id_birthday" required />'
)
msg = "Key 'nonexistentfield' not found in 'Person'. Choices are: birthday, first_name, last_name."
with self.assertRaisesMessage(KeyError, msg):
p['nonexistentfield']
form_output = []
for boundfield in p:
form_output.append(str(boundfield))
self.assertHTMLEqual(
'\n'.join(form_output),
"""<input type="text" name="first_name" value="John" id="id_first_name" required />
<input type="text" name="last_name" value="Lennon" id="id_last_name" required />
<input type="text" name="birthday" value="1940-10-9" id="id_birthday" required />"""
)
form_output = []
for boundfield in p:
form_output.append([boundfield.label, boundfield.data])
self.assertEqual(form_output, [
['First name', 'John'],
['Last name', 'Lennon'],
['Birthday', '1940-10-9']
])
self.assertHTMLEqual(
str(p),
"""<tr><th><label for="id_first_name">First name:</label></th><td>
<input type="text" name="first_name" value="John" id="id_first_name" required /></td></tr>
<tr><th><label for="id_last_name">Last name:</label></th><td>
<input type="text" name="last_name" value="Lennon" id="id_last_name" required /></td></tr>
<tr><th><label for="id_birthday">Birthday:</label></th><td>
<input type="text" name="birthday" value="1940-10-9" id="id_birthday" required /></td></tr>"""
)
def test_empty_dict(self):
# Empty dictionaries are valid, too.
p = Person({})
self.assertTrue(p.is_bound)
self.assertEqual(p.errors['first_name'], ['This field is required.'])
self.assertEqual(p.errors['last_name'], ['This field is required.'])
self.assertEqual(p.errors['birthday'], ['This field is required.'])
self.assertFalse(p.is_valid())
self.assertEqual(p.cleaned_data, {})
self.assertHTMLEqual(
str(p),
"""<tr><th><label for="id_first_name">First name:</label></th><td>
<ul class="errorlist"><li>This field is required.</li></ul>
<input type="text" name="first_name" id="id_first_name" required /></td></tr>
<tr><th><label for="id_last_name">Last name:</label></th>
<td><ul class="errorlist"><li>This field is required.</li></ul>
<input type="text" name="last_name" id="id_last_name" required /></td></tr>
<tr><th><label for="id_birthday">Birthday:</label></th><td>
<ul class="errorlist"><li>This field is required.</li></ul>
<input type="text" name="birthday" id="id_birthday" required /></td></tr>"""
)
self.assertHTMLEqual(
p.as_table(),
"""<tr><th><label for="id_first_name">First name:</label></th><td>
<ul class="errorlist"><li>This field is required.</li></ul>
<input type="text" name="first_name" id="id_first_name" required /></td></tr>
<tr><th><label for="id_last_name">Last name:</label></th>
<td><ul class="errorlist"><li>This field is required.</li></ul>
<input type="text" name="last_name" id="id_last_name" required /></td></tr>
<tr><th><label for="id_birthday">Birthday:</label></th>
<td><ul class="errorlist"><li>This field is required.</li></ul>
<input type="text" name="birthday" id="id_birthday" required /></td></tr>"""
)
self.assertHTMLEqual(
p.as_ul(),
"""<li><ul class="errorlist"><li>This field is required.</li></ul>
<label for="id_first_name">First name:</label>
<input type="text" name="first_name" id="id_first_name" required /></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
<label for="id_last_name">Last name:</label>
<input type="text" name="last_name" id="id_last_name" required /></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
<label for="id_birthday">Birthday:</label>
<input type="text" name="birthday" id="id_birthday" required /></li>"""
)
self.assertHTMLEqual(
p.as_p(),
"""<ul class="errorlist"><li>This field is required.</li></ul>
<p><label for="id_first_name">First name:</label>
<input type="text" name="first_name" id="id_first_name" required /></p>
<ul class="errorlist"><li>This field is required.</li></ul>
<p><label for="id_last_name">Last name:</label>
<input type="text" name="last_name" id="id_last_name" required /></p>
<ul class="errorlist"><li>This field is required.</li></ul>
<p><label for="id_birthday">Birthday:</label>
<input type="text" name="birthday" id="id_birthday" required /></p>"""
)
def test_unbound_form(self):
# If you don't pass any values to the Form's __init__(), or if you pass None,
# the Form will be considered unbound and won't do any validation. Form.errors
# will be an empty dictionary *but* Form.is_valid() will return False.
p = Person()
self.assertFalse(p.is_bound)
self.assertEqual(p.errors, {})
self.assertFalse(p.is_valid())
with self.assertRaises(AttributeError):
p.cleaned_data
self.assertHTMLEqual(
str(p),
"""<tr><th><label for="id_first_name">First name:</label></th><td>
<input type="text" name="first_name" id="id_first_name" required /></td></tr>
<tr><th><label for="id_last_name">Last name:</label></th><td>
<input type="text" name="last_name" id="id_last_name" required /></td></tr>
<tr><th><label for="id_birthday">Birthday:</label></th><td>
<input type="text" name="birthday" id="id_birthday" required /></td></tr>"""
)
self.assertHTMLEqual(
p.as_table(),
"""<tr><th><label for="id_first_name">First name:</label></th><td>
<input type="text" name="first_name" id="id_first_name" required /></td></tr>
<tr><th><label for="id_last_name">Last name:</label></th><td>
<input type="text" name="last_name" id="id_last_name" required /></td></tr>
<tr><th><label for="id_birthday">Birthday:</label></th><td>
<input type="text" name="birthday" id="id_birthday" required /></td></tr>"""
)
self.assertHTMLEqual(
p.as_ul(),
"""<li><label for="id_first_name">First name:</label>
<input type="text" name="first_name" id="id_first_name" required /></li>
<li><label for="id_last_name">Last name:</label>
<input type="text" name="last_name" id="id_last_name" required /></li>
<li><label for="id_birthday">Birthday:</label>
<input type="text" name="birthday" id="id_birthday" required /></li>"""
)
self.assertHTMLEqual(
p.as_p(),
"""<p><label for="id_first_name">First name:</label>
<input type="text" name="first_name" id="id_first_name" required /></p>
<p><label for="id_last_name">Last name:</label>
<input type="text" name="last_name" id="id_last_name" required /></p>
<p><label for="id_birthday">Birthday:</label>
<input type="text" name="birthday" id="id_birthday" required /></p>"""
)
def test_unicode_values(self):
# Unicode values are handled properly.
p = Person({
'first_name': 'John',
'last_name': '\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111',
'birthday': '1940-10-9'
})
self.assertHTMLEqual(
p.as_table(),
'<tr><th><label for="id_first_name">First name:</label></th><td>'
'<input type="text" name="first_name" value="John" id="id_first_name" required /></td></tr>\n'
'<tr><th><label for="id_last_name">Last name:</label>'
'</th><td><input type="text" name="last_name" '
'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111"'
'id="id_last_name" required /></td></tr>\n'
'<tr><th><label for="id_birthday">Birthday:</label></th><td>'
'<input type="text" name="birthday" value="1940-10-9" id="id_birthday" required /></td></tr>'
)
self.assertHTMLEqual(
p.as_ul(),
'<li><label for="id_first_name">First name:</label> '
'<input type="text" name="first_name" value="John" id="id_first_name" required /></li>\n'
'<li><label for="id_last_name">Last name:</label> '
'<input type="text" name="last_name" '
'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" required /></li>\n'
'<li><label for="id_birthday">Birthday:</label> '
'<input type="text" name="birthday" value="1940-10-9" id="id_birthday" required /></li>'
)
self.assertHTMLEqual(
p.as_p(),
'<p><label for="id_first_name">First name:</label> '
'<input type="text" name="first_name" value="John" id="id_first_name" required /></p>\n'
'<p><label for="id_last_name">Last name:</label> '
'<input type="text" name="last_name" '
'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" required /></p>\n'
'<p><label for="id_birthday">Birthday:</label> '
'<input type="text" name="birthday" value="1940-10-9" id="id_birthday" required /></p>'
)
p = Person({'last_name': 'Lennon'})
self.assertEqual(p.errors['first_name'], ['This field is required.'])
self.assertEqual(p.errors['birthday'], ['This field is required.'])
self.assertFalse(p.is_valid())
self.assertDictEqual(
p.errors,
{'birthday': ['This field is required.'], 'first_name': ['This field is required.']}
)
self.assertEqual(p.cleaned_data, {'last_name': 'Lennon'})
self.assertEqual(p['first_name'].errors, ['This field is required.'])
self.assertHTMLEqual(
p['first_name'].errors.as_ul(),
'<ul class="errorlist"><li>This field is required.</li></ul>'
)
self.assertEqual(p['first_name'].errors.as_text(), '* This field is required.')
p = Person()
self.assertHTMLEqual(
str(p['first_name']),
'<input type="text" name="first_name" id="id_first_name" required />',
)
self.assertHTMLEqual(str(p['last_name']), '<input type="text" name="last_name" id="id_last_name" required />')
self.assertHTMLEqual(str(p['birthday']), '<input type="text" name="birthday" id="id_birthday" required />')
def test_cleaned_data_only_fields(self):
# cleaned_data will always *only* contain a key for fields defined in the
# Form, even if you pass extra data when you define the Form. In this
# example, we pass a bunch of extra fields to the form constructor,
# but cleaned_data contains only the form's fields.
data = {
'first_name': 'John',
'last_name': 'Lennon',
'birthday': '1940-10-9',
'extra1': 'hello',
'extra2': 'hello',
}
p = Person(data)
self.assertTrue(p.is_valid())
self.assertEqual(p.cleaned_data['first_name'], 'John')
self.assertEqual(p.cleaned_data['last_name'], 'Lennon')
self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9))
def test_optional_data(self):
# cleaned_data will include a key and value for *all* fields defined in the Form,
# even if the Form's data didn't include a value for fields that are not
# required. In this example, the data dictionary doesn't include a value for the
# "nick_name" field, but cleaned_data includes it. For CharFields, it's set to the
# empty string.
class OptionalPersonForm(Form):
first_name = CharField()
last_name = CharField()
nick_name = CharField(required=False)
data = {'first_name': 'John', 'last_name': 'Lennon'}
f = OptionalPersonForm(data)
self.assertTrue(f.is_valid())
self.assertEqual(f.cleaned_data['nick_name'], '')
self.assertEqual(f.cleaned_data['first_name'], 'John')
self.assertEqual(f.cleaned_data['last_name'], 'Lennon')
# For DateFields, it's set to None.
class OptionalPersonForm(Form):
first_name = CharField()
last_name = CharField()
birth_date = DateField(required=False)
data = {'first_name': 'John', 'last_name': 'Lennon'}
f = OptionalPersonForm(data)
self.assertTrue(f.is_valid())
self.assertIsNone(f.cleaned_data['birth_date'])
self.assertEqual(f.cleaned_data['first_name'], 'John')
self.assertEqual(f.cleaned_data['last_name'], 'Lennon')
def test_auto_id(self):
# "auto_id" tells the Form to add an "id" attribute to each form element.
# If it's a string that contains '%s', Django will use that as a format string
# into which the field's name will be inserted. It will also put a <label> around
# the human-readable labels for a field.
p = Person(auto_id='%s_id')
self.assertHTMLEqual(
p.as_table(),
"""<tr><th><label for="first_name_id">First name:</label></th><td>
<input type="text" name="first_name" id="first_name_id" required /></td></tr>
<tr><th><label for="last_name_id">Last name:</label></th><td>
<input type="text" name="last_name" id="last_name_id" required /></td></tr>
<tr><th><label for="birthday_id">Birthday:</label></th><td>
<input type="text" name="birthday" id="birthday_id" required /></td></tr>"""
)
self.assertHTMLEqual(
p.as_ul(),
"""<li><label for="first_name_id">First name:</label>
<input type="text" name="first_name" id="first_name_id" required /></li>
<li><label for="last_name_id">Last name:</label>
<input type="text" name="last_name" id="last_name_id" required /></li>
<li><label for="birthday_id">Birthday:</label>
<input type="text" name="birthday" id="birthday_id" required /></li>"""
)
self.assertHTMLEqual(
p.as_p(),
"""<p><label for="first_name_id">First name:</label>
<input type="text" name="first_name" id="first_name_id" required /></p>
<p><label for="last_name_id">Last name:</label>
<input type="text" name="last_name" id="last_name_id" required /></p>
<p><label for="birthday_id">Birthday:</label>
<input type="text" name="birthday" id="birthday_id" required /></p>"""
)
def test_auto_id_true(self):
# If auto_id is any True value whose str() does not contain '%s', the "id"
# attribute will be the name of the field.
p = Person(auto_id=True)
self.assertHTMLEqual(
p.as_ul(),
"""<li><label for="first_name">First name:</label>
<input type="text" name="first_name" id="first_name" required /></li>
<li><label for="last_name">Last name:</label>
<input type="text" name="last_name" id="last_name" required /></li>
<li><label for="birthday">Birthday:</label>
<input type="text" name="birthday" id="birthday" required /></li>"""
)
def test_auto_id_false(self):
# If auto_id is any False value, an "id" attribute won't be output unless it
# was manually entered.
p = Person(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li>First name: <input type="text" name="first_name" required /></li>
<li>Last name: <input type="text" name="last_name" required /></li>
<li>Birthday: <input type="text" name="birthday" required /></li>"""
)
def test_id_on_field(self):
# In this example, auto_id is False, but the "id" attribute for the "first_name"
# field is given. Also note that field gets a <label>, while the others don't.
p = PersonNew(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li><label for="first_name_id">First name:</label>
<input type="text" id="first_name_id" name="first_name" required /></li>
<li>Last name: <input type="text" name="last_name" required /></li>
<li>Birthday: <input type="text" name="birthday" required /></li>"""
)
def test_auto_id_on_form_and_field(self):
# If the "id" attribute is specified in the Form and auto_id is True, the "id"
# attribute in the Form gets precedence.
p = PersonNew(auto_id=True)
self.assertHTMLEqual(
p.as_ul(),
"""<li><label for="first_name_id">First name:</label>
<input type="text" id="first_name_id" name="first_name" required /></li>
<li><label for="last_name">Last name:</label>
<input type="text" name="last_name" id="last_name" required /></li>
<li><label for="birthday">Birthday:</label>
<input type="text" name="birthday" id="birthday" required /></li>"""
)
def test_various_boolean_values(self):
class SignupForm(Form):
email = EmailField()
get_spam = BooleanField()
f = SignupForm(auto_id=False)
self.assertHTMLEqual(str(f['email']), '<input type="email" name="email" required />')
self.assertHTMLEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" required />')
f = SignupForm({'email': '[email protected]', 'get_spam': True}, auto_id=False)
self.assertHTMLEqual(str(f['email']), '<input type="email" name="email" value="[email protected]" required />')
self.assertHTMLEqual(
str(f['get_spam']),
'<input checked type="checkbox" name="get_spam" required />',
)
# 'True' or 'true' should be rendered without a value attribute
f = SignupForm({'email': '[email protected]', 'get_spam': 'True'}, auto_id=False)
self.assertHTMLEqual(
str(f['get_spam']),
'<input checked type="checkbox" name="get_spam" required />',
)
f = SignupForm({'email': '[email protected]', 'get_spam': 'true'}, auto_id=False)
self.assertHTMLEqual(
str(f['get_spam']), '<input checked type="checkbox" name="get_spam" required />')
# A value of 'False' or 'false' should be rendered unchecked
f = SignupForm({'email': '[email protected]', 'get_spam': 'False'}, auto_id=False)
self.assertHTMLEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" required />')
f = SignupForm({'email': '[email protected]', 'get_spam': 'false'}, auto_id=False)
self.assertHTMLEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" required />')
# A value of '0' should be interpreted as a True value (#16820)
f = SignupForm({'email': '[email protected]', 'get_spam': '0'})
self.assertTrue(f.is_valid())
self.assertTrue(f.cleaned_data.get('get_spam'))
def test_widget_output(self):
# Any Field can have a Widget class passed to its constructor:
class ContactForm(Form):
subject = CharField()
message = CharField(widget=Textarea)
f = ContactForm(auto_id=False)
self.assertHTMLEqual(str(f['subject']), '<input type="text" name="subject" required />')
self.assertHTMLEqual(str(f['message']), '<textarea name="message" rows="10" cols="40" required></textarea>')
# as_textarea(), as_text() and as_hidden() are shortcuts for changing the output
# widget type:
self.assertHTMLEqual(
f['subject'].as_textarea(),
'<textarea name="subject" rows="10" cols="40" required></textarea>',
)
self.assertHTMLEqual(f['message'].as_text(), '<input type="text" name="message" required />')
self.assertHTMLEqual(f['message'].as_hidden(), '<input type="hidden" name="message" />')
# The 'widget' parameter to a Field can also be an instance:
class ContactForm(Form):
subject = CharField()
message = CharField(widget=Textarea(attrs={'rows': 80, 'cols': 20}))
f = ContactForm(auto_id=False)
self.assertHTMLEqual(str(f['message']), '<textarea name="message" rows="80" cols="20" required></textarea>')
# Instance-level attrs are *not* carried over to as_textarea(), as_text() and
# as_hidden():
self.assertHTMLEqual(f['message'].as_text(), '<input type="text" name="message" required />')
f = ContactForm({'subject': 'Hello', 'message': 'I love you.'}, auto_id=False)
self.assertHTMLEqual(
f['subject'].as_textarea(),
'<textarea rows="10" cols="40" name="subject" required>Hello</textarea>'
)
self.assertHTMLEqual(
f['message'].as_text(),
'<input type="text" name="message" value="I love you." required />',
)
self.assertHTMLEqual(f['message'].as_hidden(), '<input type="hidden" name="message" value="I love you." />')
def test_forms_with_choices(self):
# For a form with a <select>, use ChoiceField:
class FrameworkForm(Form):
name = CharField()
language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')])
f = FrameworkForm(auto_id=False)
self.assertHTMLEqual(str(f['language']), """<select name="language">
<option value="P">Python</option>
<option value="J">Java</option>
</select>""")
f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False)
self.assertHTMLEqual(str(f['language']), """<select name="language">
<option value="P" selected>Python</option>
<option value="J">Java</option>
</select>""")
# A subtlety: If one of the choices' value is the empty string and the form is
# unbound, then the <option> for the empty-string choice will get selected.
class FrameworkForm(Form):
name = CharField()
language = ChoiceField(choices=[('', '------'), ('P', 'Python'), ('J', 'Java')])
f = FrameworkForm(auto_id=False)
self.assertHTMLEqual(str(f['language']), """<select name="language" required>
<option value="" selected>------</option>
<option value="P">Python</option>
<option value="J">Java</option>
</select>""")
# You can specify widget attributes in the Widget constructor.
class FrameworkForm(Form):
name = CharField()
language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=Select(attrs={'class': 'foo'}))
f = FrameworkForm(auto_id=False)
self.assertHTMLEqual(str(f['language']), """<select class="foo" name="language">
<option value="P">Python</option>
<option value="J">Java</option>
</select>""")
f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False)
self.assertHTMLEqual(str(f['language']), """<select class="foo" name="language">
<option value="P" selected>Python</option>
<option value="J">Java</option>
</select>""")
# When passing a custom widget instance to ChoiceField, note that setting
# 'choices' on the widget is meaningless. The widget will use the choices
# defined on the Field, not the ones defined on the Widget.
class FrameworkForm(Form):
name = CharField()
language = ChoiceField(
choices=[('P', 'Python'), ('J', 'Java')],
widget=Select(choices=[('R', 'Ruby'), ('P', 'Perl')], attrs={'class': 'foo'}),
)
f = FrameworkForm(auto_id=False)
self.assertHTMLEqual(str(f['language']), """<select class="foo" name="language">
<option value="P">Python</option>
<option value="J">Java</option>
</select>""")
f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False)
self.assertHTMLEqual(str(f['language']), """<select class="foo" name="language">
<option value="P" selected>Python</option>
<option value="J">Java</option>
</select>""")
# You can set a ChoiceField's choices after the fact.
class FrameworkForm(Form):
name = CharField()
language = ChoiceField()
f = FrameworkForm(auto_id=False)
self.assertHTMLEqual(str(f['language']), """<select name="language">
</select>""")
f.fields['language'].choices = [('P', 'Python'), ('J', 'Java')]
self.assertHTMLEqual(str(f['language']), """<select name="language">
<option value="P">Python</option>
<option value="J">Java</option>
</select>""")
def test_forms_with_radio(self):
# Add widget=RadioSelect to use that widget with a ChoiceField.
class FrameworkForm(Form):
name = CharField()
language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=RadioSelect)
f = FrameworkForm(auto_id=False)
self.assertHTMLEqual(str(f['language']), """<ul>
<li><label><input type="radio" name="language" value="P" required /> Python</label></li>
<li><label><input type="radio" name="language" value="J" required /> Java</label></li>
</ul>""")
self.assertHTMLEqual(f.as_table(), """<tr><th>Name:</th><td><input type="text" name="name" required /></td></tr>
<tr><th>Language:</th><td><ul>
<li><label><input type="radio" name="language" value="P" required /> Python</label></li>
<li><label><input type="radio" name="language" value="J" required /> Java</label></li>
</ul></td></tr>""")
self.assertHTMLEqual(f.as_ul(), """<li>Name: <input type="text" name="name" required /></li>
<li>Language: <ul>
<li><label><input type="radio" name="language" value="P" required /> Python</label></li>
<li><label><input type="radio" name="language" value="J" required /> Java</label></li>
</ul></li>""")
# Regarding auto_id and <label>, RadioSelect is a special case. Each radio button
# gets a distinct ID, formed by appending an underscore plus the button's
# zero-based index.
f = FrameworkForm(auto_id='id_%s')
self.assertHTMLEqual(
str(f['language']),
"""<ul id="id_language">
<li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" required />
Python</label></li>
<li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" required />
Java</label></li>
</ul>"""
)
# When RadioSelect is used with auto_id, and the whole form is printed using
# either as_table() or as_ul(), the label for the RadioSelect will point to the
# ID of the *first* radio button.
self.assertHTMLEqual(
f.as_table(),
"""<tr><th><label for="id_name">Name:</label></th><td><input type="text" name="name" id="id_name" required /></td></tr>
<tr><th><label for="id_language_0">Language:</label></th><td><ul id="id_language">
<li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" required />
Python</label></li>
<li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" required />
Java</label></li>
</ul></td></tr>"""
)
self.assertHTMLEqual(
f.as_ul(),
"""<li><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" required /></li>
<li><label for="id_language_0">Language:</label> <ul id="id_language">
<li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" required />
Python</label></li>
<li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" required />
Java</label></li>
</ul></li>"""
)
self.assertHTMLEqual(
f.as_p(),
"""<p><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" required /></p>
<p><label for="id_language_0">Language:</label> <ul id="id_language">
<li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" required />
Python</label></li>
<li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" required />
Java</label></li>
</ul></p>"""
)
# Test iterating on individual radios in a template
t = Template('{% for radio in form.language %}<div class="myradio">{{ radio }}</div>{% endfor %}')
self.assertHTMLEqual(
t.render(Context({'form': f})),
"""<div class="myradio"><label for="id_language_0">
<input id="id_language_0" name="language" type="radio" value="P" required /> Python</label></div>
<div class="myradio"><label for="id_language_1">
<input id="id_language_1" name="language" type="radio" value="J" required /> Java</label></div>"""
)
def test_form_with_iterable_boundfield(self):
class BeatleForm(Form):
name = ChoiceField(
choices=[('john', 'John'), ('paul', 'Paul'), ('george', 'George'), ('ringo', 'Ringo')],
widget=RadioSelect,
)
f = BeatleForm(auto_id=False)
self.assertHTMLEqual(
'\n'.join(str(bf) for bf in f['name']),
"""<label><input type="radio" name="name" value="john" required /> John</label>
<label><input type="radio" name="name" value="paul" required /> Paul</label>
<label><input type="radio" name="name" value="george" required /> George</label>
<label><input type="radio" name="name" value="ringo" required /> Ringo</label>"""
)
self.assertHTMLEqual(
'\n'.join('<div>%s</div>' % bf for bf in f['name']),
"""<div><label><input type="radio" name="name" value="john" required /> John</label></div>
<div><label><input type="radio" name="name" value="paul" required /> Paul</label></div>
<div><label><input type="radio" name="name" value="george" required /> George</label></div>
<div><label><input type="radio" name="name" value="ringo" required /> Ringo</label></div>"""
)
def test_form_with_iterable_boundfield_id(self):
class BeatleForm(Form):
name = ChoiceField(
choices=[('john', 'John'), ('paul', 'Paul'), ('george', 'George'), ('ringo', 'Ringo')],
widget=RadioSelect,
)
fields = list(BeatleForm()['name'])
self.assertEqual(len(fields), 4)
self.assertEqual(fields[0].id_for_label, 'id_name_0')
self.assertEqual(fields[0].choice_label, 'John')
self.assertHTMLEqual(
fields[0].tag(),
'<input type="radio" name="name" value="john" id="id_name_0" required />'
)
self.assertHTMLEqual(
str(fields[0]),
'<label for="id_name_0"><input type="radio" name="name" '
'value="john" id="id_name_0" required /> John</label>'
)
self.assertEqual(fields[1].id_for_label, 'id_name_1')
self.assertEqual(fields[1].choice_label, 'Paul')
self.assertHTMLEqual(
fields[1].tag(),
'<input type="radio" name="name" value="paul" id="id_name_1" required />'
)
self.assertHTMLEqual(
str(fields[1]),
'<label for="id_name_1"><input type="radio" name="name" '
'value="paul" id="id_name_1" required /> Paul</label>'
)
def test_iterable_boundfield_select(self):
class BeatleForm(Form):
name = ChoiceField(choices=[('john', 'John'), ('paul', 'Paul'), ('george', 'George'), ('ringo', 'Ringo')])
fields = list(BeatleForm(auto_id=False)['name'])
self.assertEqual(len(fields), 4)
self.assertEqual(fields[0].id_for_label, 'id_name_0')
self.assertEqual(fields[0].choice_label, 'John')
self.assertHTMLEqual(fields[0].tag(), '<option value="john">John</option>')
self.assertHTMLEqual(str(fields[0]), '<option value="john">John</option>')
def test_form_with_noniterable_boundfield(self):
# You can iterate over any BoundField, not just those with widget=RadioSelect.
class BeatleForm(Form):
name = CharField()
f = BeatleForm(auto_id=False)
self.assertHTMLEqual('\n'.join(str(bf) for bf in f['name']), '<input type="text" name="name" required />')
def test_boundfield_slice(self):
class BeatleForm(Form):
name = ChoiceField(
choices=[('john', 'John'), ('paul', 'Paul'), ('george', 'George'), ('ringo', 'Ringo')],
widget=RadioSelect,
)
f = BeatleForm()
bf = f['name']
self.assertEqual(
[str(item) for item in bf[1:]],
[str(bf[1]), str(bf[2]), str(bf[3])],
)
def test_forms_with_multiple_choice(self):
# MultipleChoiceField is a special case, as its data is required to be a list:
class SongForm(Form):
name = CharField()
composers = MultipleChoiceField()
f = SongForm(auto_id=False)
self.assertHTMLEqual(str(f['composers']), """<select multiple="multiple" name="composers" required>
</select>""")
class SongForm(Form):
name = CharField()
composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')])
f = SongForm(auto_id=False)
self.assertHTMLEqual(str(f['composers']), """<select multiple="multiple" name="composers" required>
<option value="J">John Lennon</option>
<option value="P">Paul McCartney</option>
</select>""")
f = SongForm({'name': 'Yesterday', 'composers': ['P']}, auto_id=False)
self.assertHTMLEqual(str(f['name']), '<input type="text" name="name" value="Yesterday" required />')
self.assertHTMLEqual(str(f['composers']), """<select multiple="multiple" name="composers" required>
<option value="J">John Lennon</option>
<option value="P" selected>Paul McCartney</option>
</select>""")
def test_form_with_disabled_fields(self):
class PersonForm(Form):
name = CharField()
birthday = DateField(disabled=True)
class PersonFormFieldInitial(Form):
name = CharField()
birthday = DateField(disabled=True, initial=datetime.date(1974, 8, 16))
# Disabled fields are generally not transmitted by user agents.
# The value from the form's initial data is used.
f1 = PersonForm({'name': 'John Doe'}, initial={'birthday': datetime.date(1974, 8, 16)})
f2 = PersonFormFieldInitial({'name': 'John Doe'})
for form in (f1, f2):
self.assertTrue(form.is_valid())
self.assertEqual(
form.cleaned_data,
{'birthday': datetime.date(1974, 8, 16), 'name': 'John Doe'}
)
# Values provided in the form's data are ignored.
data = {'name': 'John Doe', 'birthday': '1984-11-10'}
f1 = PersonForm(data, initial={'birthday': datetime.date(1974, 8, 16)})
f2 = PersonFormFieldInitial(data)
for form in (f1, f2):
self.assertTrue(form.is_valid())
self.assertEqual(
form.cleaned_data,
{'birthday': datetime.date(1974, 8, 16), 'name': 'John Doe'}
)
# Initial data remains present on invalid forms.
data = {}
f1 = PersonForm(data, initial={'birthday': datetime.date(1974, 8, 16)})
f2 = PersonFormFieldInitial(data)
for form in (f1, f2):
self.assertFalse(form.is_valid())
self.assertEqual(form['birthday'].value(), datetime.date(1974, 8, 16))
def test_hidden_data(self):
class SongForm(Form):
name = CharField()
composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')])
# MultipleChoiceField rendered as_hidden() is a special case. Because it can
# have multiple values, its as_hidden() renders multiple <input type="hidden">
# tags.
f = SongForm({'name': 'Yesterday', 'composers': ['P']}, auto_id=False)
self.assertHTMLEqual(f['composers'].as_hidden(), '<input type="hidden" name="composers" value="P" />')
f = SongForm({'name': 'From Me To You', 'composers': ['P', 'J']}, auto_id=False)
self.assertHTMLEqual(f['composers'].as_hidden(), """<input type="hidden" name="composers" value="P" />
<input type="hidden" name="composers" value="J" />""")
# DateTimeField rendered as_hidden() is special too
class MessageForm(Form):
when = SplitDateTimeField()
f = MessageForm({'when_0': '1992-01-01', 'when_1': '01:01'})
self.assertTrue(f.is_valid())
self.assertHTMLEqual(
str(f['when']),
'<input type="text" name="when_0" value="1992-01-01" id="id_when_0" required />'
'<input type="text" name="when_1" value="01:01" id="id_when_1" required />'
)
self.assertHTMLEqual(
f['when'].as_hidden(),
'<input type="hidden" name="when_0" value="1992-01-01" id="id_when_0" />'
'<input type="hidden" name="when_1" value="01:01" id="id_when_1" />'
)
def test_multiple_choice_checkbox(self):
# MultipleChoiceField can also be used with the CheckboxSelectMultiple widget.
class SongForm(Form):
name = CharField()
composers = MultipleChoiceField(
choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')],
widget=CheckboxSelectMultiple,
)
f = SongForm(auto_id=False)
self.assertHTMLEqual(str(f['composers']), """<ul>
<li><label><input type="checkbox" name="composers" value="J" /> John Lennon</label></li>
<li><label><input type="checkbox" name="composers" value="P" /> Paul McCartney</label></li>
</ul>""")
f = SongForm({'composers': ['J']}, auto_id=False)
self.assertHTMLEqual(str(f['composers']), """<ul>
<li><label><input checked type="checkbox" name="composers" value="J" /> John Lennon</label></li>
<li><label><input type="checkbox" name="composers" value="P" /> Paul McCartney</label></li>
</ul>""")
f = SongForm({'composers': ['J', 'P']}, auto_id=False)
self.assertHTMLEqual(str(f['composers']), """<ul>
<li><label><input checked type="checkbox" name="composers" value="J" /> John Lennon</label></li>
<li><label><input checked type="checkbox" name="composers" value="P" /> Paul McCartney</label></li>
</ul>""")
# Test iterating on individual checkboxes in a template
t = Template('{% for checkbox in form.composers %}<div class="mycheckbox">{{ checkbox }}</div>{% endfor %}')
self.assertHTMLEqual(t.render(Context({'form': f})), """<div class="mycheckbox"><label>
<input checked name="composers" type="checkbox" value="J" /> John Lennon</label></div>
<div class="mycheckbox"><label>
<input checked name="composers" type="checkbox" value="P" /> Paul McCartney</label></div>""")
def test_checkbox_auto_id(self):
# Regarding auto_id, CheckboxSelectMultiple is a special case. Each checkbox
# gets a distinct ID, formed by appending an underscore plus the checkbox's
# zero-based index.
class SongForm(Form):
name = CharField()
composers = MultipleChoiceField(
choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')],
widget=CheckboxSelectMultiple,
)
f = SongForm(auto_id='%s_id')
self.assertHTMLEqual(
str(f['composers']),
"""<ul id="composers_id">
<li><label for="composers_id_0">
<input type="checkbox" name="composers" value="J" id="composers_id_0" /> John Lennon</label></li>
<li><label for="composers_id_1">
<input type="checkbox" name="composers" value="P" id="composers_id_1" /> Paul McCartney</label></li>
</ul>"""
)
def test_multiple_choice_list_data(self):
# Data for a MultipleChoiceField should be a list. QueryDict and
# MultiValueDict conveniently work with this.
class SongForm(Form):
name = CharField()
composers = MultipleChoiceField(
choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')],
widget=CheckboxSelectMultiple,
)
data = {'name': 'Yesterday', 'composers': ['J', 'P']}
f = SongForm(data)
self.assertEqual(f.errors, {})
data = QueryDict('name=Yesterday&composers=J&composers=P')
f = SongForm(data)
self.assertEqual(f.errors, {})
data = MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P']))
f = SongForm(data)
self.assertEqual(f.errors, {})
# SelectMultiple uses ducktyping so that MultiValueDictLike.getlist()
# is called.
f = SongForm(MultiValueDictLike({'name': 'Yesterday', 'composers': 'J'}))
self.assertEqual(f.errors, {})
self.assertEqual(f.cleaned_data['composers'], ['J'])
def test_multiple_hidden(self):
class SongForm(Form):
name = CharField()
composers = MultipleChoiceField(
choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')],
widget=CheckboxSelectMultiple,
)
# The MultipleHiddenInput widget renders multiple values as hidden fields.
class SongFormHidden(Form):
name = CharField()
composers = MultipleChoiceField(
choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')],
widget=MultipleHiddenInput,
)
f = SongFormHidden(MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P'])), auto_id=False)
self.assertHTMLEqual(
f.as_ul(),
"""<li>Name: <input type="text" name="name" value="Yesterday" required />
<input type="hidden" name="composers" value="J" />
<input type="hidden" name="composers" value="P" /></li>"""
)
# When using CheckboxSelectMultiple, the framework expects a list of input and
# returns a list of input.
f = SongForm({'name': 'Yesterday'}, auto_id=False)
self.assertEqual(f.errors['composers'], ['This field is required.'])
f = SongForm({'name': 'Yesterday', 'composers': ['J']}, auto_id=False)
self.assertEqual(f.errors, {})
self.assertEqual(f.cleaned_data['composers'], ['J'])
self.assertEqual(f.cleaned_data['name'], 'Yesterday')
f = SongForm({'name': 'Yesterday', 'composers': ['J', 'P']}, auto_id=False)
self.assertEqual(f.errors, {})
self.assertEqual(f.cleaned_data['composers'], ['J', 'P'])
self.assertEqual(f.cleaned_data['name'], 'Yesterday')
# MultipleHiddenInput uses ducktyping so that
# MultiValueDictLike.getlist() is called.
f = SongForm(MultiValueDictLike({'name': 'Yesterday', 'composers': 'J'}))
self.assertEqual(f.errors, {})
self.assertEqual(f.cleaned_data['composers'], ['J'])
def test_escaping(self):
# Validation errors are HTML-escaped when output as HTML.
class EscapingForm(Form):
special_name = CharField(label="<em>Special</em> Field")
special_safe_name = CharField(label=mark_safe("<em>Special</em> Field"))
def clean_special_name(self):
raise ValidationError("Something's wrong with '%s'" % self.cleaned_data['special_name'])
def clean_special_safe_name(self):
raise ValidationError(
mark_safe("'<b>%s</b>' is a safe string" % self.cleaned_data['special_safe_name'])
)
f = EscapingForm({
'special_name':
"Nothing to escape",
'special_safe_name': "Nothing to escape",
}, auto_id=False)
self.assertHTMLEqual(
f.as_table(),
"""<tr><th><em>Special</em> Field:</th><td>
<ul class="errorlist"><li>Something's wrong with 'Nothing to escape'</li></ul>
<input type="text" name="special_name" value="Nothing to escape" required /></td></tr>
<tr><th><em>Special</em> Field:</th><td>
<ul class="errorlist"><li>'<b>Nothing to escape</b>' is a safe string</li></ul>
<input type="text" name="special_safe_name" value="Nothing to escape" required /></td></tr>"""
)
f = EscapingForm({
'special_name': "Should escape < & > and <script>alert('xss')</script>",
'special_safe_name': "<i>Do not escape</i>"
}, auto_id=False)
self.assertHTMLEqual(
f.as_table(),
"""<tr><th><em>Special</em> Field:</th><td>
<ul class="errorlist"><li>Something's wrong with 'Should escape < & > and
<script>alert('xss')</script>'</li></ul>
<input type="text" name="special_name"
value="Should escape < & > and <script>alert('xss')</script>" required /></td></tr>
<tr><th><em>Special</em> Field:</th><td>
<ul class="errorlist"><li>'<b><i>Do not escape</i></b>' is a safe string</li></ul>
<input type="text" name="special_safe_name" value="<i>Do not escape</i>" required /></td></tr>"""
)
def test_validating_multiple_fields(self):
# There are a couple of ways to do multiple-field validation. If you want the
# validation message to be associated with a particular field, implement the
# clean_XXX() method on the Form, where XXX is the field name. As in
# Field.clean(), the clean_XXX() method should return the cleaned value. In the
# clean_XXX() method, you have access to self.cleaned_data, which is a dictionary
# of all the data that has been cleaned *so far*, in order by the fields,
# including the current field (e.g., the field XXX if you're in clean_XXX()).
class UserRegistration(Form):
username = CharField(max_length=10)
password1 = CharField(widget=PasswordInput)
password2 = CharField(widget=PasswordInput)
def clean_password2(self):
if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and
self.cleaned_data['password1'] != self.cleaned_data['password2']):
raise ValidationError('Please make sure your passwords match.')
return self.cleaned_data['password2']
f = UserRegistration(auto_id=False)
self.assertEqual(f.errors, {})
f = UserRegistration({}, auto_id=False)
self.assertEqual(f.errors['username'], ['This field is required.'])
self.assertEqual(f.errors['password1'], ['This field is required.'])
self.assertEqual(f.errors['password2'], ['This field is required.'])
f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
self.assertEqual(f.errors['password2'], ['Please make sure your passwords match.'])
f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False)
self.assertEqual(f.errors, {})
self.assertEqual(f.cleaned_data['username'], 'adrian')
self.assertEqual(f.cleaned_data['password1'], 'foo')
self.assertEqual(f.cleaned_data['password2'], 'foo')
# Another way of doing multiple-field validation is by implementing the
# Form's clean() method. Usually ValidationError raised by that method
# will not be associated with a particular field and will have a
# special-case association with the field named '__all__'. It's
# possible to associate the errors to particular field with the
# Form.add_error() method or by passing a dictionary that maps each
# field to one or more errors.
#
# Note that in Form.clean(), you have access to self.cleaned_data, a
# dictionary of all the fields/values that have *not* raised a
# ValidationError. Also note Form.clean() is required to return a
# dictionary of all clean data.
class UserRegistration(Form):
username = CharField(max_length=10)
password1 = CharField(widget=PasswordInput)
password2 = CharField(widget=PasswordInput)
def clean(self):
# Test raising a ValidationError as NON_FIELD_ERRORS.
if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and
self.cleaned_data['password1'] != self.cleaned_data['password2']):
raise ValidationError('Please make sure your passwords match.')
# Test raising ValidationError that targets multiple fields.
errors = {}
if self.cleaned_data.get('password1') == 'FORBIDDEN_VALUE':
errors['password1'] = 'Forbidden value.'
if self.cleaned_data.get('password2') == 'FORBIDDEN_VALUE':
errors['password2'] = ['Forbidden value.']
if errors:
raise ValidationError(errors)
# Test Form.add_error()
if self.cleaned_data.get('password1') == 'FORBIDDEN_VALUE2':
self.add_error(None, 'Non-field error 1.')
self.add_error('password1', 'Forbidden value 2.')
if self.cleaned_data.get('password2') == 'FORBIDDEN_VALUE2':
self.add_error('password2', 'Forbidden value 2.')
raise ValidationError('Non-field error 2.')
return self.cleaned_data
f = UserRegistration(auto_id=False)
self.assertEqual(f.errors, {})
f = UserRegistration({}, auto_id=False)
self.assertHTMLEqual(
f.as_table(),
"""<tr><th>Username:</th><td>
<ul class="errorlist"><li>This field is required.</li></ul>
<input type="text" name="username" maxlength="10" required /></td></tr>
<tr><th>Password1:</th><td><ul class="errorlist"><li>This field is required.</li></ul>
<input type="password" name="password1" required /></td></tr>
<tr><th>Password2:</th><td><ul class="errorlist"><li>This field is required.</li></ul>
<input type="password" name="password2" required /></td></tr>"""
)
self.assertEqual(f.errors['username'], ['This field is required.'])
self.assertEqual(f.errors['password1'], ['This field is required.'])
self.assertEqual(f.errors['password2'], ['This field is required.'])
f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
self.assertEqual(f.errors['__all__'], ['Please make sure your passwords match.'])
self.assertHTMLEqual(
f.as_table(),
"""<tr><td colspan="2">
<ul class="errorlist nonfield"><li>Please make sure your passwords match.</li></ul></td></tr>
<tr><th>Username:</th><td><input type="text" name="username" value="adrian" maxlength="10" required /></td></tr>
<tr><th>Password1:</th><td><input type="password" name="password1" required /></td></tr>
<tr><th>Password2:</th><td><input type="password" name="password2" required /></td></tr>"""
)
self.assertHTMLEqual(
f.as_ul(),
"""<li><ul class="errorlist nonfield">
<li>Please make sure your passwords match.</li></ul></li>
<li>Username: <input type="text" name="username" value="adrian" maxlength="10" required /></li>
<li>Password1: <input type="password" name="password1" required /></li>
<li>Password2: <input type="password" name="password2" required /></li>"""
)
f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False)
self.assertEqual(f.errors, {})
self.assertEqual(f.cleaned_data['username'], 'adrian')
self.assertEqual(f.cleaned_data['password1'], 'foo')
self.assertEqual(f.cleaned_data['password2'], 'foo')
f = UserRegistration({
'username': 'adrian',
'password1': 'FORBIDDEN_VALUE',
'password2': 'FORBIDDEN_VALUE',
}, auto_id=False)
self.assertEqual(f.errors['password1'], ['Forbidden value.'])
self.assertEqual(f.errors['password2'], ['Forbidden value.'])
f = UserRegistration({
'username': 'adrian',
'password1': 'FORBIDDEN_VALUE2',
'password2': 'FORBIDDEN_VALUE2',
}, auto_id=False)
self.assertEqual(f.errors['__all__'], ['Non-field error 1.', 'Non-field error 2.'])
self.assertEqual(f.errors['password1'], ['Forbidden value 2.'])
self.assertEqual(f.errors['password2'], ['Forbidden value 2.'])
with self.assertRaisesMessage(ValueError, "has no field named"):
f.add_error('missing_field', 'Some error.')
def test_update_error_dict(self):
class CodeForm(Form):
code = CharField(max_length=10)
def clean(self):
try:
raise ValidationError({'code': [ValidationError('Code error 1.')]})
except ValidationError as e:
self._errors = e.update_error_dict(self._errors)
try:
raise ValidationError({'code': [ValidationError('Code error 2.')]})
except ValidationError as e:
self._errors = e.update_error_dict(self._errors)
try:
raise ValidationError({'code': forms.ErrorList(['Code error 3.'])})
except ValidationError as e:
self._errors = e.update_error_dict(self._errors)
try:
raise ValidationError('Non-field error 1.')
except ValidationError as e:
self._errors = e.update_error_dict(self._errors)
try:
raise ValidationError([ValidationError('Non-field error 2.')])
except ValidationError as e:
self._errors = e.update_error_dict(self._errors)
# The newly added list of errors is an instance of ErrorList.
for field, error_list in self._errors.items():
if not isinstance(error_list, self.error_class):
self._errors[field] = self.error_class(error_list)
form = CodeForm({'code': 'hello'})
# Trigger validation.
self.assertFalse(form.is_valid())
# update_error_dict didn't lose track of the ErrorDict type.
self.assertIsInstance(form._errors, forms.ErrorDict)
self.assertEqual(dict(form.errors), {
'code': ['Code error 1.', 'Code error 2.', 'Code error 3.'],
NON_FIELD_ERRORS: ['Non-field error 1.', 'Non-field error 2.'],
})
def test_has_error(self):
class UserRegistration(Form):
username = CharField(max_length=10)
password1 = CharField(widget=PasswordInput, min_length=5)
password2 = CharField(widget=PasswordInput)
def clean(self):
if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and
self.cleaned_data['password1'] != self.cleaned_data['password2']):
raise ValidationError(
'Please make sure your passwords match.',
code='password_mismatch',
)
f = UserRegistration(data={})
self.assertTrue(f.has_error('password1'))
self.assertTrue(f.has_error('password1', 'required'))
self.assertFalse(f.has_error('password1', 'anything'))
f = UserRegistration(data={'password1': 'Hi', 'password2': 'Hi'})
self.assertTrue(f.has_error('password1'))
self.assertTrue(f.has_error('password1', 'min_length'))
self.assertFalse(f.has_error('password1', 'anything'))
self.assertFalse(f.has_error('password2'))
self.assertFalse(f.has_error('password2', 'anything'))
f = UserRegistration(data={'password1': 'Bonjour', 'password2': 'Hello'})
self.assertFalse(f.has_error('password1'))
self.assertFalse(f.has_error('password1', 'required'))
self.assertTrue(f.has_error(NON_FIELD_ERRORS))
self.assertTrue(f.has_error(NON_FIELD_ERRORS, 'password_mismatch'))
self.assertFalse(f.has_error(NON_FIELD_ERRORS, 'anything'))
def test_dynamic_construction(self):
# It's possible to construct a Form dynamically by adding to the self.fields
# dictionary in __init__(). Don't forget to call Form.__init__() within the
# subclass' __init__().
class Person(Form):
first_name = CharField()
last_name = CharField()
def __init__(self, *args, **kwargs):
super(Person, self).__init__(*args, **kwargs)
self.fields['birthday'] = DateField()
p = Person(auto_id=False)
self.assertHTMLEqual(
p.as_table(),
"""<tr><th>First name:</th><td><input type="text" name="first_name" required /></td></tr>
<tr><th>Last name:</th><td><input type="text" name="last_name" required /></td></tr>
<tr><th>Birthday:</th><td><input type="text" name="birthday" required /></td></tr>"""
)
# Instances of a dynamic Form do not persist fields from one Form instance to
# the next.
class MyForm(Form):
def __init__(self, data=None, auto_id=False, field_list=[]):
Form.__init__(self, data, auto_id=auto_id)
for field in field_list:
self.fields[field[0]] = field[1]
field_list = [('field1', CharField()), ('field2', CharField())]
my_form = MyForm(field_list=field_list)
self.assertHTMLEqual(
my_form.as_table(),
"""<tr><th>Field1:</th><td><input type="text" name="field1" required /></td></tr>
<tr><th>Field2:</th><td><input type="text" name="field2" required /></td></tr>"""
)
field_list = [('field3', CharField()), ('field4', CharField())]
my_form = MyForm(field_list=field_list)
self.assertHTMLEqual(
my_form.as_table(),
"""<tr><th>Field3:</th><td><input type="text" name="field3" required /></td></tr>
<tr><th>Field4:</th><td><input type="text" name="field4" required /></td></tr>"""
)
class MyForm(Form):
default_field_1 = CharField()
default_field_2 = CharField()
def __init__(self, data=None, auto_id=False, field_list=[]):
Form.__init__(self, data, auto_id=auto_id)
for field in field_list:
self.fields[field[0]] = field[1]
field_list = [('field1', CharField()), ('field2', CharField())]
my_form = MyForm(field_list=field_list)
self.assertHTMLEqual(
my_form.as_table(),
"""<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" required /></td></tr>
<tr><th>Default field 2:</th><td><input type="text" name="default_field_2" required /></td></tr>
<tr><th>Field1:</th><td><input type="text" name="field1" required /></td></tr>
<tr><th>Field2:</th><td><input type="text" name="field2" required /></td></tr>"""
)
field_list = [('field3', CharField()), ('field4', CharField())]
my_form = MyForm(field_list=field_list)
self.assertHTMLEqual(
my_form.as_table(),
"""<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" required /></td></tr>
<tr><th>Default field 2:</th><td><input type="text" name="default_field_2" required /></td></tr>
<tr><th>Field3:</th><td><input type="text" name="field3" required /></td></tr>
<tr><th>Field4:</th><td><input type="text" name="field4" required /></td></tr>"""
)
# Similarly, changes to field attributes do not persist from one Form instance
# to the next.
class Person(Form):
first_name = CharField(required=False)
last_name = CharField(required=False)
def __init__(self, names_required=False, *args, **kwargs):
super(Person, self).__init__(*args, **kwargs)
if names_required:
self.fields['first_name'].required = True
self.fields['first_name'].widget.attrs['class'] = 'required'
self.fields['last_name'].required = True
self.fields['last_name'].widget.attrs['class'] = 'required'
f = Person(names_required=False)
self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (False, False))
self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({}, {}))
f = Person(names_required=True)
self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (True, True))
self.assertEqual(
f['first_name'].field.widget.attrs,
f['last_name'].field.widget.attrs,
({'class': 'reuired'}, {'class': 'required'})
)
f = Person(names_required=False)
self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (False, False))
self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({}, {}))
class Person(Form):
first_name = CharField(max_length=30)
last_name = CharField(max_length=30)
def __init__(self, name_max_length=None, *args, **kwargs):
super(Person, self).__init__(*args, **kwargs)
if name_max_length:
self.fields['first_name'].max_length = name_max_length
self.fields['last_name'].max_length = name_max_length
f = Person(name_max_length=None)
self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (30, 30))
f = Person(name_max_length=20)
self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (20, 20))
f = Person(name_max_length=None)
self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (30, 30))
# Similarly, choices do not persist from one Form instance to the next.
# Refs #15127.
class Person(Form):
first_name = CharField(required=False)
last_name = CharField(required=False)
gender = ChoiceField(choices=(('f', 'Female'), ('m', 'Male')))
def __init__(self, allow_unspec_gender=False, *args, **kwargs):
super(Person, self).__init__(*args, **kwargs)
if allow_unspec_gender:
self.fields['gender'].choices += (('u', 'Unspecified'),)
f = Person()
self.assertEqual(f['gender'].field.choices, [('f', 'Female'), ('m', 'Male')])
f = Person(allow_unspec_gender=True)
self.assertEqual(f['gender'].field.choices, [('f', 'Female'), ('m', 'Male'), ('u', 'Unspecified')])
f = Person()
self.assertEqual(f['gender'].field.choices, [('f', 'Female'), ('m', 'Male')])
def test_validators_independence(self):
"""
The list of form field validators can be modified without polluting
other forms.
"""
class MyForm(Form):
myfield = CharField(max_length=25)
f1 = MyForm()
f2 = MyForm()
f1.fields['myfield'].validators[0] = MaxValueValidator(12)
self.assertNotEqual(f1.fields['myfield'].validators[0], f2.fields['myfield'].validators[0])
def test_hidden_widget(self):
# HiddenInput widgets are displayed differently in the as_table(), as_ul())
# and as_p() output of a Form -- their verbose names are not displayed, and a
# separate row is not displayed. They're displayed in the last row of the
# form, directly after that row's form element.
class Person(Form):
first_name = CharField()
last_name = CharField()
hidden_text = CharField(widget=HiddenInput)
birthday = DateField()
p = Person(auto_id=False)
self.assertHTMLEqual(
p.as_table(),
"""<tr><th>First name:</th><td><input type="text" name="first_name" required /></td></tr>
<tr><th>Last name:</th><td><input type="text" name="last_name" required /></td></tr>
<tr><th>Birthday:</th>
<td><input type="text" name="birthday" required /><input type="hidden" name="hidden_text" /></td></tr>"""
)
self.assertHTMLEqual(
p.as_ul(),
"""<li>First name: <input type="text" name="first_name" required /></li>
<li>Last name: <input type="text" name="last_name" required /></li>
<li>Birthday: <input type="text" name="birthday" required /><input type="hidden" name="hidden_text" /></li>"""
)
self.assertHTMLEqual(
p.as_p(), """<p>First name: <input type="text" name="first_name" required /></p>
<p>Last name: <input type="text" name="last_name" required /></p>
<p>Birthday: <input type="text" name="birthday" required /><input type="hidden" name="hidden_text" /></p>"""
)
# With auto_id set, a HiddenInput still gets an ID, but it doesn't get a label.
p = Person(auto_id='id_%s')
self.assertHTMLEqual(
p.as_table(),
"""<tr><th><label for="id_first_name">First name:</label></th><td>
<input type="text" name="first_name" id="id_first_name" required /></td></tr>
<tr><th><label for="id_last_name">Last name:</label></th><td>
<input type="text" name="last_name" id="id_last_name" required /></td></tr>
<tr><th><label for="id_birthday">Birthday:</label></th><td>
<input type="text" name="birthday" id="id_birthday" required />
<input type="hidden" name="hidden_text" id="id_hidden_text" /></td></tr>"""
)
self.assertHTMLEqual(
p.as_ul(),
"""<li><label for="id_first_name">First name:</label>
<input type="text" name="first_name" id="id_first_name" required /></li>
<li><label for="id_last_name">Last name:</label>
<input type="text" name="last_name" id="id_last_name" required /></li>
<li><label for="id_birthday">Birthday:</label>
<input type="text" name="birthday" id="id_birthday" required />
<input type="hidden" name="hidden_text" id="id_hidden_text" /></li>"""
)
self.assertHTMLEqual(
p.as_p(),
"""<p><label for="id_first_name">First name:</label>
<input type="text" name="first_name" id="id_first_name" required /></p>
<p><label for="id_last_name">Last name:</label>
<input type="text" name="last_name" id="id_last_name" required /></p>
<p><label for="id_birthday">Birthday:</label>
<input type="text" name="birthday" id="id_birthday" required />
<input type="hidden" name="hidden_text" id="id_hidden_text" /></p>"""
)
# If a field with a HiddenInput has errors, the as_table() and as_ul() output
# will include the error message(s) with the text "(Hidden field [fieldname]) "
# prepended. This message is displayed at the top of the output, regardless of
# its field's order in the form.
p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9'}, auto_id=False)
self.assertHTMLEqual(
p.as_table(),
"""<tr><td colspan="2">
<ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field is required.</li></ul></td></tr>
<tr><th>First name:</th><td><input type="text" name="first_name" value="John" required /></td></tr>
<tr><th>Last name:</th><td><input type="text" name="last_name" value="Lennon" required /></td></tr>
<tr><th>Birthday:</th><td><input type="text" name="birthday" value="1940-10-9" required />
<input type="hidden" name="hidden_text" /></td></tr>"""
)
self.assertHTMLEqual(
p.as_ul(),
"""<li><ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field is required.</li></ul></li>
<li>First name: <input type="text" name="first_name" value="John" required /></li>
<li>Last name: <input type="text" name="last_name" value="Lennon" required /></li>
<li>Birthday: <input type="text" name="birthday" value="1940-10-9" required />
<input type="hidden" name="hidden_text" /></li>"""
)
self.assertHTMLEqual(
p.as_p(),
"""<ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field is required.</li></ul>
<p>First name: <input type="text" name="first_name" value="John" required /></p>
<p>Last name: <input type="text" name="last_name" value="Lennon" required /></p>
<p>Birthday: <input type="text" name="birthday" value="1940-10-9" required />
<input type="hidden" name="hidden_text" /></p>"""
)
# A corner case: It's possible for a form to have only HiddenInputs.
class TestForm(Form):
foo = CharField(widget=HiddenInput)
bar = CharField(widget=HiddenInput)
p = TestForm(auto_id=False)
self.assertHTMLEqual(p.as_table(), '<input type="hidden" name="foo" /><input type="hidden" name="bar" />')
self.assertHTMLEqual(p.as_ul(), '<input type="hidden" name="foo" /><input type="hidden" name="bar" />')
self.assertHTMLEqual(p.as_p(), '<input type="hidden" name="foo" /><input type="hidden" name="bar" />')
def test_field_order(self):
# A Form's fields are displayed in the same order in which they were defined.
class TestForm(Form):
field1 = CharField()
field2 = CharField()
field3 = CharField()
field4 = CharField()
field5 = CharField()
field6 = CharField()
field7 = CharField()
field8 = CharField()
field9 = CharField()
field10 = CharField()
field11 = CharField()
field12 = CharField()
field13 = CharField()
field14 = CharField()
p = TestForm(auto_id=False)
self.assertHTMLEqual(p.as_table(), """<tr><th>Field1:</th><td><input type="text" name="field1" required /></td></tr>
<tr><th>Field2:</th><td><input type="text" name="field2" required /></td></tr>
<tr><th>Field3:</th><td><input type="text" name="field3" required /></td></tr>
<tr><th>Field4:</th><td><input type="text" name="field4" required /></td></tr>
<tr><th>Field5:</th><td><input type="text" name="field5" required /></td></tr>
<tr><th>Field6:</th><td><input type="text" name="field6" required /></td></tr>
<tr><th>Field7:</th><td><input type="text" name="field7" required /></td></tr>
<tr><th>Field8:</th><td><input type="text" name="field8" required /></td></tr>
<tr><th>Field9:</th><td><input type="text" name="field9" required /></td></tr>
<tr><th>Field10:</th><td><input type="text" name="field10" required /></td></tr>
<tr><th>Field11:</th><td><input type="text" name="field11" required /></td></tr>
<tr><th>Field12:</th><td><input type="text" name="field12" required /></td></tr>
<tr><th>Field13:</th><td><input type="text" name="field13" required /></td></tr>
<tr><th>Field14:</th><td><input type="text" name="field14" required /></td></tr>""")
def test_explicit_field_order(self):
class TestFormParent(Form):
field1 = CharField()
field2 = CharField()
field4 = CharField()
field5 = CharField()
field6 = CharField()
field_order = ['field6', 'field5', 'field4', 'field2', 'field1']
class TestForm(TestFormParent):
field3 = CharField()
field_order = ['field2', 'field4', 'field3', 'field5', 'field6']
class TestFormRemove(TestForm):
field1 = None
class TestFormMissing(TestForm):
field_order = ['field2', 'field4', 'field3', 'field5', 'field6', 'field1']
field1 = None
class TestFormInit(TestFormParent):
field3 = CharField()
field_order = None
def __init__(self, **kwargs):
super(TestFormInit, self).__init__(**kwargs)
self.order_fields(field_order=TestForm.field_order)
p = TestFormParent()
self.assertEqual(list(p.fields.keys()), TestFormParent.field_order)
p = TestFormRemove()
self.assertEqual(list(p.fields.keys()), TestForm.field_order)
p = TestFormMissing()
self.assertEqual(list(p.fields.keys()), TestForm.field_order)
p = TestForm()
self.assertEqual(list(p.fields.keys()), TestFormMissing.field_order)
p = TestFormInit()
order = list(TestForm.field_order) + ['field1']
self.assertEqual(list(p.fields.keys()), order)
TestForm.field_order = ['unknown']
p = TestForm()
self.assertEqual(list(p.fields.keys()), ['field1', 'field2', 'field4', 'field5', 'field6', 'field3'])
def test_form_html_attributes(self):
# Some Field classes have an effect on the HTML attributes of their associated
# Widget. If you set max_length in a CharField and its associated widget is
# either a TextInput or PasswordInput, then the widget's rendered HTML will
# include the "maxlength" attribute.
class UserRegistration(Form):
username = CharField(max_length=10) # uses TextInput by default
password = CharField(max_length=10, widget=PasswordInput)
realname = CharField(max_length=10, widget=TextInput) # redundantly define widget, just to test
address = CharField() # no max_length defined here
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li>Username: <input type="text" name="username" maxlength="10" required /></li>
<li>Password: <input type="password" name="password" maxlength="10" required /></li>
<li>Realname: <input type="text" name="realname" maxlength="10" required /></li>
<li>Address: <input type="text" name="address" required /></li>"""
)
# If you specify a custom "attrs" that includes the "maxlength" attribute,
# the Field's max_length attribute will override whatever "maxlength" you specify
# in "attrs".
class UserRegistration(Form):
username = CharField(max_length=10, widget=TextInput(attrs={'maxlength': 20}))
password = CharField(max_length=10, widget=PasswordInput)
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li>Username: <input type="text" name="username" maxlength="10" required /></li>
<li>Password: <input type="password" name="password" maxlength="10" required /></li>"""
)
def test_specifying_labels(self):
# You can specify the label for a field by using the 'label' argument to a Field
# class. If you don't specify 'label', Django will use the field name with
# underscores converted to spaces, and the initial letter capitalized.
class UserRegistration(Form):
username = CharField(max_length=10, label='Your username')
password1 = CharField(widget=PasswordInput)
password2 = CharField(widget=PasswordInput, label='Contraseña (de nuevo)')
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li>Your username: <input type="text" name="username" maxlength="10" required /></li>
<li>Password1: <input type="password" name="password1" required /></li>
<li>Contraseña (de nuevo): <input type="password" name="password2" required /></li>"""
)
# Labels for as_* methods will only end in a colon if they don't end in other
# punctuation already.
class Questions(Form):
q1 = CharField(label='The first question')
q2 = CharField(label='What is your name?')
q3 = CharField(label='The answer to life is:')
q4 = CharField(label='Answer this question!')
q5 = CharField(label='The last question. Period.')
self.assertHTMLEqual(
Questions(auto_id=False).as_p(),
"""<p>The first question: <input type="text" name="q1" required /></p>
<p>What is your name? <input type="text" name="q2" required /></p>
<p>The answer to life is: <input type="text" name="q3" required /></p>
<p>Answer this question! <input type="text" name="q4" required /></p>
<p>The last question. Period. <input type="text" name="q5" required /></p>"""
)
self.assertHTMLEqual(
Questions().as_p(),
"""<p><label for="id_q1">The first question:</label> <input type="text" name="q1" id="id_q1" required /></p>
<p><label for="id_q2">What is your name?</label> <input type="text" name="q2" id="id_q2" required /></p>
<p><label for="id_q3">The answer to life is:</label> <input type="text" name="q3" id="id_q3" required /></p>
<p><label for="id_q4">Answer this question!</label> <input type="text" name="q4" id="id_q4" required /></p>
<p><label for="id_q5">The last question. Period.</label> <input type="text" name="q5" id="id_q5" required /></p>"""
)
# If a label is set to the empty string for a field, that field won't get a label.
class UserRegistration(Form):
username = CharField(max_length=10, label='')
password = CharField(widget=PasswordInput)
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(p.as_ul(), """<li> <input type="text" name="username" maxlength="10" required /></li>
<li>Password: <input type="password" name="password" required /></li>""")
p = UserRegistration(auto_id='id_%s')
self.assertHTMLEqual(
p.as_ul(),
"""<li> <input id="id_username" type="text" name="username" maxlength="10" required /></li>
<li><label for="id_password">Password:</label>
<input type="password" name="password" id="id_password" required /></li>"""
)
# If label is None, Django will auto-create the label from the field name. This
# is default behavior.
class UserRegistration(Form):
username = CharField(max_length=10, label=None)
password = CharField(widget=PasswordInput)
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li>Username: <input type="text" name="username" maxlength="10" required /></li>
<li>Password: <input type="password" name="password" required /></li>"""
)
p = UserRegistration(auto_id='id_%s')
self.assertHTMLEqual(
p.as_ul(),
"""<li><label for="id_username">Username:</label>
<input id="id_username" type="text" name="username" maxlength="10" required /></li>
<li><label for="id_password">Password:</label>
<input type="password" name="password" id="id_password" required /></li>"""
)
def test_label_suffix(self):
# You can specify the 'label_suffix' argument to a Form class to modify the
# punctuation symbol used at the end of a label. By default, the colon (:) is
# used, and is only appended to the label if the label doesn't already end with a
# punctuation symbol: ., !, ? or :. If you specify a different suffix, it will
# be appended regardless of the last character of the label.
class FavoriteForm(Form):
color = CharField(label='Favorite color?')
animal = CharField(label='Favorite animal')
answer = CharField(label='Secret answer', label_suffix=' =')
f = FavoriteForm(auto_id=False)
self.assertHTMLEqual(f.as_ul(), """<li>Favorite color? <input type="text" name="color" required /></li>
<li>Favorite animal: <input type="text" name="animal" required /></li>
<li>Secret answer = <input type="text" name="answer" required /></li>""")
f = FavoriteForm(auto_id=False, label_suffix='?')
self.assertHTMLEqual(f.as_ul(), """<li>Favorite color? <input type="text" name="color" required /></li>
<li>Favorite animal? <input type="text" name="animal" required /></li>
<li>Secret answer = <input type="text" name="answer" required /></li>""")
f = FavoriteForm(auto_id=False, label_suffix='')
self.assertHTMLEqual(f.as_ul(), """<li>Favorite color? <input type="text" name="color" required /></li>
<li>Favorite animal <input type="text" name="animal" required /></li>
<li>Secret answer = <input type="text" name="answer" required /></li>""")
f = FavoriteForm(auto_id=False, label_suffix='\u2192')
self.assertHTMLEqual(
f.as_ul(),
'<li>Favorite color? <input type="text" name="color" required /></li>\n'
'<li>Favorite animal\u2192 <input type="text" name="animal" required /></li>\n'
'<li>Secret answer = <input type="text" name="answer" required /></li>'
)
def test_initial_data(self):
# You can specify initial data for a field by using the 'initial' argument to a
# Field class. This initial data is displayed when a Form is rendered with *no*
# data. It is not displayed when a Form is rendered with any data (including an
# empty dictionary). Also, the initial value is *not* used if data for a
# particular required field isn't provided.
class UserRegistration(Form):
username = CharField(max_length=10, initial='django')
password = CharField(widget=PasswordInput)
# Here, we're not submitting any data, so the initial value will be displayed.)
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li>Username: <input type="text" name="username" value="django" maxlength="10" required /></li>
<li>Password: <input type="password" name="password" required /></li>"""
)
# Here, we're submitting data, so the initial value will *not* be displayed.
p = UserRegistration({}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li><ul class="errorlist"><li>This field is required.</li></ul>
Username: <input type="text" name="username" maxlength="10" required /></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" required /></li>"""
)
p = UserRegistration({'username': ''}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li><ul class="errorlist"><li>This field is required.</li></ul>
Username: <input type="text" name="username" maxlength="10" required /></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" required /></li>"""
)
p = UserRegistration({'username': 'foo'}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li>Username: <input type="text" name="username" value="foo" maxlength="10" required /></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" required /></li>"""
)
# An 'initial' value is *not* used as a fallback if data is not provided. In this
# example, we don't provide a value for 'username', and the form raises a
# validation error rather than using the initial value for 'username'.
p = UserRegistration({'password': 'secret'})
self.assertEqual(p.errors['username'], ['This field is required.'])
self.assertFalse(p.is_valid())
def test_dynamic_initial_data(self):
# The previous technique dealt with "hard-coded" initial data, but it's also
# possible to specify initial data after you've already created the Form class
# (i.e., at runtime). Use the 'initial' parameter to the Form constructor. This
# should be a dictionary containing initial values for one or more fields in the
# form, keyed by field name.
class UserRegistration(Form):
username = CharField(max_length=10)
password = CharField(widget=PasswordInput)
# Here, we're not submitting any data, so the initial value will be displayed.)
p = UserRegistration(initial={'username': 'django'}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li>Username: <input type="text" name="username" value="django" maxlength="10" required /></li>
<li>Password: <input type="password" name="password" required /></li>"""
)
p = UserRegistration(initial={'username': 'stephane'}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li>Username: <input type="text" name="username" value="stephane" maxlength="10" required /></li>
<li>Password: <input type="password" name="password" required /></li>"""
)
# The 'initial' parameter is meaningless if you pass data.
p = UserRegistration({}, initial={'username': 'django'}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li><ul class="errorlist"><li>This field is required.</li></ul>
Username: <input type="text" name="username" maxlength="10" required /></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" required /></li>"""
)
p = UserRegistration({'username': ''}, initial={'username': 'django'}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li><ul class="errorlist"><li>This field is required.</li></ul>
Username: <input type="text" name="username" maxlength="10" required /></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" required /></li>"""
)
p = UserRegistration({'username': 'foo'}, initial={'username': 'django'}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" required /></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" required /></li>"""
)
# A dynamic 'initial' value is *not* used as a fallback if data is not provided.
# In this example, we don't provide a value for 'username', and the form raises a
# validation error rather than using the initial value for 'username'.
p = UserRegistration({'password': 'secret'}, initial={'username': 'django'})
self.assertEqual(p.errors['username'], ['This field is required.'])
self.assertFalse(p.is_valid())
# If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(),
# then the latter will get precedence.
class UserRegistration(Form):
username = CharField(max_length=10, initial='django')
password = CharField(widget=PasswordInput)
p = UserRegistration(initial={'username': 'babik'}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li>Username: <input type="text" name="username" value="babik" maxlength="10" required /></li>
<li>Password: <input type="password" name="password" required /></li>"""
)
def test_callable_initial_data(self):
# The previous technique dealt with raw values as initial data, but it's also
# possible to specify callable data.
class UserRegistration(Form):
username = CharField(max_length=10)
password = CharField(widget=PasswordInput)
options = MultipleChoiceField(choices=[('f', 'foo'), ('b', 'bar'), ('w', 'whiz')])
# We need to define functions that get called later.)
def initial_django():
return 'django'
def initial_stephane():
return 'stephane'
def initial_options():
return ['f', 'b']
def initial_other_options():
return ['b', 'w']
# Here, we're not submitting any data, so the initial value will be displayed.)
p = UserRegistration(initial={'username': initial_django, 'options': initial_options}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li>Username: <input type="text" name="username" value="django" maxlength="10" required /></li>
<li>Password: <input type="password" name="password" required /></li>
<li>Options: <select multiple="multiple" name="options" required>
<option value="f" selected>foo</option>
<option value="b" selected>bar</option>
<option value="w">whiz</option>
</select></li>"""
)
# The 'initial' parameter is meaningless if you pass data.
p = UserRegistration({}, initial={'username': initial_django, 'options': initial_options}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li><ul class="errorlist"><li>This field is required.</li></ul>
Username: <input type="text" name="username" maxlength="10" required /></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" required /></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
Options: <select multiple="multiple" name="options" required>
<option value="f">foo</option>
<option value="b">bar</option>
<option value="w">whiz</option>
</select></li>"""
)
p = UserRegistration({'username': ''}, initial={'username': initial_django}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li><ul class="errorlist"><li>This field is required.</li></ul>
Username: <input type="text" name="username" maxlength="10" required /></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" required /></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
Options: <select multiple="multiple" name="options" required>
<option value="f">foo</option>
<option value="b">bar</option>
<option value="w">whiz</option>
</select></li>"""
)
p = UserRegistration(
{'username': 'foo', 'options': ['f', 'b']}, initial={'username': initial_django}, auto_id=False
)
self.assertHTMLEqual(
p.as_ul(),
"""<li>Username: <input type="text" name="username" value="foo" maxlength="10" required /></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" required /></li>
<li>Options: <select multiple="multiple" name="options" required>
<option value="f" selected>foo</option>
<option value="b" selected>bar</option>
<option value="w">whiz</option>
</select></li>"""
)
# A callable 'initial' value is *not* used as a fallback if data is not provided.
# In this example, we don't provide a value for 'username', and the form raises a
# validation error rather than using the initial value for 'username'.
p = UserRegistration({'password': 'secret'}, initial={'username': initial_django, 'options': initial_options})
self.assertEqual(p.errors['username'], ['This field is required.'])
self.assertFalse(p.is_valid())
# If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(),
# then the latter will get precedence.
class UserRegistration(Form):
username = CharField(max_length=10, initial=initial_django)
password = CharField(widget=PasswordInput)
options = MultipleChoiceField(
choices=[('f', 'foo'), ('b', 'bar'), ('w', 'whiz')],
initial=initial_other_options,
)
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li>Username: <input type="text" name="username" value="django" maxlength="10" required /></li>
<li>Password: <input type="password" name="password" required /></li>
<li>Options: <select multiple="multiple" name="options" required>
<option value="f">foo</option>
<option value="b" selected>bar</option>
<option value="w" selected>whiz</option>
</select></li>"""
)
p = UserRegistration(initial={'username': initial_stephane, 'options': initial_options}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li>Username: <input type="text" name="username" value="stephane" maxlength="10" required /></li>
<li>Password: <input type="password" name="password" required /></li>
<li>Options: <select multiple="multiple" name="options" required>
<option value="f" selected>foo</option>
<option value="b" selected>bar</option>
<option value="w">whiz</option>
</select></li>"""
)
def test_get_initial_for_field(self):
class PersonForm(Form):
first_name = CharField(initial='John')
last_name = CharField(initial='Doe')
age = IntegerField()
occupation = CharField(initial=lambda: 'Unknown')
form = PersonForm(initial={'first_name': 'Jane'})
self.assertEqual(form.get_initial_for_field(form.fields['age'], 'age'), None)
self.assertEqual(form.get_initial_for_field(form.fields['last_name'], 'last_name'), 'Doe')
# Form.initial overrides Field.initial.
self.assertEqual(form.get_initial_for_field(form.fields['first_name'], 'first_name'), 'Jane')
# Callables are evaluated.
self.assertEqual(form.get_initial_for_field(form.fields['occupation'], 'occupation'), 'Unknown')
def test_changed_data(self):
class Person(Form):
first_name = CharField(initial='Hans')
last_name = CharField(initial='Greatel')
birthday = DateField(initial=datetime.date(1974, 8, 16))
p = Person(data={'first_name': 'Hans', 'last_name': 'Scrmbl', 'birthday': '1974-08-16'})
self.assertTrue(p.is_valid())
self.assertNotIn('first_name', p.changed_data)
self.assertIn('last_name', p.changed_data)
self.assertNotIn('birthday', p.changed_data)
# A field raising ValidationError is always in changed_data
class PedanticField(forms.Field):
def to_python(self, value):
raise ValidationError('Whatever')
class Person2(Person):
pedantic = PedanticField(initial='whatever', show_hidden_initial=True)
p = Person2(data={
'first_name': 'Hans', 'last_name': 'Scrmbl', 'birthday': '1974-08-16',
'initial-pedantic': 'whatever',
})
self.assertFalse(p.is_valid())
self.assertIn('pedantic', p.changed_data)
def test_boundfield_values(self):
# It's possible to get to the value which would be used for rendering
# the widget for a field by using the BoundField's value method.
class UserRegistration(Form):
username = CharField(max_length=10, initial='djangonaut')
password = CharField(widget=PasswordInput)
unbound = UserRegistration()
bound = UserRegistration({'password': 'foo'})
self.assertIsNone(bound['username'].value())
self.assertEqual(unbound['username'].value(), 'djangonaut')
self.assertEqual(bound['password'].value(), 'foo')
self.assertIsNone(unbound['password'].value())
def test_boundfield_initial_called_once(self):
"""
Multiple calls to BoundField().value() in an unbound form should return
the same result each time (#24391).
"""
class MyForm(Form):
name = CharField(max_length=10, initial=uuid.uuid4)
form = MyForm()
name = form['name']
self.assertEqual(name.value(), name.value())
# BoundField is also cached
self.assertIs(form['name'], name)
def test_boundfield_value_disabled_callable_initial(self):
class PersonForm(Form):
name = CharField(initial=lambda: 'John Doe', disabled=True)
# Without form data.
form = PersonForm()
self.assertEqual(form['name'].value(), 'John Doe')
# With form data. As the field is disabled, the value should not be
# affected by the form data.
form = PersonForm({})
self.assertEqual(form['name'].value(), 'John Doe')
def test_custom_boundfield(self):
class CustomField(CharField):
def get_bound_field(self, form, name):
return (form, name)
class SampleForm(Form):
name = CustomField()
f = SampleForm()
self.assertEqual(f['name'], (f, 'name'))
def test_initial_datetime_values(self):
now = datetime.datetime.now()
# Nix microseconds (since they should be ignored). #22502
now_no_ms = now.replace(microsecond=0)
if now == now_no_ms:
now = now.replace(microsecond=1)
def delayed_now():
return now
def delayed_now_time():
return now.time()
class HiddenInputWithoutMicrosec(HiddenInput):
supports_microseconds = False
class TextInputWithoutMicrosec(TextInput):
supports_microseconds = False
class DateTimeForm(Form):
auto_timestamp = DateTimeField(initial=delayed_now)
auto_time_only = TimeField(initial=delayed_now_time)
supports_microseconds = DateTimeField(initial=delayed_now, widget=TextInput)
hi_default_microsec = DateTimeField(initial=delayed_now, widget=HiddenInput)
hi_without_microsec = DateTimeField(initial=delayed_now, widget=HiddenInputWithoutMicrosec)
ti_without_microsec = DateTimeField(initial=delayed_now, widget=TextInputWithoutMicrosec)
unbound = DateTimeForm()
self.assertEqual(unbound['auto_timestamp'].value(), now_no_ms)
self.assertEqual(unbound['auto_time_only'].value(), now_no_ms.time())
self.assertEqual(unbound['supports_microseconds'].value(), now)
self.assertEqual(unbound['hi_default_microsec'].value(), now)
self.assertEqual(unbound['hi_without_microsec'].value(), now_no_ms)
self.assertEqual(unbound['ti_without_microsec'].value(), now_no_ms)
def test_datetime_clean_initial_callable_disabled(self):
now = datetime.datetime(2006, 10, 25, 14, 30, 45, 123456)
class DateTimeForm(forms.Form):
dt = DateTimeField(initial=lambda: now, disabled=True)
form = DateTimeForm({})
self.assertEqual(form.errors, {})
self.assertEqual(form.cleaned_data, {'dt': now})
def test_datetime_changed_data_callable_with_microseconds(self):
class DateTimeForm(forms.Form):
dt = DateTimeField(initial=lambda: datetime.datetime(2006, 10, 25, 14, 30, 45, 123456), disabled=True)
form = DateTimeForm({'dt': '2006-10-25 14:30:45'})
self.assertEqual(form.changed_data, [])
def test_help_text(self):
# You can specify descriptive text for a field by using the 'help_text' argument)
class UserRegistration(Form):
username = CharField(max_length=10, help_text='e.g., [email protected]')
password = CharField(widget=PasswordInput, help_text='Wählen Sie mit Bedacht.')
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li>Username: <input type="text" name="username" maxlength="10" required />
<span class="helptext">e.g., [email protected]</span></li>
<li>Password: <input type="password" name="password" required />
<span class="helptext">Wählen Sie mit Bedacht.</span></li>"""
)
self.assertHTMLEqual(
p.as_p(),
"""<p>Username: <input type="text" name="username" maxlength="10" required />
<span class="helptext">e.g., [email protected]</span></p>
<p>Password: <input type="password" name="password" required />
<span class="helptext">Wählen Sie mit Bedacht.</span></p>"""
)
self.assertHTMLEqual(
p.as_table(),
"""<tr><th>Username:</th><td><input type="text" name="username" maxlength="10" required /><br />
<span class="helptext">e.g., [email protected]</span></td></tr>
<tr><th>Password:</th><td><input type="password" name="password" required /><br />
<span class="helptext">Wählen Sie mit Bedacht.</span></td></tr>"""
)
# The help text is displayed whether or not data is provided for the form.
p = UserRegistration({'username': 'foo'}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li>Username: <input type="text" name="username" value="foo" maxlength="10" required />
<span class="helptext">e.g., [email protected]</span></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" required />
<span class="helptext">Wählen Sie mit Bedacht.</span></li>"""
)
# help_text is not displayed for hidden fields. It can be used for documentation
# purposes, though.
class UserRegistration(Form):
username = CharField(max_length=10, help_text='e.g., [email protected]')
password = CharField(widget=PasswordInput)
next = CharField(widget=HiddenInput, initial='/', help_text='Redirect destination')
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li>Username: <input type="text" name="username" maxlength="10" required />
<span class="helptext">e.g., [email protected]</span></li>
<li>Password: <input type="password" name="password" required />
<input type="hidden" name="next" value="/" /></li>"""
)
def test_subclassing_forms(self):
# You can subclass a Form to add fields. The resulting form subclass will have
# all of the fields of the parent Form, plus whichever fields you define in the
# subclass.
class Person(Form):
first_name = CharField()
last_name = CharField()
birthday = DateField()
class Musician(Person):
instrument = CharField()
p = Person(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li>First name: <input type="text" name="first_name" required /></li>
<li>Last name: <input type="text" name="last_name" required /></li>
<li>Birthday: <input type="text" name="birthday" required /></li>"""
)
m = Musician(auto_id=False)
self.assertHTMLEqual(
m.as_ul(),
"""<li>First name: <input type="text" name="first_name" required /></li>
<li>Last name: <input type="text" name="last_name" required /></li>
<li>Birthday: <input type="text" name="birthday" required /></li>
<li>Instrument: <input type="text" name="instrument" required /></li>"""
)
# Yes, you can subclass multiple forms. The fields are added in the order in
# which the parent classes are listed.
class Person(Form):
first_name = CharField()
last_name = CharField()
birthday = DateField()
class Instrument(Form):
instrument = CharField()
class Beatle(Person, Instrument):
haircut_type = CharField()
b = Beatle(auto_id=False)
self.assertHTMLEqual(b.as_ul(), """<li>Instrument: <input type="text" name="instrument" required /></li>
<li>First name: <input type="text" name="first_name" required /></li>
<li>Last name: <input type="text" name="last_name" required /></li>
<li>Birthday: <input type="text" name="birthday" required /></li>
<li>Haircut type: <input type="text" name="haircut_type" required /></li>""")
def test_forms_with_prefixes(self):
# Sometimes it's necessary to have multiple forms display on the same HTML page,
# or multiple copies of the same form. We can accomplish this with form prefixes.
# Pass the keyword argument 'prefix' to the Form constructor to use this feature.
# This value will be prepended to each HTML form field name. One way to think
# about this is "namespaces for HTML forms". Notice that in the data argument,
# each field's key has the prefix, in this case 'person1', prepended to the
# actual field name.
class Person(Form):
first_name = CharField()
last_name = CharField()
birthday = DateField()
data = {
'person1-first_name': 'John',
'person1-last_name': 'Lennon',
'person1-birthday': '1940-10-9'
}
p = Person(data, prefix='person1')
self.assertHTMLEqual(
p.as_ul(),
"""<li><label for="id_person1-first_name">First name:</label>
<input type="text" name="person1-first_name" value="John" id="id_person1-first_name" required /></li>
<li><label for="id_person1-last_name">Last name:</label>
<input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" required /></li>
<li><label for="id_person1-birthday">Birthday:</label>
<input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" required /></li>"""
)
self.assertHTMLEqual(
str(p['first_name']),
'<input type="text" name="person1-first_name" value="John" id="id_person1-first_name" required />'
)
self.assertHTMLEqual(
str(p['last_name']),
'<input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" required />'
)
self.assertHTMLEqual(
str(p['birthday']),
'<input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" required />'
)
self.assertEqual(p.errors, {})
self.assertTrue(p.is_valid())
self.assertEqual(p.cleaned_data['first_name'], 'John')
self.assertEqual(p.cleaned_data['last_name'], 'Lennon')
self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9))
# Let's try submitting some bad data to make sure form.errors and field.errors
# work as expected.
data = {
'person1-first_name': '',
'person1-last_name': '',
'person1-birthday': ''
}
p = Person(data, prefix='person1')
self.assertEqual(p.errors['first_name'], ['This field is required.'])
self.assertEqual(p.errors['last_name'], ['This field is required.'])
self.assertEqual(p.errors['birthday'], ['This field is required.'])
self.assertEqual(p['first_name'].errors, ['This field is required.'])
# Accessing a nonexistent field.
with self.assertRaises(KeyError):
p['person1-first_name'].errors
# In this example, the data doesn't have a prefix, but the form requires it, so
# the form doesn't "see" the fields.
data = {
'first_name': 'John',
'last_name': 'Lennon',
'birthday': '1940-10-9'
}
p = Person(data, prefix='person1')
self.assertEqual(p.errors['first_name'], ['This field is required.'])
self.assertEqual(p.errors['last_name'], ['This field is required.'])
self.assertEqual(p.errors['birthday'], ['This field is required.'])
# With prefixes, a single data dictionary can hold data for multiple instances
# of the same form.
data = {
'person1-first_name': 'John',
'person1-last_name': 'Lennon',
'person1-birthday': '1940-10-9',
'person2-first_name': 'Jim',
'person2-last_name': 'Morrison',
'person2-birthday': '1943-12-8'
}
p1 = Person(data, prefix='person1')
self.assertTrue(p1.is_valid())
self.assertEqual(p1.cleaned_data['first_name'], 'John')
self.assertEqual(p1.cleaned_data['last_name'], 'Lennon')
self.assertEqual(p1.cleaned_data['birthday'], datetime.date(1940, 10, 9))
p2 = Person(data, prefix='person2')
self.assertTrue(p2.is_valid())
self.assertEqual(p2.cleaned_data['first_name'], 'Jim')
self.assertEqual(p2.cleaned_data['last_name'], 'Morrison')
self.assertEqual(p2.cleaned_data['birthday'], datetime.date(1943, 12, 8))
# By default, forms append a hyphen between the prefix and the field name, but a
# form can alter that behavior by implementing the add_prefix() method. This
# method takes a field name and returns the prefixed field, according to
# self.prefix.
class Person(Form):
first_name = CharField()
last_name = CharField()
birthday = DateField()
def add_prefix(self, field_name):
return '%s-prefix-%s' % (self.prefix, field_name) if self.prefix else field_name
p = Person(prefix='foo')
self.assertHTMLEqual(
p.as_ul(),
"""<li><label for="id_foo-prefix-first_name">First name:</label>
<input type="text" name="foo-prefix-first_name" id="id_foo-prefix-first_name" required /></li>
<li><label for="id_foo-prefix-last_name">Last name:</label>
<input type="text" name="foo-prefix-last_name" id="id_foo-prefix-last_name" required /></li>
<li><label for="id_foo-prefix-birthday">Birthday:</label>
<input type="text" name="foo-prefix-birthday" id="id_foo-prefix-birthday" required /></li>"""
)
data = {
'foo-prefix-first_name': 'John',
'foo-prefix-last_name': 'Lennon',
'foo-prefix-birthday': '1940-10-9'
}
p = Person(data, prefix='foo')
self.assertTrue(p.is_valid())
self.assertEqual(p.cleaned_data['first_name'], 'John')
self.assertEqual(p.cleaned_data['last_name'], 'Lennon')
self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9))
def test_class_prefix(self):
# Prefix can be also specified at the class level.
class Person(Form):
first_name = CharField()
prefix = 'foo'
p = Person()
self.assertEqual(p.prefix, 'foo')
p = Person(prefix='bar')
self.assertEqual(p.prefix, 'bar')
def test_forms_with_null_boolean(self):
# NullBooleanField is a bit of a special case because its presentation (widget)
# is different than its data. This is handled transparently, though.
class Person(Form):
name = CharField()
is_cool = NullBooleanField()
p = Person({'name': 'Joe'}, auto_id=False)
self.assertHTMLEqual(str(p['is_cool']), """<select name="is_cool">
<option value="1" selected>Unknown</option>
<option value="2">Yes</option>
<option value="3">No</option>
</select>""")
p = Person({'name': 'Joe', 'is_cool': '1'}, auto_id=False)
self.assertHTMLEqual(str(p['is_cool']), """<select name="is_cool">
<option value="1" selected>Unknown</option>
<option value="2">Yes</option>
<option value="3">No</option>
</select>""")
p = Person({'name': 'Joe', 'is_cool': '2'}, auto_id=False)
self.assertHTMLEqual(str(p['is_cool']), """<select name="is_cool">
<option value="1">Unknown</option>
<option value="2" selected>Yes</option>
<option value="3">No</option>
</select>""")
p = Person({'name': 'Joe', 'is_cool': '3'}, auto_id=False)
self.assertHTMLEqual(str(p['is_cool']), """<select name="is_cool">
<option value="1">Unknown</option>
<option value="2">Yes</option>
<option value="3" selected>No</option>
</select>""")
p = Person({'name': 'Joe', 'is_cool': True}, auto_id=False)
self.assertHTMLEqual(str(p['is_cool']), """<select name="is_cool">
<option value="1">Unknown</option>
<option value="2" selected>Yes</option>
<option value="3">No</option>
</select>""")
p = Person({'name': 'Joe', 'is_cool': False}, auto_id=False)
self.assertHTMLEqual(str(p['is_cool']), """<select name="is_cool">
<option value="1">Unknown</option>
<option value="2">Yes</option>
<option value="3" selected>No</option>
</select>""")
def test_forms_with_file_fields(self):
# FileFields are a special case because they take their data from the request.FILES,
# not request.POST.
class FileForm(Form):
file1 = FileField()
f = FileForm(auto_id=False)
self.assertHTMLEqual(
f.as_table(),
'<tr><th>File1:</th><td><input type="file" name="file1" required /></td></tr>',
)
f = FileForm(data={}, files={}, auto_id=False)
self.assertHTMLEqual(
f.as_table(),
'<tr><th>File1:</th><td>'
'<ul class="errorlist"><li>This field is required.</li></ul>'
'<input type="file" name="file1" required /></td></tr>'
)
f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', b'')}, auto_id=False)
self.assertHTMLEqual(
f.as_table(),
'<tr><th>File1:</th><td>'
'<ul class="errorlist"><li>The submitted file is empty.</li></ul>'
'<input type="file" name="file1" required /></td></tr>'
)
f = FileForm(data={}, files={'file1': 'something that is not a file'}, auto_id=False)
self.assertHTMLEqual(
f.as_table(),
'<tr><th>File1:</th><td>'
'<ul class="errorlist"><li>No file was submitted. Check the '
'encoding type on the form.</li></ul>'
'<input type="file" name="file1" required /></td></tr>'
)
f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', b'some content')}, auto_id=False)
self.assertHTMLEqual(
f.as_table(),
'<tr><th>File1:</th><td><input type="file" name="file1" required /></td></tr>',
)
self.assertTrue(f.is_valid())
file1 = SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))
f = FileForm(data={}, files={'file1': file1}, auto_id=False)
self.assertHTMLEqual(
f.as_table(),
'<tr><th>File1:</th><td><input type="file" name="file1" required /></td></tr>',
)
# A required file field with initial data should not contain the
# required HTML attribute. The file input is left blank by the user to
# keep the existing, initial value.
f = FileForm(initial={'file1': 'resume.txt'}, auto_id=False)
self.assertHTMLEqual(
f.as_table(),
'<tr><th>File1:</th><td><input type="file" name="file1" /></td></tr>',
)
def test_filefield_initial_callable(self):
class FileForm(forms.Form):
file1 = forms.FileField(initial=lambda: 'resume.txt')
f = FileForm({})
self.assertEqual(f.errors, {})
self.assertEqual(f.cleaned_data['file1'], 'resume.txt')
def test_basic_processing_in_view(self):
class UserRegistration(Form):
username = CharField(max_length=10)
password1 = CharField(widget=PasswordInput)
password2 = CharField(widget=PasswordInput)
def clean(self):
if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and
self.cleaned_data['password1'] != self.cleaned_data['password2']):
raise ValidationError('Please make sure your passwords match.')
return self.cleaned_data
def my_function(method, post_data):
if method == 'POST':
form = UserRegistration(post_data, auto_id=False)
else:
form = UserRegistration(auto_id=False)
if form.is_valid():
return 'VALID: %r' % sorted(form.cleaned_data.items())
t = Template(
'<form action="" method="post">\n'
'<table>\n{{ form }}\n</table>\n<input type="submit" required />\n</form>'
)
return t.render(Context({'form': form}))
# Case 1: GET (an empty form, with no errors).)
self.assertHTMLEqual(my_function('GET', {}), """<form action="" method="post">
<table>
<tr><th>Username:</th><td><input type="text" name="username" maxlength="10" required /></td></tr>
<tr><th>Password1:</th><td><input type="password" name="password1" required /></td></tr>
<tr><th>Password2:</th><td><input type="password" name="password2" required /></td></tr>
</table>
<input type="submit" required />
</form>""")
# Case 2: POST with erroneous data (a redisplayed form, with errors).)
self.assertHTMLEqual(
my_function('POST', {'username': 'this-is-a-long-username', 'password1': 'foo', 'password2': 'bar'}),
"""<form action="" method="post">
<table>
<tr><td colspan="2"><ul class="errorlist nonfield"><li>Please make sure your passwords match.</li></ul></td></tr>
<tr><th>Username:</th><td><ul class="errorlist">
<li>Ensure this value has at most 10 characters (it has 23).</li></ul>
<input type="text" name="username" value="this-is-a-long-username" maxlength="10" required /></td></tr>
<tr><th>Password1:</th><td><input type="password" name="password1" required /></td></tr>
<tr><th>Password2:</th><td><input type="password" name="password2" required /></td></tr>
</table>
<input type="submit" required />
</form>"""
)
# Case 3: POST with valid data (the success message).)
self.assertEqual(
my_function('POST', {'username': 'adrian', 'password1': 'secret', 'password2': 'secret'}),
"VALID: [('password1', 'secret'), ('password2', 'secret'), ('username', 'adrian')]"
)
def test_templates_with_forms(self):
class UserRegistration(Form):
username = CharField(max_length=10, help_text="Good luck picking a username that doesn't already exist.")
password1 = CharField(widget=PasswordInput)
password2 = CharField(widget=PasswordInput)
def clean(self):
if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and
self.cleaned_data['password1'] != self.cleaned_data['password2']):
raise ValidationError('Please make sure your passwords match.')
return self.cleaned_data
# You have full flexibility in displaying form fields in a template. Just pass a
# Form instance to the template, and use "dot" access to refer to individual
# fields. Note, however, that this flexibility comes with the responsibility of
# displaying all the errors, including any that might not be associated with a
# particular field.
t = Template('''<form action="">
{{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p>
{{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p>
{{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p>
<input type="submit" required />
</form>''')
self.assertHTMLEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form action="">
<p><label>Your username: <input type="text" name="username" maxlength="10" required /></label></p>
<p><label>Password: <input type="password" name="password1" required /></label></p>
<p><label>Password (again): <input type="password" name="password2" required /></label></p>
<input type="submit" required />
</form>""")
self.assertHTMLEqual(
t.render(Context({'form': UserRegistration({'username': 'django'}, auto_id=False)})),
"""<form action="">
<p><label>Your username: <input type="text" name="username" value="django" maxlength="10" required /></label></p>
<ul class="errorlist"><li>This field is required.</li></ul><p>
<label>Password: <input type="password" name="password1" required /></label></p>
<ul class="errorlist"><li>This field is required.</li></ul>
<p><label>Password (again): <input type="password" name="password2" required /></label></p>
<input type="submit" required />
</form>"""
)
# Use form.[field].label to output a field's label. You can specify the label for
# a field by using the 'label' argument to a Field class. If you don't specify
# 'label', Django will use the field name with underscores converted to spaces,
# and the initial letter capitalized.
t = Template('''<form action="">
<p><label>{{ form.username.label }}: {{ form.username }}</label></p>
<p><label>{{ form.password1.label }}: {{ form.password1 }}</label></p>
<p><label>{{ form.password2.label }}: {{ form.password2 }}</label></p>
<input type="submit" required />
</form>''')
self.assertHTMLEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form action="">
<p><label>Username: <input type="text" name="username" maxlength="10" required /></label></p>
<p><label>Password1: <input type="password" name="password1" required /></label></p>
<p><label>Password2: <input type="password" name="password2" required /></label></p>
<input type="submit" required />
</form>""")
# User form.[field].label_tag to output a field's label with a <label> tag
# wrapped around it, but *only* if the given field has an "id" attribute.
# Recall from above that passing the "auto_id" argument to a Form gives each
# field an "id" attribute.
t = Template('''<form action="">
<p>{{ form.username.label_tag }} {{ form.username }}</p>
<p>{{ form.password1.label_tag }} {{ form.password1 }}</p>
<p>{{ form.password2.label_tag }} {{ form.password2 }}</p>
<input type="submit" required />
</form>''')
self.assertHTMLEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form action="">
<p>Username: <input type="text" name="username" maxlength="10" required /></p>
<p>Password1: <input type="password" name="password1" required /></p>
<p>Password2: <input type="password" name="password2" required /></p>
<input type="submit" required />
</form>""")
self.assertHTMLEqual(t.render(Context({'form': UserRegistration(auto_id='id_%s')})), """<form action="">
<p><label for="id_username">Username:</label>
<input id="id_username" type="text" name="username" maxlength="10" required /></p>
<p><label for="id_password1">Password1:</label>
<input type="password" name="password1" id="id_password1" required /></p>
<p><label for="id_password2">Password2:</label>
<input type="password" name="password2" id="id_password2" required /></p>
<input type="submit" required />
</form>""")
# User form.[field].help_text to output a field's help text. If the given field
# does not have help text, nothing will be output.
t = Template('''<form action="">
<p>{{ form.username.label_tag }} {{ form.username }}<br />{{ form.username.help_text }}</p>
<p>{{ form.password1.label_tag }} {{ form.password1 }}</p>
<p>{{ form.password2.label_tag }} {{ form.password2 }}</p>
<input type="submit" required />
</form>''')
self.assertHTMLEqual(
t.render(Context({'form': UserRegistration(auto_id=False)})),
"""<form action="">
<p>Username: <input type="text" name="username" maxlength="10" required /><br />
Good luck picking a username that doesn't already exist.</p>
<p>Password1: <input type="password" name="password1" required /></p>
<p>Password2: <input type="password" name="password2" required /></p>
<input type="submit" required />
</form>"""
)
self.assertEqual(
Template('{{ form.password1.help_text }}').render(Context({'form': UserRegistration(auto_id=False)})),
''
)
# To display the errors that aren't associated with a particular field -- e.g.,
# the errors caused by Form.clean() -- use {{ form.non_field_errors }} in the
# template. If used on its own, it is displayed as a <ul> (or an empty string, if
# the list of errors is empty). You can also use it in {% if %} statements.
t = Template('''<form action="">
{{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p>
{{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p>
{{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p>
<input type="submit" required />
</form>''')
self.assertHTMLEqual(
t.render(Context({
'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
})),
"""<form action="">
<p><label>Your username: <input type="text" name="username" value="django" maxlength="10" required /></label></p>
<p><label>Password: <input type="password" name="password1" required /></label></p>
<p><label>Password (again): <input type="password" name="password2" required /></label></p>
<input type="submit" required />
</form>"""
)
t = Template('''<form action="">
{{ form.non_field_errors }}
{{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p>
{{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p>
{{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p>
<input type="submit" required />
</form>''')
self.assertHTMLEqual(
t.render(Context({
'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
})),
"""<form action="">
<ul class="errorlist nonfield"><li>Please make sure your passwords match.</li></ul>
<p><label>Your username: <input type="text" name="username" value="django" maxlength="10" required /></label></p>
<p><label>Password: <input type="password" name="password1" required /></label></p>
<p><label>Password (again): <input type="password" name="password2" required /></label></p>
<input type="submit" required />
</form>"""
)
def test_empty_permitted(self):
# Sometimes (pretty much in formsets) we want to allow a form to pass validation
# if it is completely empty. We can accomplish this by using the empty_permitted
# argument to a form constructor.
class SongForm(Form):
artist = CharField()
name = CharField()
# First let's show what happens id empty_permitted=False (the default):
data = {'artist': '', 'song': ''}
form = SongForm(data, empty_permitted=False)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors, {'name': ['This field is required.'], 'artist': ['This field is required.']})
self.assertEqual(form.cleaned_data, {})
# Now let's show what happens when empty_permitted=True and the form is empty.
form = SongForm(data, empty_permitted=True)
self.assertTrue(form.is_valid())
self.assertEqual(form.errors, {})
self.assertEqual(form.cleaned_data, {})
# But if we fill in data for one of the fields, the form is no longer empty and
# the whole thing must pass validation.
data = {'artist': 'The Doors', 'song': ''}
form = SongForm(data, empty_permitted=False)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors, {'name': ['This field is required.']})
self.assertEqual(form.cleaned_data, {'artist': 'The Doors'})
# If a field is not given in the data then None is returned for its data. Lets
# make sure that when checking for empty_permitted that None is treated
# accordingly.
data = {'artist': None, 'song': ''}
form = SongForm(data, empty_permitted=True)
self.assertTrue(form.is_valid())
# However, we *really* need to be sure we are checking for None as any data in
# initial that returns False on a boolean call needs to be treated literally.
class PriceForm(Form):
amount = FloatField()
qty = IntegerField()
data = {'amount': '0.0', 'qty': ''}
form = PriceForm(data, initial={'amount': 0.0}, empty_permitted=True)
self.assertTrue(form.is_valid())
def test_extracting_hidden_and_visible(self):
class SongForm(Form):
token = CharField(widget=HiddenInput)
artist = CharField()
name = CharField()
form = SongForm()
self.assertEqual([f.name for f in form.hidden_fields()], ['token'])
self.assertEqual([f.name for f in form.visible_fields()], ['artist', 'name'])
def test_hidden_initial_gets_id(self):
class MyForm(Form):
field1 = CharField(max_length=50, show_hidden_initial=True)
self.assertHTMLEqual(
MyForm().as_table(),
'<tr><th><label for="id_field1">Field1:</label></th>'
'<td><input id="id_field1" type="text" name="field1" maxlength="50" required />'
'<input type="hidden" name="initial-field1" id="initial-id_field1" /></td></tr>'
)
def test_error_html_required_html_classes(self):
class Person(Form):
name = CharField()
is_cool = NullBooleanField()
email = EmailField(required=False)
age = IntegerField()
p = Person({})
p.error_css_class = 'error'
p.required_css_class = 'required'
self.assertHTMLEqual(
p.as_ul(),
"""<li class="required error"><ul class="errorlist"><li>This field is required.</li></ul>
<label class="required" for="id_name">Name:</label> <input type="text" name="name" id="id_name" required /></li>
<li class="required"><label class="required" for="id_is_cool">Is cool:</label>
<select name="is_cool" id="id_is_cool">
<option value="1" selected>Unknown</option>
<option value="2">Yes</option>
<option value="3">No</option>
</select></li>
<li><label for="id_email">Email:</label> <input type="email" name="email" id="id_email" /></li>
<li class="required error"><ul class="errorlist"><li>This field is required.</li></ul>
<label class="required" for="id_age">Age:</label> <input type="number" name="age" id="id_age" required /></li>"""
)
self.assertHTMLEqual(
p.as_p(),
"""<ul class="errorlist"><li>This field is required.</li></ul>
<p class="required error"><label class="required" for="id_name">Name:</label>
<input type="text" name="name" id="id_name" required /></p>
<p class="required"><label class="required" for="id_is_cool">Is cool:</label>
<select name="is_cool" id="id_is_cool">
<option value="1" selected>Unknown</option>
<option value="2">Yes</option>
<option value="3">No</option>
</select></p>
<p><label for="id_email">Email:</label> <input type="email" name="email" id="id_email" /></p>
<ul class="errorlist"><li>This field is required.</li></ul>
<p class="required error"><label class="required" for="id_age">Age:</label>
<input type="number" name="age" id="id_age" required /></p>"""
)
self.assertHTMLEqual(
p.as_table(),
"""<tr class="required error">
<th><label class="required" for="id_name">Name:</label></th>
<td><ul class="errorlist"><li>This field is required.</li></ul>
<input type="text" name="name" id="id_name" required /></td></tr>
<tr class="required"><th><label class="required" for="id_is_cool">Is cool:</label></th>
<td><select name="is_cool" id="id_is_cool">
<option value="1" selected>Unknown</option>
<option value="2">Yes</option>
<option value="3">No</option>
</select></td></tr>
<tr><th><label for="id_email">Email:</label></th><td>
<input type="email" name="email" id="id_email" /></td></tr>
<tr class="required error"><th><label class="required" for="id_age">Age:</label></th>
<td><ul class="errorlist"><li>This field is required.</li></ul>
<input type="number" name="age" id="id_age" required /></td></tr>"""
)
def test_label_has_required_css_class(self):
"""
#17922 - required_css_class is added to the label_tag() of required fields.
"""
class SomeForm(Form):
required_css_class = 'required'
field = CharField(max_length=10)
field2 = IntegerField(required=False)
f = SomeForm({'field': 'test'})
self.assertHTMLEqual(f['field'].label_tag(), '<label for="id_field" class="required">Field:</label>')
self.assertHTMLEqual(
f['field'].label_tag(attrs={'class': 'foo'}),
'<label for="id_field" class="foo required">Field:</label>'
)
self.assertHTMLEqual(f['field2'].label_tag(), '<label for="id_field2">Field2:</label>')
def test_label_split_datetime_not_displayed(self):
class EventForm(Form):
happened_at = SplitDateTimeField(widget=SplitHiddenDateTimeWidget)
form = EventForm()
self.assertHTMLEqual(
form.as_ul(),
'<input type="hidden" name="happened_at_0" id="id_happened_at_0" />'
'<input type="hidden" name="happened_at_1" id="id_happened_at_1" />'
)
def test_multivalue_field_validation(self):
def bad_names(value):
if value == 'bad value':
raise ValidationError('bad value not allowed')
class NameField(MultiValueField):
def __init__(self, fields=(), *args, **kwargs):
fields = (CharField(label='First name', max_length=10),
CharField(label='Last name', max_length=10))
super(NameField, self).__init__(fields=fields, *args, **kwargs)
def compress(self, data_list):
return ' '.join(data_list)
class NameForm(Form):
name = NameField(validators=[bad_names])
form = NameForm(data={'name': ['bad', 'value']})
form.full_clean()
self.assertFalse(form.is_valid())
self.assertEqual(form.errors, {'name': ['bad value not allowed']})
form = NameForm(data={'name': ['should be overly', 'long for the field names']})
self.assertFalse(form.is_valid())
self.assertEqual(form.errors, {'name': ['Ensure this value has at most 10 characters (it has 16).',
'Ensure this value has at most 10 characters (it has 24).']})
form = NameForm(data={'name': ['fname', 'lname']})
self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data, {'name': 'fname lname'})
def test_multivalue_deep_copy(self):
"""
#19298 -- MultiValueField needs to override the default as it needs
to deep-copy subfields:
"""
class ChoicesField(MultiValueField):
def __init__(self, fields=(), *args, **kwargs):
fields = (
ChoiceField(label='Rank', choices=((1, 1), (2, 2))),
CharField(label='Name', max_length=10),
)
super(ChoicesField, self).__init__(fields=fields, *args, **kwargs)
field = ChoicesField()
field2 = copy.deepcopy(field)
self.assertIsInstance(field2, ChoicesField)
self.assertIsNot(field2.fields, field.fields)
self.assertIsNot(field2.fields[0].choices, field.fields[0].choices)
def test_multivalue_initial_data(self):
"""
#23674 -- invalid initial data should not break form.changed_data()
"""
class DateAgeField(MultiValueField):
def __init__(self, fields=(), *args, **kwargs):
fields = (DateField(label="Date"), IntegerField(label="Age"))
super(DateAgeField, self).__init__(fields=fields, *args, **kwargs)
class DateAgeForm(Form):
date_age = DateAgeField()
data = {"date_age": ["1998-12-06", 16]}
form = DateAgeForm(data, initial={"date_age": ["200-10-10", 14]})
self.assertTrue(form.has_changed())
def test_multivalue_optional_subfields(self):
class PhoneField(MultiValueField):
def __init__(self, *args, **kwargs):
fields = (
CharField(label='Country Code', validators=[
RegexValidator(r'^\+[0-9]{1,2}$', message='Enter a valid country code.')]),
CharField(label='Phone Number'),
CharField(label='Extension', error_messages={'incomplete': 'Enter an extension.'}),
CharField(label='Label', required=False, help_text='E.g. home, work.'),
)
super(PhoneField, self).__init__(fields, *args, **kwargs)
def compress(self, data_list):
if data_list:
return '%s.%s ext. %s (label: %s)' % tuple(data_list)
return None
# An empty value for any field will raise a `required` error on a
# required `MultiValueField`.
f = PhoneField()
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean('')
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean([])
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(['+61'])
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(['+61', '287654321', '123'])
self.assertEqual('+61.287654321 ext. 123 (label: Home)', f.clean(['+61', '287654321', '123', 'Home']))
with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
f.clean(['61', '287654321', '123', 'Home'])
# Empty values for fields will NOT raise a `required` error on an
# optional `MultiValueField`
f = PhoneField(required=False)
self.assertIsNone(f.clean(''))
self.assertIsNone(f.clean(None))
self.assertIsNone(f.clean([]))
self.assertEqual('+61. ext. (label: )', f.clean(['+61']))
self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123']))
self.assertEqual('+61.287654321 ext. 123 (label: Home)', f.clean(['+61', '287654321', '123', 'Home']))
with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
f.clean(['61', '287654321', '123', 'Home'])
# For a required `MultiValueField` with `require_all_fields=False`, a
# `required` error will only be raised if all fields are empty. Fields
# can individually be required or optional. An empty value for any
# required field will raise an `incomplete` error.
f = PhoneField(require_all_fields=False)
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean('')
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean([])
with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"):
f.clean(['+61'])
self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123']))
with self.assertRaisesMessage(ValidationError, "'Enter a complete value.', 'Enter an extension.'"):
f.clean(['', '', '', 'Home'])
with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
f.clean(['61', '287654321', '123', 'Home'])
# For an optional `MultiValueField` with `require_all_fields=False`, we
# don't get any `required` error but we still get `incomplete` errors.
f = PhoneField(required=False, require_all_fields=False)
self.assertIsNone(f.clean(''))
self.assertIsNone(f.clean(None))
self.assertIsNone(f.clean([]))
with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"):
f.clean(['+61'])
self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123']))
with self.assertRaisesMessage(ValidationError, "'Enter a complete value.', 'Enter an extension.'"):
f.clean(['', '', '', 'Home'])
with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
f.clean(['61', '287654321', '123', 'Home'])
def test_custom_empty_values(self):
"""
Form fields can customize what is considered as an empty value
for themselves (#19997).
"""
class CustomJSONField(CharField):
empty_values = [None, '']
def to_python(self, value):
# Fake json.loads
if value == '{}':
return {}
return super(CustomJSONField, self).to_python(value)
class JSONForm(forms.Form):
json = CustomJSONField()
form = JSONForm(data={'json': '{}'})
form.full_clean()
self.assertEqual(form.cleaned_data, {'json': {}})
def test_boundfield_label_tag(self):
class SomeForm(Form):
field = CharField()
boundfield = SomeForm()['field']
testcases = [ # (args, kwargs, expected)
# without anything: just print the <label>
((), {}, '<label for="id_field">Field:</label>'),
# passing just one argument: overrides the field's label
(('custom',), {}, '<label for="id_field">custom:</label>'),
# the overridden label is escaped
(('custom&',), {}, '<label for="id_field">custom&:</label>'),
((mark_safe('custom&'),), {}, '<label for="id_field">custom&:</label>'),
# Passing attrs to add extra attributes on the <label>
((), {'attrs': {'class': 'pretty'}}, '<label for="id_field" class="pretty">Field:</label>')
]
for args, kwargs, expected in testcases:
self.assertHTMLEqual(boundfield.label_tag(*args, **kwargs), expected)
def test_boundfield_label_tag_no_id(self):
"""
If a widget has no id, label_tag just returns the text with no
surrounding <label>.
"""
class SomeForm(Form):
field = CharField()
boundfield = SomeForm(auto_id='')['field']
self.assertHTMLEqual(boundfield.label_tag(), 'Field:')
self.assertHTMLEqual(boundfield.label_tag('Custom&'), 'Custom&:')
def test_boundfield_label_tag_custom_widget_id_for_label(self):
class CustomIdForLabelTextInput(TextInput):
def id_for_label(self, id):
return 'custom_' + id
class EmptyIdForLabelTextInput(TextInput):
def id_for_label(self, id):
return None
class SomeForm(Form):
custom = CharField(widget=CustomIdForLabelTextInput)
empty = CharField(widget=EmptyIdForLabelTextInput)
form = SomeForm()
self.assertHTMLEqual(form['custom'].label_tag(), '<label for="custom_id_custom">Custom:</label>')
self.assertHTMLEqual(form['empty'].label_tag(), '<label>Empty:</label>')
def test_boundfield_empty_label(self):
class SomeForm(Form):
field = CharField(label='')
boundfield = SomeForm()['field']
self.assertHTMLEqual(boundfield.label_tag(), '<label for="id_field"></label>')
def test_boundfield_id_for_label(self):
class SomeForm(Form):
field = CharField(label='')
self.assertEqual(SomeForm()['field'].id_for_label, 'id_field')
def test_boundfield_id_for_label_override_by_attrs(self):
"""
If an id is provided in `Widget.attrs`, it overrides the generated ID,
unless it is `None`.
"""
class SomeForm(Form):
field = CharField(widget=TextInput(attrs={'id': 'myCustomID'}))
field_none = CharField(widget=TextInput(attrs={'id': None}))
form = SomeForm()
self.assertEqual(form['field'].id_for_label, 'myCustomID')
self.assertEqual(form['field_none'].id_for_label, 'id_field_none')
def test_label_tag_override(self):
"""
BoundField label_suffix (if provided) overrides Form label_suffix
"""
class SomeForm(Form):
field = CharField()
boundfield = SomeForm(label_suffix='!')['field']
self.assertHTMLEqual(boundfield.label_tag(label_suffix='$'), '<label for="id_field">Field$</label>')
def test_field_name(self):
"""#5749 - `field_name` may be used as a key in _html_output()."""
class SomeForm(Form):
some_field = CharField()
def as_p(self):
return self._html_output(
normal_row='<p id="p_%(field_name)s"></p>',
error_row='%s',
row_ender='</p>',
help_text_html=' %s',
errors_on_separate_row=True,
)
form = SomeForm()
self.assertHTMLEqual(form.as_p(), '<p id="p_some_field"></p>')
def test_field_without_css_classes(self):
"""
`css_classes` may be used as a key in _html_output() (empty classes).
"""
class SomeForm(Form):
some_field = CharField()
def as_p(self):
return self._html_output(
normal_row='<p class="%(css_classes)s"></p>',
error_row='%s',
row_ender='</p>',
help_text_html=' %s',
errors_on_separate_row=True,
)
form = SomeForm()
self.assertHTMLEqual(form.as_p(), '<p class=""></p>')
def test_field_with_css_class(self):
"""
`css_classes` may be used as a key in _html_output() (class comes
from required_css_class in this case).
"""
class SomeForm(Form):
some_field = CharField()
required_css_class = 'foo'
def as_p(self):
return self._html_output(
normal_row='<p class="%(css_classes)s"></p>',
error_row='%s',
row_ender='</p>',
help_text_html=' %s',
errors_on_separate_row=True,
)
form = SomeForm()
self.assertHTMLEqual(form.as_p(), '<p class="foo"></p>')
def test_field_name_with_hidden_input(self):
"""
BaseForm._html_output() should merge all the hidden input fields and
put them in the last row.
"""
class SomeForm(Form):
hidden1 = CharField(widget=HiddenInput)
custom = CharField()
hidden2 = CharField(widget=HiddenInput)
def as_p(self):
return self._html_output(
normal_row='<p%(html_class_attr)s>%(field)s %(field_name)s</p>',
error_row='%s',
row_ender='</p>',
help_text_html=' %s',
errors_on_separate_row=True,
)
form = SomeForm()
self.assertHTMLEqual(
form.as_p(),
'<p><input id="id_custom" name="custom" type="text" required /> custom'
'<input id="id_hidden1" name="hidden1" type="hidden" />'
'<input id="id_hidden2" name="hidden2" type="hidden" /></p>'
)
def test_field_name_with_hidden_input_and_non_matching_row_ender(self):
"""
BaseForm._html_output() should merge all the hidden input fields and
put them in the last row ended with the specific row ender.
"""
class SomeForm(Form):
hidden1 = CharField(widget=HiddenInput)
custom = CharField()
hidden2 = CharField(widget=HiddenInput)
def as_p(self):
return self._html_output(
normal_row='<p%(html_class_attr)s>%(field)s %(field_name)s</p>',
error_row='%s',
row_ender='<hr /><hr />',
help_text_html=' %s',
errors_on_separate_row=True
)
form = SomeForm()
self.assertHTMLEqual(
form.as_p(),
'<p><input id="id_custom" name="custom" type="text" required /> custom</p>\n'
'<input id="id_hidden1" name="hidden1" type="hidden" />'
'<input id="id_hidden2" name="hidden2" type="hidden" /><hr /><hr />'
)
def test_error_dict(self):
class MyForm(Form):
foo = CharField()
bar = CharField()
def clean(self):
raise ValidationError('Non-field error.', code='secret', params={'a': 1, 'b': 2})
form = MyForm({})
self.assertIs(form.is_valid(), False)
errors = form.errors.as_text()
control = [
'* foo\n * This field is required.',
'* bar\n * This field is required.',
'* __all__\n * Non-field error.',
]
for error in control:
self.assertIn(error, errors)
errors = form.errors.as_ul()
control = [
'<li>foo<ul class="errorlist"><li>This field is required.</li></ul></li>',
'<li>bar<ul class="errorlist"><li>This field is required.</li></ul></li>',
'<li>__all__<ul class="errorlist nonfield"><li>Non-field error.</li></ul></li>',
]
for error in control:
self.assertInHTML(error, errors)
errors = json.loads(form.errors.as_json())
control = {
'foo': [{'code': 'required', 'message': 'This field is required.'}],
'bar': [{'code': 'required', 'message': 'This field is required.'}],
'__all__': [{'code': 'secret', 'message': 'Non-field error.'}]
}
self.assertEqual(errors, control)
def test_error_dict_as_json_escape_html(self):
"""#21962 - adding html escape flag to ErrorDict"""
class MyForm(Form):
foo = CharField()
bar = CharField()
def clean(self):
raise ValidationError('<p>Non-field error.</p>',
code='secret',
params={'a': 1, 'b': 2})
control = {
'foo': [{'code': 'required', 'message': 'This field is required.'}],
'bar': [{'code': 'required', 'message': 'This field is required.'}],
'__all__': [{'code': 'secret', 'message': '<p>Non-field error.</p>'}]
}
form = MyForm({})
self.assertFalse(form.is_valid())
errors = json.loads(form.errors.as_json())
self.assertEqual(errors, control)
errors = json.loads(form.errors.as_json(escape_html=True))
control['__all__'][0]['message'] = '<p>Non-field error.</p>'
self.assertEqual(errors, control)
def test_error_list(self):
e = ErrorList()
e.append('Foo')
e.append(ValidationError('Foo%(bar)s', code='foobar', params={'bar': 'bar'}))
self.assertIsInstance(e, list)
self.assertIn('Foo', e)
self.assertIn('Foo', forms.ValidationError(e))
self.assertEqual(
e.as_text(),
'* Foo\n* Foobar'
)
self.assertEqual(
e.as_ul(),
'<ul class="errorlist"><li>Foo</li><li>Foobar</li></ul>'
)
self.assertEqual(
json.loads(e.as_json()),
[{"message": "Foo", "code": ""}, {"message": "Foobar", "code": "foobar"}]
)
def test_error_list_class_not_specified(self):
e = ErrorList()
e.append('Foo')
e.append(ValidationError('Foo%(bar)s', code='foobar', params={'bar': 'bar'}))
self.assertEqual(
e.as_ul(),
'<ul class="errorlist"><li>Foo</li><li>Foobar</li></ul>'
)
def test_error_list_class_has_one_class_specified(self):
e = ErrorList(error_class='foobar-error-class')
e.append('Foo')
e.append(ValidationError('Foo%(bar)s', code='foobar', params={'bar': 'bar'}))
self.assertEqual(
e.as_ul(),
'<ul class="errorlist foobar-error-class"><li>Foo</li><li>Foobar</li></ul>'
)
def test_error_list_with_hidden_field_errors_has_correct_class(self):
class Person(Form):
first_name = CharField()
last_name = CharField(widget=HiddenInput)
p = Person({'first_name': 'John'})
self.assertHTMLEqual(
p.as_ul(),
"""<li><ul class="errorlist nonfield">
<li>(Hidden field last_name) This field is required.</li></ul></li><li>
<label for="id_first_name">First name:</label>
<input id="id_first_name" name="first_name" type="text" value="John" required />
<input id="id_last_name" name="last_name" type="hidden" /></li>"""
)
self.assertHTMLEqual(
p.as_p(),
"""<ul class="errorlist nonfield"><li>(Hidden field last_name) This field is required.</li></ul>
<p><label for="id_first_name">First name:</label>
<input id="id_first_name" name="first_name" type="text" value="John" required />
<input id="id_last_name" name="last_name" type="hidden" /></p>"""
)
self.assertHTMLEqual(
p.as_table(),
"""<tr><td colspan="2"><ul class="errorlist nonfield">
<li>(Hidden field last_name) This field is required.</li></ul></td></tr>
<tr><th><label for="id_first_name">First name:</label></th><td>
<input id="id_first_name" name="first_name" type="text" value="John" required />
<input id="id_last_name" name="last_name" type="hidden" /></td></tr>"""
)
def test_error_list_with_non_field_errors_has_correct_class(self):
class Person(Form):
first_name = CharField()
last_name = CharField()
def clean(self):
raise ValidationError('Generic validation error')
p = Person({'first_name': 'John', 'last_name': 'Lennon'})
self.assertHTMLEqual(
str(p.non_field_errors()),
'<ul class="errorlist nonfield"><li>Generic validation error</li></ul>'
)
self.assertHTMLEqual(
p.as_ul(),
"""<li>
<ul class="errorlist nonfield"><li>Generic validation error</li></ul></li>
<li><label for="id_first_name">First name:</label>
<input id="id_first_name" name="first_name" type="text" value="John" required /></li>
<li><label for="id_last_name">Last name:</label>
<input id="id_last_name" name="last_name" type="text" value="Lennon" required /></li>"""
)
self.assertHTMLEqual(
p.non_field_errors().as_text(),
'* Generic validation error'
)
self.assertHTMLEqual(
p.as_p(),
"""<ul class="errorlist nonfield"><li>Generic validation error</li></ul>
<p><label for="id_first_name">First name:</label>
<input id="id_first_name" name="first_name" type="text" value="John" required /></p>
<p><label for="id_last_name">Last name:</label>
<input id="id_last_name" name="last_name" type="text" value="Lennon" required /></p>"""
)
self.assertHTMLEqual(
p.as_table(),
"""<tr><td colspan="2"><ul class="errorlist nonfield"><li>Generic validation error</li></ul></td></tr>
<tr><th><label for="id_first_name">First name:</label></th><td>
<input id="id_first_name" name="first_name" type="text" value="John" required /></td></tr>
<tr><th><label for="id_last_name">Last name:</label></th><td>
<input id="id_last_name" name="last_name" type="text" value="Lennon" required /></td></tr>"""
)
def test_errorlist_override(self):
class DivErrorList(ErrorList):
def __str__(self):
return self.as_divs()
def as_divs(self):
if not self:
return ''
return '<div class="errorlist">%s</div>' % ''.join(
'<div class="error">%s</div>' % e for e in self)
class CommentForm(Form):
name = CharField(max_length=50, required=False)
email = EmailField()
comment = CharField()
data = dict(email='invalid')
f = CommentForm(data, auto_id=False, error_class=DivErrorList)
self.assertHTMLEqual(f.as_p(), """<p>Name: <input type="text" name="name" maxlength="50" /></p>
<div class="errorlist"><div class="error">Enter a valid email address.</div></div>
<p>Email: <input type="email" name="email" value="invalid" required /></p>
<div class="errorlist"><div class="error">This field is required.</div></div>
<p>Comment: <input type="text" name="comment" required /></p>""")
def test_baseform_repr(self):
"""
BaseForm.__repr__() should contain some basic information about the
form.
"""
p = Person()
self.assertEqual(repr(p), "<Person bound=False, valid=Unknown, fields=(first_name;last_name;birthday)>")
p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9'})
self.assertEqual(repr(p), "<Person bound=True, valid=Unknown, fields=(first_name;last_name;birthday)>")
p.is_valid()
self.assertEqual(repr(p), "<Person bound=True, valid=True, fields=(first_name;last_name;birthday)>")
p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': 'fakedate'})
p.is_valid()
self.assertEqual(repr(p), "<Person bound=True, valid=False, fields=(first_name;last_name;birthday)>")
def test_baseform_repr_dont_trigger_validation(self):
"""
BaseForm.__repr__() shouldn't trigger the form validation.
"""
p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': 'fakedate'})
repr(p)
with self.assertRaises(AttributeError):
p.cleaned_data
self.assertFalse(p.is_valid())
self.assertEqual(p.cleaned_data, {'first_name': 'John', 'last_name': 'Lennon'})
def test_accessing_clean(self):
class UserForm(Form):
username = CharField(max_length=10)
password = CharField(widget=PasswordInput)
def clean(self):
data = self.cleaned_data
if not self.errors:
data['username'] = data['username'].lower()
return data
f = UserForm({'username': 'SirRobin', 'password': 'blue'})
self.assertTrue(f.is_valid())
self.assertEqual(f.cleaned_data['username'], 'sirrobin')
def test_changing_cleaned_data_nothing_returned(self):
class UserForm(Form):
username = CharField(max_length=10)
password = CharField(widget=PasswordInput)
def clean(self):
self.cleaned_data['username'] = self.cleaned_data['username'].lower()
# don't return anything
f = UserForm({'username': 'SirRobin', 'password': 'blue'})
self.assertTrue(f.is_valid())
self.assertEqual(f.cleaned_data['username'], 'sirrobin')
def test_changing_cleaned_data_in_clean(self):
class UserForm(Form):
username = CharField(max_length=10)
password = CharField(widget=PasswordInput)
def clean(self):
data = self.cleaned_data
# Return a different dict. We have not changed self.cleaned_data.
return {
'username': data['username'].lower(),
'password': 'this_is_not_a_secret',
}
f = UserForm({'username': 'SirRobin', 'password': 'blue'})
self.assertTrue(f.is_valid())
self.assertEqual(f.cleaned_data['username'], 'sirrobin')
def test_multipart_encoded_form(self):
class FormWithoutFile(Form):
username = CharField()
class FormWithFile(Form):
username = CharField()
file = FileField()
class FormWithImage(Form):
image = ImageField()
self.assertFalse(FormWithoutFile().is_multipart())
self.assertTrue(FormWithFile().is_multipart())
self.assertTrue(FormWithImage().is_multipart())
def test_html_safe(self):
class SimpleForm(Form):
username = CharField()
form = SimpleForm()
self.assertTrue(hasattr(SimpleForm, '__html__'))
self.assertEqual(str(form), form.__html__())
self.assertTrue(hasattr(form['username'], '__html__'))
self.assertEqual(str(form['username']), form['username'].__html__())
def test_use_required_attribute_true(self):
class MyForm(Form):
use_required_attribute = True
f1 = CharField(max_length=30)
f2 = CharField(max_length=30, required=False)
f3 = CharField(widget=Textarea)
f4 = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')])
form = MyForm()
self.assertHTMLEqual(
form.as_p(),
'<p><label for="id_f1">F1:</label> <input id="id_f1" maxlength="30" name="f1" type="text" required /></p>'
'<p><label for="id_f2">F2:</label> <input id="id_f2" maxlength="30" name="f2" type="text" /></p>'
'<p><label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" rows="10" required>'
'</textarea></p>'
'<p><label for="id_f4">F4:</label> <select id="id_f4" name="f4">'
'<option value="P">Python</option>'
'<option value="J">Java</option>'
'</select></p>',
)
self.assertHTMLEqual(
form.as_ul(),
'<li><label for="id_f1">F1:</label> '
'<input id="id_f1" maxlength="30" name="f1" type="text" required /></li>'
'<li><label for="id_f2">F2:</label> <input id="id_f2" maxlength="30" name="f2" type="text" /></li>'
'<li><label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" rows="10" required>'
'</textarea></li>'
'<li><label for="id_f4">F4:</label> <select id="id_f4" name="f4">'
'<option value="P">Python</option>'
'<option value="J">Java</option>'
'</select></li>',
)
self.assertHTMLEqual(
form.as_table(),
'<tr><th><label for="id_f1">F1:</label></th>'
'<td><input id="id_f1" maxlength="30" name="f1" type="text" required /></td></tr>'
'<tr><th><label for="id_f2">F2:</label></th>'
'<td><input id="id_f2" maxlength="30" name="f2" type="text" /></td></tr>'
'<tr><th><label for="id_f3">F3:</label></th>'
'<td><textarea cols="40" id="id_f3" name="f3" rows="10" required>'
'</textarea></td></tr>'
'<tr><th><label for="id_f4">F4:</label></th><td><select id="id_f4" name="f4">'
'<option value="P">Python</option>'
'<option value="J">Java</option>'
'</select></td></tr>',
)
def test_use_required_attribute_false(self):
class MyForm(Form):
use_required_attribute = False
f1 = CharField(max_length=30)
f2 = CharField(max_length=30, required=False)
f3 = CharField(widget=Textarea)
f4 = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')])
form = MyForm()
self.assertHTMLEqual(
form.as_p(),
'<p><label for="id_f1">F1:</label> <input id="id_f1" maxlength="30" name="f1" type="text" /></p>'
'<p><label for="id_f2">F2:</label> <input id="id_f2" maxlength="30" name="f2" type="text" /></p>'
'<p><label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" rows="10">'
'</textarea></p>'
'<p><label for="id_f4">F4:</label> <select id="id_f4" name="f4">'
'<option value="P">Python</option>'
'<option value="J">Java</option>'
'</select></p>',
)
self.assertHTMLEqual(
form.as_ul(),
'<li><label for="id_f1">F1:</label> <input id="id_f1" maxlength="30" name="f1" type="text" /></li>'
'<li><label for="id_f2">F2:</label> <input id="id_f2" maxlength="30" name="f2" type="text" /></li>'
'<li><label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" rows="10">'
'</textarea></li>'
'<li><label for="id_f4">F4:</label> <select id="id_f4" name="f4">'
'<option value="P">Python</option>'
'<option value="J">Java</option>'
'</select></li>',
)
self.assertHTMLEqual(
form.as_table(),
'<tr><th><label for="id_f1">F1:</label></th>'
'<td><input id="id_f1" maxlength="30" name="f1" type="text" /></td></tr>'
'<tr><th><label for="id_f2">F2:</label></th>'
'<td><input id="id_f2" maxlength="30" name="f2" type="text" /></td></tr>'
'<tr><th><label for="id_f3">F3:</label></th><td><textarea cols="40" id="id_f3" name="f3" rows="10">'
'</textarea></td></tr>'
'<tr><th><label for="id_f4">F4:</label></th><td><select id="id_f4" name="f4">'
'<option value="P">Python</option>'
'<option value="J">Java</option>'
'</select></td></tr>',
)
def test_only_hidden_fields(self):
# A form with *only* hidden fields that has errors is going to be very unusual.
class HiddenForm(Form):
data = IntegerField(widget=HiddenInput)
f = HiddenForm({})
self.assertHTMLEqual(
f.as_p(),
'<ul class="errorlist nonfield">'
'<li>(Hidden field data) This field is required.</li></ul>\n<p> '
'<input type="hidden" name="data" id="id_data" /></p>'
)
self.assertHTMLEqual(
f.as_table(),
'<tr><td colspan="2"><ul class="errorlist nonfield">'
'<li>(Hidden field data) This field is required.</li></ul>'
'<input type="hidden" name="data" id="id_data" /></td></tr>'
)
def test_field_named_data(self):
class DataForm(Form):
data = CharField(max_length=10)
f = DataForm({'data': 'xyzzy'})
self.assertTrue(f.is_valid())
self.assertEqual(f.cleaned_data, {'data': 'xyzzy'})
class CustomRenderer(DjangoTemplates):
pass
class RendererTests(SimpleTestCase):
def test_default(self):
form = Form()
self.assertEqual(form.renderer, get_default_renderer())
def test_kwarg_instance(self):
custom = CustomRenderer()
form = Form(renderer=custom)
self.assertEqual(form.renderer, custom)
def test_kwarg_class(self):
custom = CustomRenderer()
form = Form(renderer=custom)
self.assertEqual(form.renderer, custom)
def test_attribute_instance(self):
class CustomForm(Form):
default_renderer = DjangoTemplates()
form = CustomForm()
self.assertEqual(form.renderer, CustomForm.default_renderer)
def test_attribute_class(self):
class CustomForm(Form):
default_renderer = CustomRenderer
form = CustomForm()
self.assertTrue(isinstance(form.renderer, CustomForm.default_renderer))
def test_attribute_override(self):
class CustomForm(Form):
default_renderer = DjangoTemplates()
custom = CustomRenderer()
form = CustomForm(renderer=custom)
self.assertEqual(form.renderer, custom)
|
#!/usr/bin/python
#-*- encoding: utf-8 -*-
# This file is part of the Pameng,
# Pameng website: http://www.cnpameng.com/,
# Sina weibo: http://weibo.com/cnpameng.
# This file is part of WeiboMsgBackup.
# Copyright (C) 2013 Pameng.
# Pameng <[email protected]>, 2013.
# WeiboMsgBackup is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
# WeiboMsgBackup is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with WeiboMsgBackup; see the file COPYING3. If not see
# <http://www.gnu.org/licenses/>.
import urllib2
import cookielib
import time
import datetime
import json
import re
import random
import urllib
import base64
import StringIO
import gzip
from model.log4py import Log4py
import sys
from model import syscontext
import os
import wx
import rsa
from rsa import transform
logger = Log4py().getLogger("run")
class LoginSinaCom():
def __init__(self, **kwargs):
#INIT cookie load object
self.cj = cookielib.LWPCookieJar()
self.cookie_support = urllib2.HTTPCookieProcessor(self.cj)
self.opener = urllib2.build_opener(self.cookie_support, urllib2.HTTPHandler)
urllib2.install_opener(self.opener)
self.soft_path = kwargs.get("soft_path", "")
self.cookiefile = os.path.join(self.soft_path, "cookie.dat")
self.proxyip = kwargs.get("proxyip", "")
self.pcid = ""
self.servertime = ""
self.nonce = ""
self.pubkey = ''
self.rsakv = ''
def __get_millitime(self):
""" get mill times """
pre = str(int(time.time()))
pos = str(datetime.datetime.now().microsecond)[:3]
p = pre + pos
return p
def get_servertime(self, login_un):
""" get sine server time """
url = 'http://login.sina.com.cn/sso/prelogin.php?entry=account&callback=sinaSSOController.preloginCallBack&su=&rsakt=mod&client=ssologin.js(v1.4.2)&_=%s' % self.__get_millitime()
result = {}
servertime = None
nonce = None
headers = self.__get_headers()
headers['Host'] = 'login.sina.com.cn'
headers['Accept'] = '*/*'
headers['Referer'] = 'http://weibo.com/'
del headers['Accept-encoding']
for i in range(3): #@UnusedVariable
req = self.pack_request(url, headers)
data = urllib2.urlopen(req).read()
p = re.compile('\((.*)\)')
try:
json_data = p.search(data).group(1)
data = json.loads(json_data)
servertime = str(data['servertime'])
nonce = data['nonce']
result["servertime"] = servertime
result["nonce"] = nonce
result["rsakv"] = str(data['rsakv'])
result["pubkey"] = str(data['pubkey'])
self.pcid = str(data['pcid'])
break
except:
msg = u'Get severtime error!'
logger.error(msg)
continue
return result
def get_global_id(self):
""" get sina session id """
time = self.__get_millitime()
url = "http://beacon.sina.com.cn/a.gif"
headers = self.__get_headers()
headers['Host'] = 'beacon.sina.com.cn'
headers['Accept'] = 'image/png,image/*;q=0.8,*/*;q=0.5'
headers['Referer'] = 'http://weibo.com/'
req = self.pack_request(url, headers)
urllib2.urlopen(req)
def get_random_nonce(self, range_num=6):
""" get random nonce key """
nonce = ""
for i in range(range_num): #@UnusedVariable
nonce += random.choice('QWERTYUIOPASDFGHJKLZXCVBNM1234567890')
return nonce
def dec2hex(self, string_num):
base = [str(x) for x in range(10)] + [chr(x) for x in range(ord('A'), ord('A')+6)]
num = int(string_num)
mid = []
while True:
if num == 0: break
num, rem = divmod(num, 16)
mid.append(base[rem])
return ''.join([str(x) for x in mid[::-1]])
def get_pwd(self, pwd, servertime, nonce):
#pwd1 = hashlib.sha1(pwd).hexdigest()
#pwd2 = hashlib.sha1(pwd1).hexdigest()
#pwd3_ = pwd2 + servertime + nonce
#pwd3 = hashlib.sha1(pwd3_).hexdigest()
#return pwd3
p = int(self.pubkey, 16)
pub_key = rsa.PublicKey(p, int('10001', 16))
pwd = '%s\t%s\n%s' % (servertime, nonce, pwd)
pwd = (self.dec2hex(transform.bytes2int(rsa.encrypt(pwd.encode('utf-8'), pub_key))))
return pwd
def get_user(self, username):
username_ = urllib.quote(username)
username = base64.encodestring(username_)[:-1]
return username
def save_verifycode(self, url):
try:
cookiestr = ""
for cookie in self.cj.as_lwp_str(True, True).split("\n"):
cookie = cookie.split(";")[0]
cookie = cookie.replace("\"", "").replace("Set-Cookie3: ", " ").strip() + ";"
cookiestr += cookie
headers = {'Host': 'login.sina.com.cn',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; rv:13.0) Gecko/20100101 Firefox/13.0.1',
'Accept': 'image/png,image/*;q=0.8,*/*;q=0.5',
#'Accept-encoding': 'gzip, deflate',
'Accept-Language': 'zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3',
'Connection': 'keep-alive',
'Referer' : 'http://weibo.com/',
'Cookie' : cookiestr,
}
req = self.pack_request(url, headers)
response = urllib2.urlopen(req, timeout=10)
content = response.read()
f = open(os.path.join(self.soft_path, "pin.png"), "wb")
f.write(content)
f.flush()
f.close()
except:
logger.error(u"save verify code error.")
def login(self, login_un, login_pw):
loginFalg = False
try:
try:
stObj = self.get_servertime(login_un)
self.servertime = stObj.get("servertime")
self.nonce = stObj.get("nonce")
self.pubkey = stObj.get("pubkey")
self.rsakv = stObj.get("rsakv")
except:
return False
#获取会话ID
self.get_global_id()
loginHtml = self.do_login(login_un, login_pw)
loginHtml = loginHtml.replace('"', "'")
#print loginHtml
#p = re.compile('location\.replace\(\'(.*?)\'\)')
try:
p = re.compile('location\.replace\(\'(.*?)\'\)')
login_url = p.search(loginHtml).group(1)
#print login_url
if "retcode=0" in loginHtml:
return self.redo_login(login_url)
#是否需要手动输入验证码
if syscontext.VERIFY_INPUT_FLAG:
logger.info(u"Allow user type verify code.")
pass
else:
logger.error(u"Enable input verify code,return failure.")
return False
#需要验证码,你妹
if "retcode=5" in loginHtml:
logger.error(u"password or account error.")
return False
if "retcode=4040" in loginHtml:
logger.error(u"do login too much times.")
return False
#这次是真的要验证码:code 4049
if "retcode=4049" in login_url:
for i in range(3):
logger.info(u"need verify code.")
verifycode_url = 'http://login.sina.com.cn/cgi/pin.php?r=%s&s=0&p=%s' % (random.randint(20000000,99999999), self.pcid)
self.save_verifycode(verifycode_url)
syscontext.VERIFY_CODE = ""
codeimg = os.path.join(os.path.join(syscontext.userentity.get("path", ""), syscontext.FILE_PATH_DEFAULT), "pin.png")
logger.info(u"verify code img path:%s." % codeimg)
try:
window = syscontext.MAIN_WINDOW
genthread = syscontext.MAIN_GENTHREAD
wx.CallAfter(window.EnableMainWin, False)
wx.CallAfter(window.ShowVerifyCode, codeimg)
#print "before self.acquire"
genthread.lock.acquire()
genthread.lockcondition.wait()
genthread.lock.release()
#print "after self.release"
#veroifyFrame = VerifyCodeFrame(window, filename=codeimg)
#veroifyFrame.Center()
#veroifyFrame.Show(True)
#app.MainLoop()
except:
s = sys.exc_info()
msg = (u"app error %s happened on line %d" % (s[1], s[2].tb_lineno))
logger.error(msg)
door = syscontext.VERIFY_CODE
logger.error(u"get input verify code:%s" % door)
#附加验证码再次登录
self.nonce = self.get_random_nonce()
loginHtml = self.do_login(login_un, login_pw, door=door)
loginHtml = loginHtml.replace('"', "'")
p = re.compile('location\.replace\(\'(.*?)\'\)')
if p.search(loginHtml):
login_url = p.search(loginHtml).group(1)
return self.redo_login(login_url)
else:
if "retcode=2070" in loginHtml:
#小LANG吃翔吧
logger.error(u"verify code:%s error." % door)
continue
else:
break
except:
s = sys.exc_info()
msg = (u"do login %s happened on line %d" % (s[1], s[2].tb_lineno))
logger.error(msg)
loginFalg = False
except Exception:
s = sys.exc_info()
msg = (u"login: %s happened on line %d" % (s[1], s[2].tb_lineno))
logger.error(msg)
return loginFalg
def redo_login(self, login_url):
try:
headers = self.__get_headers()
headers['Referer'] = 'http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.2)'
req = self.pack_request(login_url, headers)
urllib2.urlopen(req)
#self.cj.clear(name="Apache", domain=".sina.com.cn", path="/")
#self.cj.clear(name="SINAGLOBAL", domain=".sina.com.cn", path="/")
self.cj.save(self.cookiefile, True, True)
msg = u'login success'
logger.info(msg)
loginFalg = True
except:
s = sys.exc_info()
msg = (u"redo_login %s happened on line %d" % (s[1], s[2].tb_lineno))
logger.error(msg)
loginFalg = False
return loginFalg
def do_login(self, login_un, login_pw, door=""):
try:
loginFalg = False #登录状态
username = login_un #微博账号
pwd = login_pw #微博密码
url = 'http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.2)'
#POST DATA for login
postdata = {
# 'entry': 'weibo',
# 'gateway': '1',
# 'from': '',
# 'savestate': '7',
# 'userticket': '1',
# 'ssosimplelogin': '1',
# 'vsnf': '1',
# 'vsnval': '',
# 'su': '',
# 'service': 'miniblog',
# 'servertime': '',
# 'nonce': '',
# 'pwencode': 'wsse',
# 'sp': '',
# 'encoding': 'UTF-8',
# 'url': 'http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack',
# 'returntype': 'META'
'entry': 'weibo',
'gateway': '1',
'from': '',
'savestate': '7',
'userticket': '1',
'pagerefer' : '',
'ssosimplelogin': '1',
'vsnf': '1',
'vsnval': '',
'service': 'miniblog',
'pwencode': 'rsa2',
'rsakv' : self.rsakv,
'encoding': 'UTF-8',
'url': 'http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack',
'returntype': 'META',
'prelt' : '26',
}
postdata['servertime'] = self.servertime
postdata['nonce'] = self.nonce
postdata['su'] = self.get_user(username)
postdata['sp'] = self.get_pwd(pwd, self.servertime, self.nonce).lower()
#当需要验证码登录的时候
if door:
postdata['pcid'] = self.pcid
postdata['door'] = door.lower()
#headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; rv:13.0) Gecko/20100101 Firefox/13.0.1'}
headers = {'Host': 'login.sina.com.cn',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; rv:17.0) Gecko/20100101 Firefox/17.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-encoding': 'gzip, deflate',
'Accept-Language': 'zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3',
#'Accept-Charset': 'GB2312,utf-8;q=0.7,*;q=0.7',
'Connection': 'keep-alive',
'Referer' : 'http://weibo.com/',
'Content-Type': 'application/x-www-form-urlencoded',
}
req = self.pack_request(url, headers, postdata)
result = urllib2.urlopen(req)
#cj.save(cookiefile, True, True)
if result.info().get("Content-Encoding") == 'gzip':
text = self.gzip_data(result.read())
else:
text = result.read()
return text
except:
s = sys.exc_info()
msg = (u"do_login: %s happened on line %d" % (s[1], s[2].tb_lineno))
logger.error(msg)
return loginFalg
def check_cookie(self, un, pw, softPath):
loginFalg = True
self.cookiefile = os.path.join(softPath, "cookie.dat")
if os.path.exists(self.cookiefile):
msg = u"cookie dat exist."
logger.info(msg)
if "Set-Cookie" not in open(self.cookiefile,'r').read():
msg = u"but does not contain a valid cookie."
logger.info(msg)
loginFalg = self.login(un, pw)
else:
loginFalg = self.login(un, pw)
if loginFalg:
return self.valid_cookie()
else:
return False
'''
#当HTML参数为空时
#需要在login调用之后执行
#返回cookiestr or Flase
'''
def valid_cookie(self, html=""):
#http://weibo.com/signup/signup
html = str(html)
if not html:
headers = self.__get_headers()
html = self.get_content_head(url="http://weibo.com/kaifulee", headers=headers)
if not html:
msg = u"need relogin."
logger.error(msg)
self.clear_cookiedat(self.cookiefile) #clear cookie file
return False
html = str(html)
html = html.replace('"', "'")
if "sinaSSOController" in html:
p = re.compile('location\.replace\(\'(.*?)\'\)')
#p = re.compile('location\.replace\("(.*?)"\)')
try:
login_url = p.search(html).group(1)
headers = self.__get_headers()
headers['Host'] = 'account.weibo.com'
req = self.pack_request(url=login_url, headers=headers)
result = urllib2.urlopen(req)
#self.cj.clear(name="Apache", domain=".sina.com.cn", path="/")
#self.cj.clear(name="SINAGLOBAL", domain=".sina.com.cn", path="/")
self.cj.save(self.cookiefile, True, True)
if result.info().get("Content-Encoding") == 'gzip':
html = self.gzipData(result.read())
else:
html = result.read()
except:
msg = u"relogin failure."
logger.error(msg)
self.clear_cookiedat(self.cookiefile)
return False
if "违反了新浪微博的安全检测规则" in html:
msg = u"cookie failure."
logger.error(msg)
self.clear_cookiedat(self.cookiefile) #clear cookie file
return False
elif "您的帐号存在异常" in html and "解除限制" in html:
msg = u"账号被限制."
logger.error(msg)
self.clear_cookiedat(self.cookiefile)#clear cookie file
return False
elif "$CONFIG['islogin'] = '0'" in html:
msg = u"登录失败."
logger.error(msg)
self.clear_cookiedat(self.cookiefile)#clear cookie file
return False
elif "$CONFIG['islogin']='1'" in html:
#print "cookie success."
msg = u"cookie success."
logger.info(msg)
#print cj.as_lwp_str(True, True).replace("\n", ";").replace("Set-Cookie3: ", " ").strip()
#cokiestr = ""
#for cookie in self.cj.as_lwp_str(True, True).split("\n"):
# if "Apache" in cookie or "SINAGLOBAL" in cookie:
# continue
# cookie = cookie.split(";")[0]
# cookie = cookie.replace("\"", "").replace("Set-Cookie3: ", " ").strip() + ";"
# cokiestr += cookie
self.cj.save(self.cookiefile, True, True)
return True
else:
msg = u"登录失败."
self.clear_cookiedat(self.cookiefile) #clear cookie file
logger.error(msg)
return False
def get_content_head(self, url, headers={}, data=None):
content = ""
try:
if os.path.exists(self.cookiefile):
self.cj.revert(self.cookiefile, True, True)
self.cookie_support = urllib2.HTTPCookieProcessor(self.cj)
self.opener = urllib2.build_opener(self.cookie_support, urllib2.HTTPHandler)
urllib2.install_opener(self.opener)
else:
return ""
req = self.pack_request(url=url, headers=headers, data=data)
#response = urllib2.urlopen(req, timeout=15)
response = self.opener.open(req, timeout=10)
if response.info().get("Content-Encoding") == 'gzip':
content = self.gzip_data(response.read())
else:
content = response.read()
#time.sleep(0.1*random.randint(10, 20))
except urllib2.HTTPError, e:
return e.code
except:
s=sys.exc_info()
msg = u"get_content Error %s happened on line %d" % (s[1], s[2].tb_lineno)
logger.error(msg)
content = ""
return content
def get_content_cookie(self, url, headers={}, data=None):
content = ""
try:
req = self.pack_request(url=url, headers=headers, data=data)
opener = urllib2.build_opener(self.cookie_support)
response = opener.open(req, timeout=10)
if response.info().get("Content-Encoding") == 'gzip':
content = self.gzip_data(response.read())
else:
content = response.read()
#time.sleep(0.1*random.randint(10, 20))
except:
s=sys.exc_info()
msg = u"get_content Error %s happened on line %d" % (s[1], s[2].tb_lineno)
logger.error(msg)
content = ""
return content
def clear_cookiedat(self, datpath):
try:
os.remove(datpath)
#f = file(datpath, 'w')
#f.truncate()
#f.close()
except:
pass
def pack_request(self, url="", headers={}, data=None):
if data:
headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
data = urllib.urlencode(data)
req = urllib2.Request(
url=url,
data=data,
headers=headers
)
proxyip = self.proxyip
if proxyip and "127.0.0.1" not in proxyip:
if proxyip.startswith("http"):
proxyip = proxyip.replace("http://", "")
req.set_proxy(proxyip, "http")
return req
def gzip_data(self, spider_data):
""" get data from gzip """
if 0 == len(spider_data):
return spider_data
spiderDataStream = StringIO.StringIO(spider_data)
spider_data = gzip.GzipFile(fileobj=spiderDataStream).read()
return spider_data
def __get_headers(self):
headers = {'Host': 'weibo.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; rv:13.0) Gecko/20100101 Firefox/13.0.1',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-encoding': 'gzip, deflate',
'Accept-Language': 'zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3',
'Connection': 'keep-alive',
}
return headers
|
import glob
import cPickle
import os
import argparse
import numpy as np
import pynet.datasets.preprocessor as procs
def generate_specs(ext, spec_dir, specnames, datafiles, dtype, feature_size,
output_dir, preprocessor, output_dtype, model):
assert dtype in ['f4', 'f8']
print 'opening model.. ' + model
with open(model) as m:
model = cPickle.load(m)
specnames_ls = glob.glob(specnames)
datafiles_ls = glob.glob(datafiles)
specnames_ls.sort()
datafiles_ls.sort()
spec_files = "%s/*.%s"%(spec_dir, ext)
files = glob.glob(spec_files)
size = len(files)
assert size > 0, 'empty mgc folder'
print '..number of mgc files %d'%size
data = []
count = 0
for datafile, specname in zip(datafiles_ls, specnames_ls):
print 'datafile: ' + datafile
print 'specname: ' + specname
assert datafile.split('_data_')[-1] == specname.split('_specnames_')[-1]
specname_fin = open(specname)
specname_data = np.load(specname_fin)
data = []
mgc_frame_num = []
for name, num_frames in specname_data:
basename = name.split('.')[0]
f = '%s/%s.%s'%(spec_dir, basename, ext)
print '..opening ' + f
count += 1
clip = np.fromfile(f, dtype='<%s'%dtype, count=-1)
assert clip.shape[0] % feature_size == 0, \
'clip.shape[0]:%s, feature_size:%s'%(clip.shape[0],feature_size)
mgc_frame_num.append(clip.shape[0] / feature_size)
print '(mgc frame num, spec frame num)', clip.shape[0] / feature_size, int(num_frames)
data.extend(clip)
print(str(count) + '/' + str(size) + ' opened: ' + name)
specname_basename = os.path.basename(specname)
data_basename = specname_basename.replace('specnames', 'data')
assert len(data) % feature_size == 0
print '..reshaping mgc files into npy array'
low_dim_data = np.asarray(data).reshape(len(data)/feature_size, feature_size)
data_fin = open(datafile)
dataset_raw = np.load(data_fin)
if preprocessor:
proc = getattr(procs, args.preprocessor)()
print 'applying preprocessing: ' + args.preprocessor
proc.apply(dataset_raw)
del dataset_raw
print 'decoding..'
dataset_out = model.decode(low_dim_data)
del low_dim_data
if preprocessor:
print 'invert dataset..'
dataset = proc.invert(dataset_out)
else:
dataset = dataset_out
dataset = dataset.astype(output_dtype)
del dataset_out
pointer = 0
for specname_d, mgc_num in zip(specname_data, mgc_frame_num):
f_name, num = tuple(specname_d)
print 'f_name, mgc_num_frames : %s, %s'%(f_name, mgc_num)
f_name = f_name.rstrip('.f4')
f_name = f_name.rstrip('.f8')
dataset[pointer:pointer + mgc_num].tofile(output_dir + '/' + f_name+'.%s'%output_dtype, format=output_dtype)
pointer += mgc_num
assert pointer == dataset.shape[0], 'did not recur until the end of array'
print 'closing files..'
data_fin.close()
specname_fin.close()
print 'Done!'
print('all files saved to %s'%output_dir)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='''Generate specs from hmm generated mgcs using the decoding part of Autoencoder''')
parser.add_argument('--mgc_dir', metavar='DIR', type=str, help='''dir of the mgc files''')
parser.add_argument('--ext', metavar='EXT', default='spec', help='''extension of mgc files''')
parser.add_argument('--specnames', metavar='PATH', help='''path to specnames npy files''')
parser.add_argument('--dataset', metavar='PATH', help='path to data npy file')
parser.add_argument('--input_spec_dtype', metavar='f4|f8', default='f4',
help='''dtype of the input spec files f4|f8, default=f4''')
parser.add_argument('--feature_size', metavar='INT', default=2049, type=int,
help='''feature size in an example, default=2049''')
parser.add_argument('--output_dir', metavar='PATH', default='.',
help='''directory to save the combined data file''')
parser.add_argument('--preprocessor', metavar='NAME', help='name of the preprocessor')
parser.add_argument('--output_dtype', metavar='f4|f8', default='f8',
help='output datatype of spec file, f4|f8, default=f8')
parser.add_argument('--model', metavar='PATH', help='path for the model')
args = parser.parse_args()
print('..dataset directory: %s'%args.mgc_dir)
print('..spec extension: %s'%args.ext)
print('..specnames: %s'%args.specnames)
print('..original npy dataset: %s'%args.dataset)
print('..input data files dtype: %s'%args.input_spec_dtype)
print('..feature_size: %s'%args.feature_size)
print('..save outputs to: %s'%args.output_dir)
print('..preprocessor: %s'%args.preprocessor)
print('..output_dtype: %s'%args.output_dtype)
print('..model: %s'%args.model)
if not os.path.exists(args.output_dir):
os.mkdir(args.output_dir)
generate_specs(args.ext, args.mgc_dir, args.specnames, args.dataset, args.input_spec_dtype,
args.feature_size, args.output_dir, args.preprocessor, args.output_dtype, args.model)
|
# Another code written by Jagger Kyne
# Copyright 2006 - 2013 Jagger Kyne <[email protected]>
__author__ = 'Jagger Kyne'
from tkinter import *
import random
import time
class Game:
def __init__(self):
self.tk = Tk()
self.tk.title("Mr. Stick Man Race for the Exit")
self.tk.resizable(0,0)
self.tk.wm_attributes('-topmost',1)
self.canvas = Canvas(self.tk,width=500,height=500,highlightthickness=0)
self.canvas.pack()
self.canvas.update()
self.canvas_height = 500
self.canvas_width = 500
bg_path = '/Users/Wilson/Documents/Sites/Python_For_Kids/Part_02/Chapter_16/graphics/background.gif'
self.bg = PhotoImage(file=bg_path)
# test.gif
w = self.bg.width()
h = self.bg.height()
for x in range(0,5):
for y in range(0,5):
self.canvas.create_image(x*w,y*h,image=self.bg,anchor='nw')
self.sprites = []
self.running = True
def mainloop(self):
while 1:
if self.running == True:
for sprite in self.sprites:
sprite.move()
self.tk.update_idletasks()
self.tk.update()
time.sleep(0.01)
class Corrds:
def __init__(self,x1=0,y1=0,x2=0,y2=0):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
def within_x(co1,co2):
if (co1.x1 > co2.x1 and co1.x1 < co2.x2)\
or (co1.x2 > co2.x1 and co1.x2 < co2.x2)\
or (co2.x1 > co1.x1 and co2.x2 < co1.x1)\
or (co2.x2 > co1.x1 and co2.x2 < co1.x1):
return True
else:
return False
def within_y(co1,co2):
if(co1.y1 > co2.y1 and co1.y1 <co2.y2)\
or(co1.y2 > co2.y1 and co1.y2 < co2.y2)\
or(co2.y1 > co1.y1 and co2.y1 < co1.y2)\
or(co2.y2 > co1.y1 and co2.y2 < co1.y1):
return True
else:
return False
def collided_left(co1,co2):
if within_y(co1,co2):
if co1.x1 <= co2.x2 and co1.x1 >= co2.x1:
return True
return False
def collided_right(co1,co2):
if within_y(co1,co2):
if co1.x2 >= co2.x1 and co1.x2 <= co2.x2:
return True
return False
def collided_top(co1,co2):
if within_x(co1,co2):
if co1.y1 <= co2.y2 and co1.y1 >= co2.y1:
return True
return False
def collided_bottom(y,co1,co2):
if within_x(co1, co2):
y_cal = co1.y2 + y
if y_cal >= co2.y1 and y_cal <= co2.y2:
return True
return False
class Sprite:
def __init__(self,game):
self.game = game
self.endgame = False
self.coordinates = None
def move(self):
pass
def coords(self):
return self.coordinates
class PlatformSprite(Sprite):
def __init__(self,game,photo_image,x,y,width,height):
Sprite.__init__(self,game)
self.photo_image = photo_image
self.image = game.canvas.create_image(x,y,image=self.photo_image,anchor='nw')
self.coordinates = Corrds(x,y,x + width, y + height)
g = Game()
path1 = '/Users/Wilson/Documents/Sites/Python_For_Kids/Part_02/Chapter_16/graphics/platform1.gif'
path2 = '/Users/Wilson/Documents/Sites/Python_For_Kids/Part_02/Chapter_16/graphics/platform2.gif'
path3 = '/Users/Wilson/Documents/Sites/Python_For_Kids/Part_02/Chapter_16/graphics/platform3.gif'
platform1 = PlatformSprite(g,PhotoImage(file=path1),0,480,100,10)
platform2 = PlatformSprite(g,PhotoImage(file=path1),150,440,100,10)
platform3 = PlatformSprite(g,PhotoImage(file=path1),300,480,100,10)
platform4 = PlatformSprite(g,PhotoImage(file=path1),300,160,100,10)
platform5 = PlatformSprite(g,PhotoImage(file=path2),175,350,66,10)
platform6 = PlatformSprite(g,PhotoImage(file=path2),50,380,66,10)
platform7 = PlatformSprite(g,PhotoImage(file=path2),170,120,66,10)
platform8 = PlatformSprite(g,PhotoImage(file=path2),45,60,66,10)
platform9 = PlatformSprite(g,PhotoImage(file=path3),170,250,32,10)
platform10 = PlatformSprite(g,PhotoImage(file=path3),230,280,32,10)
g.sprites.append(platform1)
g.mainloop()
|
#!/usr/bin/python -u
# 2004/10/15
#v1.0.0
# webcounter.py
# A very simple webcounter.
# Copyright Michael Foord
# You are free to modify, use and relicense this code.
# No warranty express or implied for the accuracy, fitness to purpose or otherwise for this code....
# Use at your own risk !!!
# For information about bugfixes, updates and support, please join the Pythonutils mailing list.
# http://voidspace.xennos.com/mailman/listinfo/pythonutils_voidspace.xennos.com
# Comments, suggestions and bug reports welcome.
# Scripts maintained at www.voidspace.org.uk/atlantibots/pythonutils.html
# E-mail michael AT foord DOT me DOT uk
"""
This saves a count of accesses and returns a single line of javascript.
This writes the number into the webpage.
Insert the following entry into your page :
<script language=JavaScript src="http://www.voidspace.xennos.com/cgi-bin/webcounter.py?site=SITENAME"></script>
That will use the version hosted on my server.
Replace SITENAME with something that is likely to be unique.
"""
########################################################################
# imports
import os
import cgi
import time
try:
import cgitb
cgitb.enable()
except:
sys.stderr = sys.stdout
############################################
# values
sitedir = 'webcounter/' # directory to store counter files
logfile = '.counter' # each site will have it's own counter file. The full path is sitedir + sitename + logfile
# timeformat is used by strftime in the time module
# It defines how the date is displayed.
# set to '' to omit.
# Only edit if you understand strftime.
timeformat = "%d %B, %Y."
serverline = 'Content-type: application/x-javascript\n' # header to send for stats output, just text so far
# This is the actual Javascript returned
thescript = 'document.writeln("%s");'
line1 = "%s visitors"
line2 = "%s visitors since<br />%s"
errormsg = 'Counter Error - No site specified.'
######################################################################
def main():
theform = cgi.FieldStorage() # get the form
try:
thesite = theform['site'].value
except KeyError:
thesite = ''
counterfile = sitedir+thesite+logfile
if not os.path.isdir(sitedir):
os.makedirs(sitedir)
if not thesite:
themsg = thescript % errormsg
else:
if os.path.isfile(counterfile):
filehandle = open(counterfile, 'r')
counterdata = filehandle.readlines()
filehandle.close()
thedate = counterdata[1]
thecount = counterdata[0]
else:
if timeformat:
thedate = time.strftime(timeformat)
else:
thedate = ''
thecount = "0"
thecount = str(int(thecount)+1)
filehandle = open(counterfile, 'w')
filehandle.write(thecount+'\n')
filehandle.write(thedate)
filehandle.close()
if timeformat:
msgline = line2 % (thecount, thedate)
else:
msgline = line1 % thecount
themsg = thescript % msgline
print serverline
print themsg
########################################################################
if __name__ =='__main__':
main()
"""
TODO
ISSUES
CHANGELOG
2004/10/15 Version 1.0.0
A very simple CGI.
"""
|
# Copyright 2012 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Handles all requests to the conductor service."""
from oslo.config import cfg
from oslo import messaging
from nova import baserpc
from nova.conductor import manager
from nova.conductor import rpcapi
from nova.openstack.common.gettextutils import _
from nova.openstack.common import log as logging
from nova import utils
conductor_opts = [
cfg.BoolOpt('use_local',
default=False,
help='Perform nova-conductor operations locally'),
cfg.StrOpt('topic',
default='conductor',
help='The topic on which conductor nodes listen'),
cfg.StrOpt('manager',
default='nova.conductor.manager.ConductorManager',
help='Full class name for the Manager for conductor'),
cfg.IntOpt('workers',
help='Number of workers for OpenStack Conductor service. '
'The default will be the number of CPUs available.')
]
conductor_group = cfg.OptGroup(name='conductor',
title='Conductor Options')
CONF = cfg.CONF
CONF.register_group(conductor_group)
CONF.register_opts(conductor_opts, conductor_group)
LOG = logging.getLogger(__name__)
class LocalAPI(object):
"""A local version of the conductor API that does database updates
locally instead of via RPC.
"""
def __init__(self):
# TODO(danms): This needs to be something more generic for
# other/future users of this sort of functionality.
self._manager = utils.ExceptionHelper(manager.ConductorManager())
def wait_until_ready(self, context, *args, **kwargs):
# nothing to wait for in the local case.
pass
def instance_update(self, context, instance_uuid, **updates):
"""Perform an instance update in the database."""
return self._manager.instance_update(context, instance_uuid,
updates, 'compute')
def instance_get_by_uuid(self, context, instance_uuid,
columns_to_join=None):
return self._manager.instance_get_by_uuid(context, instance_uuid,
columns_to_join)
def instance_destroy(self, context, instance):
return self._manager.instance_destroy(context, instance)
def instance_get_all_by_host(self, context, host, columns_to_join=None):
return self._manager.instance_get_all_by_host(
context, host, columns_to_join=columns_to_join)
def instance_get_all_by_host_and_node(self, context, host, node):
return self._manager.instance_get_all_by_host(context, host, node)
def instance_get_all_by_filters(self, context, filters,
sort_key='created_at',
sort_dir='desc',
columns_to_join=None, use_slave=False):
return self._manager.instance_get_all_by_filters(context,
filters,
sort_key,
sort_dir,
columns_to_join,
use_slave)
def instance_get_active_by_window_joined(self, context, begin, end=None,
project_id=None, host=None):
return self._manager.instance_get_active_by_window_joined(
context, begin, end, project_id, host)
def instance_info_cache_delete(self, context, instance):
return self._manager.instance_info_cache_delete(context, instance)
def instance_fault_create(self, context, values):
return self._manager.instance_fault_create(context, values)
def migration_get_in_progress_by_host_and_node(self, context, host, node):
return self._manager.migration_get_in_progress_by_host_and_node(
context, host, node)
def aggregate_host_add(self, context, aggregate, host):
return self._manager.aggregate_host_add(context, aggregate, host)
def aggregate_host_delete(self, context, aggregate, host):
return self._manager.aggregate_host_delete(context, aggregate, host)
def aggregate_metadata_get_by_host(self, context, host,
key='availability_zone'):
return self._manager.aggregate_metadata_get_by_host(context,
host,
key)
def bw_usage_get(self, context, uuid, start_period, mac):
return self._manager.bw_usage_update(context, uuid, mac, start_period)
def bw_usage_update(self, context, uuid, mac, start_period,
bw_in, bw_out, last_ctr_in, last_ctr_out,
last_refreshed=None, update_cells=True):
return self._manager.bw_usage_update(context, uuid, mac, start_period,
bw_in, bw_out,
last_ctr_in, last_ctr_out,
last_refreshed,
update_cells=update_cells)
def provider_fw_rule_get_all(self, context):
return self._manager.provider_fw_rule_get_all(context)
def agent_build_get_by_triple(self, context, hypervisor, os, architecture):
return self._manager.agent_build_get_by_triple(context, hypervisor,
os, architecture)
def block_device_mapping_create(self, context, values):
return self._manager.block_device_mapping_update_or_create(context,
values,
create=True)
def block_device_mapping_update(self, context, bdm_id, values):
values = dict(values)
values['id'] = bdm_id
return self._manager.block_device_mapping_update_or_create(
context, values, create=False)
def block_device_mapping_update_or_create(self, context, values):
return self._manager.block_device_mapping_update_or_create(context,
values)
def block_device_mapping_get_all_by_instance(self, context, instance,
legacy=True):
return self._manager.block_device_mapping_get_all_by_instance(
context, instance, legacy)
def vol_get_usage_by_time(self, context, start_time):
return self._manager.vol_get_usage_by_time(context, start_time)
def vol_usage_update(self, context, vol_id, rd_req, rd_bytes, wr_req,
wr_bytes, instance, last_refreshed=None,
update_totals=False):
return self._manager.vol_usage_update(context, vol_id,
rd_req, rd_bytes,
wr_req, wr_bytes,
instance, last_refreshed,
update_totals)
def service_get_all(self, context):
return self._manager.service_get_all_by(context)
def service_get_all_by_topic(self, context, topic):
return self._manager.service_get_all_by(context, topic=topic)
def service_get_all_by_host(self, context, host):
return self._manager.service_get_all_by(context, host=host)
def service_get_by_host_and_topic(self, context, host, topic):
return self._manager.service_get_all_by(context, topic, host)
def service_get_by_compute_host(self, context, host):
result = self._manager.service_get_all_by(context, 'compute', host)
# FIXME(comstud): A major revision bump to 2.0 should return a
# single entry, so we should just return 'result' at that point.
return result[0]
def service_get_by_args(self, context, host, binary):
return self._manager.service_get_all_by(context, host=host,
binary=binary)
def action_event_start(self, context, values):
return self._manager.action_event_start(context, values)
def action_event_finish(self, context, values):
return self._manager.action_event_finish(context, values)
def service_create(self, context, values):
return self._manager.service_create(context, values)
def service_destroy(self, context, service_id):
return self._manager.service_destroy(context, service_id)
def compute_node_create(self, context, values):
return self._manager.compute_node_create(context, values)
def compute_node_update(self, context, node, values, prune_stats=False):
# NOTE(belliott) ignore prune_stats param, it's no longer relevant
return self._manager.compute_node_update(context, node, values)
def compute_node_delete(self, context, node):
return self._manager.compute_node_delete(context, node)
def service_update(self, context, service, values):
return self._manager.service_update(context, service, values)
def task_log_get(self, context, task_name, begin, end, host, state=None):
return self._manager.task_log_get(context, task_name, begin, end,
host, state)
def task_log_begin_task(self, context, task_name, begin, end, host,
task_items=None, message=None):
return self._manager.task_log_begin_task(context, task_name,
begin, end, host,
task_items, message)
def task_log_end_task(self, context, task_name, begin, end, host,
errors, message=None):
return self._manager.task_log_end_task(context, task_name,
begin, end, host,
errors, message)
def notify_usage_exists(self, context, instance, current_period=False,
ignore_missing_network_data=True,
system_metadata=None, extra_usage_info=None):
return self._manager.notify_usage_exists(
context, instance, current_period, ignore_missing_network_data,
system_metadata, extra_usage_info)
def security_groups_trigger_handler(self, context, event, *args):
return self._manager.security_groups_trigger_handler(context,
event, args)
def security_groups_trigger_members_refresh(self, context, group_ids):
return self._manager.security_groups_trigger_members_refresh(context,
group_ids)
def network_migrate_instance_start(self, context, instance, migration):
return self._manager.network_migrate_instance_start(context,
instance,
migration)
def network_migrate_instance_finish(self, context, instance, migration):
return self._manager.network_migrate_instance_finish(context,
instance,
migration)
def get_ec2_ids(self, context, instance):
return self._manager.get_ec2_ids(context, instance)
def compute_unrescue(self, context, instance):
return self._manager.compute_unrescue(context, instance)
def object_backport(self, context, objinst, target_version):
return self._manager.object_backport(context, objinst, target_version)
class LocalComputeTaskAPI(object):
def __init__(self):
# TODO(danms): This needs to be something more generic for
# other/future users of this sort of functionality.
self._manager = utils.ExceptionHelper(
manager.ComputeTaskManager())
def resize_instance(self, context, instance, extra_instance_updates,
scheduler_hint, flavor, reservations):
# NOTE(comstud): 'extra_instance_updates' is not used here but is
# needed for compatibility with the cells_rpcapi version of this
# method.
self._manager.migrate_server(
context, instance, scheduler_hint, False, False, flavor,
None, None, reservations)
def live_migrate_instance(self, context, instance, host_name,
block_migration, disk_over_commit):
scheduler_hint = {'host': host_name}
self._manager.migrate_server(
context, instance, scheduler_hint, True, False, None,
block_migration, disk_over_commit, None)
def build_instances(self, context, instances, image,
filter_properties, admin_password, injected_files,
requested_networks, security_groups, block_device_mapping,
legacy_bdm=True):
utils.spawn_n(self._manager.build_instances, context,
instances=instances, image=image,
filter_properties=filter_properties,
admin_password=admin_password, injected_files=injected_files,
requested_networks=requested_networks,
security_groups=security_groups,
block_device_mapping=block_device_mapping,
legacy_bdm=legacy_bdm)
def unshelve_instance(self, context, instance):
utils.spawn_n(self._manager.unshelve_instance, context,
instance=instance)
class API(LocalAPI):
"""Conductor API that does updates via RPC to the ConductorManager."""
def __init__(self):
self._manager = rpcapi.ConductorAPI()
self.base_rpcapi = baserpc.BaseAPI(topic=CONF.conductor.topic)
def wait_until_ready(self, context, early_timeout=10, early_attempts=10):
'''Wait until a conductor service is up and running.
This method calls the remote ping() method on the conductor topic until
it gets a response. It starts with a shorter timeout in the loop
(early_timeout) up to early_attempts number of tries. It then drops
back to the globally configured timeout for rpc calls for each retry.
'''
attempt = 0
timeout = early_timeout
while True:
# NOTE(danms): Try ten times with a short timeout, and then punt
# to the configured RPC timeout after that
if attempt == early_attempts:
timeout = None
attempt += 1
# NOTE(russellb): This is running during service startup. If we
# allow an exception to be raised, the service will shut down.
# This may fail the first time around if nova-conductor wasn't
# running when this service started.
try:
self.base_rpcapi.ping(context, '1.21 GigaWatts',
timeout=timeout)
break
except messaging.MessagingTimeout:
LOG.warning(_('Timed out waiting for nova-conductor. '
'Is it running? Or did this service start '
'before nova-conductor?'))
def instance_update(self, context, instance_uuid, **updates):
"""Perform an instance update in the database."""
return self._manager.instance_update(context, instance_uuid,
updates, 'conductor')
class ComputeTaskAPI(object):
"""ComputeTask API that queues up compute tasks for nova-conductor."""
def __init__(self):
self.conductor_compute_rpcapi = rpcapi.ComputeTaskAPI()
def resize_instance(self, context, instance, extra_instance_updates,
scheduler_hint, flavor, reservations):
# NOTE(comstud): 'extra_instance_updates' is not used here but is
# needed for compatibility with the cells_rpcapi version of this
# method.
self.conductor_compute_rpcapi.migrate_server(
context, instance, scheduler_hint, False, False, flavor,
None, None, reservations)
def live_migrate_instance(self, context, instance, host_name,
block_migration, disk_over_commit):
scheduler_hint = {'host': host_name}
self.conductor_compute_rpcapi.migrate_server(
context, instance, scheduler_hint, True, False, None,
block_migration, disk_over_commit, None)
def build_instances(self, context, instances, image, filter_properties,
admin_password, injected_files, requested_networks,
security_groups, block_device_mapping, legacy_bdm=True):
self.conductor_compute_rpcapi.build_instances(context,
instances=instances, image=image,
filter_properties=filter_properties,
admin_password=admin_password, injected_files=injected_files,
requested_networks=requested_networks,
security_groups=security_groups,
block_device_mapping=block_device_mapping,
legacy_bdm=legacy_bdm)
def unshelve_instance(self, context, instance):
self.conductor_compute_rpcapi.unshelve_instance(context,
instance=instance)
|
__author__ = 'matthewpang'
import serial
import time
import pickle
import struct
serStepper = serial.Serial('/dev/cu.usbmodem14231', 230400)
time.sleep(3)
def output_encoder(value):
"""
Takes a 16 bit integer value, packs it little endian, then encapsulates it in the defined format
[0xAA,LSByte,MSByte,OxFF]
"""
b = struct.pack('<H', value)
output = bytearray(4)
output[0] = 0xAA
output[1] = b[0]
output[2] = b[1]
output[3] = 0xFF
return output
def output_decoder(array):
"""
Takes a little endian byte array of format [0xAA,LSByte,MSByte,OxFF]
and returns the corresponding 16 bit integer value
"""
if len(array) != 4: #If the packet length is correct, otherwise return None
return None
if (array[0] == 0xAA) and (array[3] == 0XFF) and len(array) == 4: #Check that the packet has the correct start and end frame
a = array[2] << 8 | array[1]
return int(a)
def serial_send(value):
"""
Accepts a 16 bit unsigned int , encodes it and sends it, returns the bytearray that was sent
"""
frame = output_encoder(value)
serStepper.write(frame)
print(str(value))
return frame
def serial_receive():
"""
Waits up to 5 seconds for a response after being called, decodes the byte array and returns a 16 bit unsigned int
"""
timeout = time.time() + 5
while (serStepper.in_waiting <= 3) and (time.time() < timeout): # Wait until correct number of packets, timeout if waiting too long
time.sleep(0.0001)
else:
serial_read = (serStepper.read(serStepper.in_waiting))
val = output_decoder(serial_read)
print(str(val))
return val
def arrival_wait():
"""
Waits the get the arrival confirmation message 0xFF00 .
Clears the buffers for cleanliness
"""
timeout = time.time() + 600
while (serial_receive() != 0xFF00) and (time.time() <= timeout):
time.sleep(0.0001)
serStepper.reset_input_buffer()
serStepper.reset_output_buffer()
def go(pos=0):
"""
Accepts a position and sends it serially.
Waits for arrival confirmation
#Optionally times the difference between instruction and respose - uncomment.
"""
sent = time.time()
serial_send(pos)
arrival_wait()
received = time.time()
print(str(received - sent))
go(0x0000)
|
import os
import re
import datetime
import subprocess
vendorid = 85838187 # David Foster
# Find all reports in the current directory
reports = [] # list of (vendorid, YYYYMMDD), both strings
for filename in os.listdir('.'):
# NOTE: Download filename format changed on 2011-11-03
m = re.match(r'S_D_([0-9]+)_([0-9]{8})(_[^.]*)?\.txt(\.gz)?', filename)
if m is None:
continue
reports.append((m.group(1), m.group(2)))
if len(reports) == 0:
exit('No reports found in the current directory.')
# Find all report dates for the vendor of interest
dates = [x[1] for x in reports if x[0] == str(vendorid)] # list of YYYYMMDD
if len(reports) == 0:
exit('No reports in the current directory match the vendor ID ' + str(vendorID) + '.')
# Determine reports available for download
downloadableDates = [] # list of YYYYMMDD
now = datetime.datetime.now()
for i in xrange(30):
downloadableDates.append((now - datetime.timedelta(days = i+1)).strftime('%Y%m%d'))
# Determine reports available for download that haven't already been downloaded
missingDates = list(set(downloadableDates) - set(dates)) # list of YYYYMMDD
missingDates.sort()
if len(missingDates) == 0:
print 'All reports have been downloaded already.'
exit(0)
# Download all missing reports, recording any errors
downloadErrors = [] # list of (YYYYMMDD, stdoutdata, stderrdata)
for curDate in missingDates:
downloader = subprocess.Popen(['java', 'Autoingestion', 'autoingestion.properties', str(vendorid), 'Sales', 'Daily', 'Summary', curDate], stdout=subprocess.PIPE)
out, err = downloader.communicate()
if 'File Downloaded Successfully' in out:
continue
# NOTE: Status message changed format on 2014-06-20
if ('There are no reports available to download for this selection.' in out or
'There is no report available to download, for the selected period'):
# No downloads occurred on this day.
# Generate placeholder result file to avoid refetching.
with open('S_D_%s_%s.txt' % (vendorid, curDate), 'wb'):
pass
continue
downloadErrors.append((curDate, out, err))
# Print summary
if len(downloadErrors) == 0:
print "Downloaded %s report(s)." % (len(missingDates))
else:
for (date, out, err) in downloadErrors:
print date + ':'
print out
print
print "Error downloading %s report(s). Remaining %s reports downloaded." % (len(downloadErrors), len(missingDates) - len(downloadErrors))
exit(1)
|
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# Thinkopen Brasil
# Copyright (C) Thinkopen Solutions Brasil (<http://www.tkobr.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Partner Relatives',
'version': '0.001',
'category': 'Customizations',
'sequence': 38,
'complexity': 'normal',
'description': ''' This module adds relatives tab in partner form
''',
'author': 'ThinkOpen Solutions Brasil',
'website': 'http://www.tkobr.com',
'images': ['images/oerp61.jpeg',
],
'depends': [
'base',
],
'data': [
'partner_view.xml',
],
'init': [],
'demo': [],
'update': [],
'test': [], # YAML files with tests
'installable': True,
'application': False,
# If it's True, the modules will be auto-installed when all dependencies are installed
'auto_install': False,
'certificate': '',
}
|
"""
sentry.interfaces
~~~~~~~~~~~~~~~~~
Interfaces provide an abstraction for how structured data should be
validated and rendered.
:copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import itertools
import urlparse
import warnings
from pygments import highlight
# from pygments.lexers import get_lexer_for_filename, TextLexer, ClassNotFound
from pygments.lexers import TextLexer
from pygments.formatters import HtmlFormatter
from django.http import QueryDict
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from sentry.app import env
from sentry.models import UserOption
from sentry.utils.strings import strip
from sentry.web.helpers import render_to_string
_Exception = Exception
def unserialize(klass, data):
value = object.__new__(klass)
value.__setstate__(data)
return value
def is_url(filename):
return filename.startswith(('http:', 'https:', 'file:'))
def get_context(lineno, context_line, pre_context=None, post_context=None, filename=None,
format=False):
lineno = int(lineno)
context = []
start_lineno = lineno - len(pre_context or [])
if pre_context:
start_lineno = lineno - len(pre_context)
at_lineno = start_lineno
for line in pre_context:
context.append((at_lineno, line))
at_lineno += 1
else:
start_lineno = lineno
at_lineno = lineno
if start_lineno < 0:
start_lineno = 0
context.append((at_lineno, context_line))
at_lineno += 1
if post_context:
for line in post_context:
context.append((at_lineno, line))
at_lineno += 1
# HACK:
if filename and is_url(filename) and '.' not in filename.rsplit('/', 1)[-1]:
filename = 'index.html'
if format:
# try:
# lexer = get_lexer_for_filename(filename)
# except ClassNotFound:
# lexer = TextLexer()
lexer = TextLexer()
formatter = HtmlFormatter()
def format(line):
if not line:
return mark_safe('<pre></pre>')
return mark_safe(highlight(line, lexer, formatter))
context = tuple((n, format(l)) for n, l in context)
return context
def is_newest_frame_first(event):
newest_first = event.platform not in ('python', None)
if env.request and env.request.user.is_authenticated():
display = UserOption.objects.get_value(
user=env.request.user,
project=None,
key='stacktrace_order',
default=None,
)
if display == '1':
newest_first = False
elif display == '2':
newest_first = True
return newest_first
class Interface(object):
"""
An interface is a structured representation of data, which may
render differently than the default ``extra`` metadata in an event.
"""
score = 0
display_score = None
def __init__(self, **kwargs):
self.attrs = kwargs.keys()
self.__dict__.update(kwargs)
def __eq__(self, other):
if type(self) != type(other):
return False
return self.serialize() == other.serialize()
def __setstate__(self, data):
kwargs = self.unserialize(data)
self.attrs = kwargs.keys()
self.__dict__.update(kwargs)
def __getstate__(self):
return self.serialize()
def validate(self):
pass
def unserialize(self, data):
return data
def serialize(self):
return dict((k, self.__dict__[k]) for k in self.attrs)
def get_composite_hash(self, interfaces):
return self.get_hash()
def get_hash(self):
return []
def to_html(self, event, is_public=False, **kwargs):
return ''
def to_string(self, event, is_public=False, **kwargs):
return ''
def get_slug(self):
return type(self).__name__.lower()
def get_title(self):
return _(type(self).__name__)
def get_display_score(self):
return self.display_score or self.score
def get_score(self):
return self.score
def get_search_context(self, event):
"""
Returns a dictionary describing the data that should be indexed
by the search engine. Several fields are accepted:
- text: a list of text items to index as part of the generic query
- filters: a map of fields which are used for precise matching
"""
return {
# 'text': ['...'],
# 'filters': {
# 'field": ['...'],
# },
}
class Message(Interface):
"""
A standard message consisting of a ``message`` arg, and an optional
``params`` arg for formatting.
If your message cannot be parameterized, then the message interface
will serve no benefit.
- ``message`` must be no more than 1000 characters in length.
>>> {
>>> "message": "My raw message with interpreted strings like %s",
>>> "params": ["this"]
>>> }
"""
attrs = ('message', 'params')
def __init__(self, message, params=(), **kwargs):
self.message = message
self.params = params
def validate(self):
assert len(self.message) <= 5000
def serialize(self):
return {
'message': self.message,
'params': self.params,
}
def get_hash(self):
return [self.message]
def get_search_context(self, event):
if isinstance(self.params, (list, tuple)):
params = list(self.params)
elif isinstance(self.params, dict):
params = self.params.values()
else:
params = []
return {
'text': [self.message] + params,
}
class Query(Interface):
"""
A SQL query with an optional string describing the SQL driver, ``engine``.
>>> {
>>> "query": "SELECT 1"
>>> "engine": "psycopg2"
>>> }
"""
attrs = ('query', 'engine')
def __init__(self, query, engine=None, **kwargs):
self.query = query
self.engine = engine
def get_hash(self):
return [self.query]
def serialize(self):
return {
'query': self.query,
'engine': self.engine,
}
def get_search_context(self, event):
return {
'text': [self.query],
}
class Frame(object):
attrs = ('abs_path', 'filename', 'lineno', 'colno', 'in_app', 'context_line',
'pre_context', 'post_context', 'vars', 'module', 'function', 'data')
def __init__(self, abs_path=None, filename=None, lineno=None, colno=None,
in_app=None, context_line=None, pre_context=(),
post_context=(), vars=None, module=None, function=None,
data=None, **kwargs):
self.abs_path = abs_path or filename
self.filename = filename or abs_path
if self.is_url():
urlparts = urlparse.urlparse(self.abs_path)
if urlparts.path:
self.filename = urlparts.path
self.module = module
self.function = function
if lineno is not None:
self.lineno = int(lineno)
else:
self.lineno = None
if colno is not None:
self.colno = int(colno)
else:
self.colno = None
self.in_app = in_app
self.context_line = context_line
self.pre_context = pre_context
self.post_context = post_context
self.vars = vars or {}
self.data = data or {}
def __getitem__(self, key):
warnings.warn('Frame[key] is deprecated. Use Frame.key instead.', DeprecationWarning)
return getattr(self, key)
def is_url(self):
if not self.abs_path:
return False
return is_url(self.abs_path)
def is_valid(self):
if self.in_app not in (False, True, None):
return False
if type(self.vars) != dict:
return False
if type(self.data) != dict:
return False
return self.filename or self.function or self.module
def get_hash(self):
output = []
if self.module:
output.append(self.module)
elif self.filename and not self.is_url():
output.append(self.filename)
if self.context_line is not None:
output.append(self.context_line)
elif not output:
# If we were unable to achieve any context at this point
# (likely due to a bad JavaScript error) we should just
# bail on recording this frame
return output
elif self.function:
output.append(self.function)
elif self.lineno is not None:
output.append(self.lineno)
return output
def get_context(self, event, is_public=False, **kwargs):
if (self.context_line and self.lineno is not None
and (self.pre_context or self.post_context)):
context = get_context(
lineno=self.lineno,
context_line=self.context_line,
pre_context=self.pre_context,
post_context=self.post_context,
filename=self.filename or self.module,
format=True,
)
start_lineno = context[0][0]
else:
context = []
start_lineno = None
frame_data = {
'abs_path': self.abs_path,
'filename': self.filename,
'module': self.module,
'function': self.function,
'start_lineno': start_lineno,
'lineno': self.lineno,
'context': context,
'context_line': self.context_line,
'in_app': self.in_app,
'is_url': self.is_url(),
}
if not is_public:
frame_data['vars'] = self.vars or {}
if event.platform == 'javascript' and self.data:
frame_data.update({
'sourcemap': self.data['sourcemap'].rsplit('/', 1)[-1],
'sourcemap_url': urlparse.urljoin(self.abs_path, self.data['sourcemap']),
'orig_function': self.data['orig_function'],
'orig_filename': self.data['orig_filename'],
'orig_lineno': self.data['orig_lineno'],
'orig_colno': self.data['orig_colno'],
})
return frame_data
def to_string(self, event):
if event.platform is not None:
choices = [event.platform]
else:
choices = []
choices.append('default')
templates = [
'sentry/partial/frames/%s.txt' % choice
for choice in choices
]
return render_to_string(templates, {
'abs_path': self.abs_path,
'filename': self.filename,
'function': self.function,
'module': self.module,
'lineno': self.lineno,
'colno': self.colno,
'context_line': self.context_line,
}).strip('\n')
class Stacktrace(Interface):
"""
A stacktrace contains a list of frames, each with various bits (most optional)
describing the context of that frame. Frames should be sorted from oldest
to newest.
The stacktrace contains one element, ``frames``, which is a list of hashes. Each
hash must contain **at least** the ``filename`` attribute. The rest of the values
are optional, but recommended.
The list of frames should be ordered by the oldest call first.
Each frame must contain the following attributes:
``filename``
The relative filepath to the call
OR
``function``
The name of the function being called
OR
``module``
Platform-specific module path (e.g. sentry.interfaces.Stacktrace)
The following additional attributes are supported:
``lineno``
The line number of the call
``colno``
The column number of the call
``abs_path``
The absolute path to filename
``context_line``
Source code in filename at lineno
``pre_context``
A list of source code lines before context_line (in order) -- usually [lineno - 5:lineno]
``post_context``
A list of source code lines after context_line (in order) -- usually [lineno + 1:lineno + 5]
``in_app``
Signifies whether this frame is related to the execution of the relevant code in this stacktrace. For example,
the frames that might power the framework's webserver of your app are probably not relevant, however calls to
the framework's library once you start handling code likely are.
``vars``
A mapping of variables which were available within this frame (usually context-locals).
>>> {
>>> "frames": [{
>>> "abs_path": "/real/file/name.py"
>>> "filename": "file/name.py",
>>> "function": "myfunction",
>>> "vars": {
>>> "key": "value"
>>> },
>>> "pre_context": [
>>> "line1",
>>> "line2"
>>> ],
>>> "context_line": "line3",
>>> "lineno": 3,
>>> "in_app": true,
>>> "post_context": [
>>> "line4",
>>> "line5"
>>> ],
>>> }]
>>> }
.. note:: This interface can be passed as the 'stacktrace' key in addition
to the full interface path.
"""
attrs = ('frames',)
score = 1000
def __init__(self, frames, **kwargs):
self.frames = [Frame(**f) for f in frames]
def __iter__(self):
return iter(self.frames)
def validate(self):
for frame in self.frames:
# ensure we've got the correct required values
assert frame.is_valid()
def serialize(self):
frames = []
for f in self.frames:
# compatibility with old serialization
if isinstance(f, Frame):
frames.append(vars(f))
else:
frames.append(f)
return {
'frames': frames,
}
def has_app_frames(self):
return any(f.in_app is not None for f in self.frames)
def unserialize(self, data):
data['frames'] = [Frame(**f) for f in data.pop('frames', [])]
return data
def get_composite_hash(self, interfaces):
output = self.get_hash()
if 'sentry.interfaces.Exception' in interfaces:
exc = interfaces['sentry.interfaces.Exception'][0]
if exc.type:
output.append(exc.type)
elif not output:
output = exc.get_hash()
return output
def get_hash(self):
output = []
for frame in self.frames:
output.extend(frame.get_hash())
return output
def get_context(self, event, is_public=False, newest_first=None,
with_stacktrace=True, **kwargs):
system_frames = 0
frames = []
for frame in self.frames:
frames.append(frame.get_context(event=event, is_public=is_public))
if not frame.in_app:
system_frames += 1
if len(frames) == system_frames:
system_frames = 0
# if theres no system frames, pretend they're all part of the app
if not system_frames:
for frame in frames:
frame['in_app'] = True
if newest_first is None:
newest_first = is_newest_frame_first(event)
if newest_first:
frames = frames[::-1]
context = {
'is_public': is_public,
'newest_first': newest_first,
'system_frames': system_frames,
'event': event,
'frames': frames,
'stack_id': 'stacktrace_1',
}
if with_stacktrace:
context['stacktrace'] = self.get_traceback(event, newest_first=newest_first)
return context
def to_html(self, event, **kwargs):
context = self.get_context(
event=event,
**kwargs
)
return render_to_string('sentry/partial/interfaces/stacktrace.html', context)
def to_string(self, event, is_public=False, **kwargs):
return self.get_stacktrace(event, system_frames=False, max_frames=5)
def get_stacktrace(self, event, system_frames=True, newest_first=None, max_frames=None):
if newest_first is None:
newest_first = is_newest_frame_first(event)
result = []
if newest_first:
result.append(_('Stacktrace (most recent call first):'))
else:
result.append(_('Stacktrace (most recent call last):'))
result.append('')
frames = self.frames
num_frames = len(frames)
if not system_frames:
frames = [f for f in frames if f.in_app is not False]
if not frames:
frames = self.frames
if newest_first:
frames = frames[::-1]
if max_frames:
visible_frames = max_frames
if newest_first:
start, stop = None, max_frames
else:
start, stop = -max_frames, None
else:
visible_frames = len(frames)
start, stop = None, None
if not newest_first and visible_frames < num_frames:
result.extend(('(%d additional frame(s) were not displayed)' % (num_frames - visible_frames,), '...'))
for frame in frames[start:stop]:
result.append(frame.to_string(event))
if newest_first and visible_frames < num_frames:
result.extend(('...', '(%d additional frame(s) were not displayed)' % (num_frames - visible_frames,)))
return '\n'.join(result)
def get_traceback(self, event, newest_first=None):
result = [
event.message, '',
self.get_stacktrace(event, newest_first=newest_first),
]
return '\n'.join(result)
def get_search_context(self, event):
return {
'text': list(itertools.chain(*[[f.filename, f.function, f.context_line] for f in self.frames])),
}
class SingleException(Interface):
"""
A standard exception with a mandatory ``value`` argument, and optional
``type`` and``module`` argument describing the exception class type and
module namespace.
You can also optionally bind a stacktrace interface to an exception. The
spec is identical to ``sentry.interfaces.Stacktrace``.
>>> {
>>> "type": "ValueError",
>>> "value": "My exception value",
>>> "module": "__builtins__"
>>> "stacktrace": {
>>> # see sentry.interfaces.Stacktrace
>>> }
>>> }
"""
attrs = ('value', 'type', 'module', 'stacktrace')
score = 900
display_score = 1200
def __init__(self, value, type=None, module=None, stacktrace=None, **kwargs):
# A human readable value for the exception
self.value = value
# The exception type name (e.g. TypeError)
self.type = type
# Optional module of the exception type (e.g. __builtin__)
self.module = module
# Optional bound stacktrace interface
if stacktrace:
self.stacktrace = Stacktrace(**stacktrace)
else:
self.stacktrace = None
def validate(self):
if self.stacktrace:
return self.stacktrace.validate()
def serialize(self):
if self.stacktrace:
stacktrace = self.stacktrace.serialize()
else:
stacktrace = None
return {
'type': strip(self.type) or None,
'value': strip(self.value) or None,
'module': strip(self.module) or None,
'stacktrace': stacktrace,
}
def unserialize(self, data):
if data.get('stacktrace'):
data['stacktrace'] = unserialize(Stacktrace, data['stacktrace'])
else:
data['stacktrace'] = None
return data
def get_hash(self):
output = None
if self.stacktrace:
output = self.stacktrace.get_hash()
if output and self.type:
output.append(self.type)
if not output:
output = filter(bool, [self.type, self.value])
return output
def get_context(self, event, is_public=False, **kwargs):
last_frame = None
interface = event.interfaces.get('sentry.interfaces.Stacktrace')
if interface is not None and interface.frames:
last_frame = interface.frames[-1]
e_module = strip(self.module)
e_type = strip(self.type) or 'Exception'
e_value = strip(self.value)
if self.module:
fullname = '%s.%s' % (e_module, e_type)
else:
fullname = e_type
return {
'is_public': is_public,
'event': event,
'exception_value': e_value or e_type or '<empty value>',
'exception_type': e_type,
'exception_module': e_module,
'fullname': fullname,
'last_frame': last_frame
}
def get_search_context(self, event):
return {
'text': [self.value, self.type, self.module]
}
class Exception(Interface):
"""
An exception consists of a list of values. In most cases, this list
contains a single exception, with an optional stacktrace interface.
Each exception has a mandatory ``value`` argument and optional ``type`` and
``module`` arguments describing the exception class type and module
namespace.
You can also optionally bind a stacktrace interface to an exception. The
spec is identical to ``sentry.interfaces.Stacktrace``.
>>> [{
>>> "type": "ValueError",
>>> "value": "My exception value",
>>> "module": "__builtins__"
>>> "stacktrace": {
>>> # see sentry.interfaces.Stacktrace
>>> }
>>> }]
Values should be sent oldest to newest, this includes both the stacktrace
and the exception itself.
.. note:: This interface can be passed as the 'exception' key in addition
to the full interface path.
"""
attrs = ('values',)
score = 2000
def __init__(self, *args, **kwargs):
if 'values' in kwargs:
values = kwargs['values']
elif not kwargs and len(args) == 1 and isinstance(args[0], (list, tuple)):
values = args[0]
else:
values = [kwargs]
self.values = [SingleException(**e) for e in values]
def __getitem__(self, key):
return self.values[key]
def __iter__(self):
return iter(self.values)
def __len__(self):
return len(self.values)
def validate(self):
for exception in self.values:
# ensure we've got the correct required values
exception.validate()
def serialize(self):
return {
'values': [e.serialize() for e in self.values]
}
def unserialize(self, data):
if 'values' not in data:
data = {'values': [data]}
data['values'] = [unserialize(SingleException, v) for v in data['values']]
return data
def get_hash(self):
return self.values[0].get_hash()
def get_composite_hash(self, interfaces):
return self.values[0].get_composite_hash(interfaces)
def get_context(self, event, is_public=False, **kwargs):
newest_first = is_newest_frame_first(event)
context_kwargs = {
'event': event,
'is_public': is_public,
'newest_first': newest_first,
}
exceptions = []
last = len(self.values) - 1
for num, e in enumerate(self.values):
context = e.get_context(**context_kwargs)
if e.stacktrace:
context['stacktrace'] = e.stacktrace.get_context(
with_stacktrace=False, **context_kwargs)
else:
context['stacktrace'] = {}
context['stack_id'] = 'exception_%d' % (num,)
context['is_root'] = num == last
exceptions.append(context)
if newest_first:
exceptions.reverse()
return {
'newest_first': newest_first,
'system_frames': sum(e['stacktrace'].get('system_frames', 0) for e in exceptions),
'exceptions': exceptions,
'stacktrace': self.get_stacktrace(event, newest_first=newest_first)
}
def to_html(self, event, **kwargs):
if not self.values:
return ''
if len(self.values) == 1 and not self.values[0].stacktrace:
exception = self.values[0]
context = exception.get_context(event=event, **kwargs)
return render_to_string('sentry/partial/interfaces/exception.html', context)
context = self.get_context(event=event, **kwargs)
return render_to_string('sentry/partial/interfaces/chained_exception.html', context)
def to_string(self, event, is_public=False, **kwargs):
return self.get_stacktrace(event, system_frames=False, max_frames=5)
def get_search_context(self, event):
return self.values[0].get_search_context(event)
def get_stacktrace(self, *args, **kwargs):
exc = self.values[0]
if exc.stacktrace:
return exc.stacktrace.get_stacktrace(*args, **kwargs)
return ''
class Http(Interface):
"""
The Request information is stored in the Http interface. Two arguments
are required: ``url`` and ``method``.
The ``env`` variable is a compounded dictionary of HTTP headers as well
as environment information passed from the webserver. Sentry will explicitly
look for ``REMOTE_ADDR`` in ``env`` for things which require an IP address.
The ``data`` variable should only contain the request body (not the query
string). It can either be a dictionary (for standard HTTP requests) or a
raw request body.
>>> {
>>> "url": "http://absolute.uri/foo",
>>> "method": "POST",
>>> "data": {
>>> "foo": "bar"
>>> },
>>> "query_string": "hello=world",
>>> "cookies": "foo=bar",
>>> "headers": {
>>> "Content-Type": "text/html"
>>> },
>>> "env": {
>>> "REMOTE_ADDR": "192.168.0.1"
>>> }
>>> }
.. note:: This interface can be passed as the 'request' key in addition
to the full interface path.
"""
attrs = ('url', 'method', 'data', 'query_string', 'cookies', 'headers',
'env')
display_score = 1000
score = 800
# methods as defined by http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html + PATCH
METHODS = ('GET', 'POST', 'PUT', 'OPTIONS', 'HEAD', 'DELETE', 'TRACE', 'CONNECT', 'PATCH')
def __init__(self, url, method=None, data=None, query_string=None, cookies=None, headers=None, env=None, **kwargs):
if data is None:
data = {}
if method:
method = method.upper()
urlparts = urlparse.urlsplit(url)
if not query_string:
# define querystring from url
query_string = urlparts.query
elif query_string.startswith('?'):
# remove '?' prefix
query_string = query_string[1:]
self.url = '%s://%s%s' % (urlparts.scheme, urlparts.netloc, urlparts.path)
self.method = method
self.data = data
self.query_string = query_string
if cookies:
self.cookies = cookies
else:
self.cookies = {}
# if cookies were a string, convert to a dict
# parse_qsl will parse both acceptable formats:
# a=b&c=d
# and
# a=b; c=d
if isinstance(self.cookies, basestring):
self.cookies = dict(urlparse.parse_qsl(self.cookies, keep_blank_values=True))
# if cookies were [also] included in headers we
# strip them out
if headers and 'Cookie' in headers:
cookies = headers.pop('Cookie')
if cookies:
self.cookies = cookies
self.headers = headers or {}
self.env = env or {}
def serialize(self):
return {
'url': self.url,
'method': self.method,
'data': self.data,
'query_string': self.query_string,
'cookies': self.cookies,
'headers': self.headers,
'env': self.env,
}
def to_string(self, event, is_public=False, **kwargs):
return render_to_string('sentry/partial/interfaces/http.txt', {
'event': event,
'full_url': '?'.join(filter(bool, [self.url, self.query_string])),
'url': self.url,
'method': self.method,
'query_string': self.query_string,
})
def _to_dict(self, value):
if value is None:
value = {}
if isinstance(value, dict):
return True, value
try:
value = QueryDict(value)
except _Exception:
return False, value
else:
return True, value
def to_html(self, event, is_public=False, **kwargs):
data = self.data
headers_is_dict, headers = self._to_dict(self.headers)
# educated guess as to whether the body is normal POST data
if headers_is_dict and headers.get('Content-Type') == 'application/x-www-form-urlencoded' and '=' in data:
_, data = self._to_dict(data)
context = {
'is_public': is_public,
'event': event,
'full_url': '?'.join(filter(bool, [self.url, self.query_string])),
'url': self.url,
'method': self.method,
'data': data,
'query_string': self.query_string,
'headers': self.headers,
}
if not is_public:
# It's kind of silly we store this twice
_, cookies = self._to_dict(self.cookies)
context.update({
'cookies': cookies,
'env': self.env,
})
return render_to_string('sentry/partial/interfaces/http.html', context)
def get_title(self):
return _('Request')
def get_search_context(self, event):
return {
'filters': {
'url': [self.url],
}
}
class Template(Interface):
"""
A rendered template (generally used like a single frame in a stacktrace).
The attributes ``filename``, ``context_line``, and ``lineno`` are required.
>>> {
>>> "abs_path": "/real/file/name.html"
>>> "filename": "file/name.html",
>>> "pre_context": [
>>> "line1",
>>> "line2"
>>> ],
>>> "context_line": "line3",
>>> "lineno": 3,
>>> "post_context": [
>>> "line4",
>>> "line5"
>>> ],
>>> }
.. note:: This interface can be passed as the 'template' key in addition
to the full interface path.
"""
attrs = ('filename', 'context_line', 'lineno', 'pre_context', 'post_context',
'abs_path')
score = 1100
def __init__(self, filename, context_line, lineno, pre_context=None, post_context=None,
abs_path=None, **kwargs):
self.abs_path = abs_path
self.filename = filename
self.context_line = context_line
self.lineno = int(lineno)
self.pre_context = pre_context
self.post_context = post_context
def serialize(self):
return {
'abs_path': self.abs_path,
'filename': self.filename,
'context_line': self.context_line,
'lineno': self.lineno,
'pre_context': self.pre_context,
'post_context': self.post_context,
}
def get_hash(self):
return [self.filename, self.context_line]
def to_string(self, event, is_public=False, **kwargs):
context = get_context(
lineno=self.lineno,
context_line=self.context_line,
pre_context=self.pre_context,
post_context=self.post_context,
filename=self.filename,
format=False,
)
result = [
'Stacktrace (most recent call last):', '',
self.get_traceback(event, context)
]
return '\n'.join(result)
def to_html(self, event, is_public=False, **kwargs):
context = get_context(
lineno=self.lineno,
context_line=self.context_line,
pre_context=self.pre_context,
post_context=self.post_context,
filename=self.filename,
format=True,
)
return render_to_string('sentry/partial/interfaces/template.html', {
'event': event,
'abs_path': self.abs_path,
'filename': self.filename,
'lineno': int(self.lineno),
'start_lineno': context[0][0],
'context': context,
'template': self.get_traceback(event, context),
'is_public': is_public,
})
def get_traceback(self, event, context):
result = [
event.message, '',
'File "%s", line %s' % (self.filename, self.lineno), '',
]
result.extend([n[1].strip('\n') for n in context])
return '\n'.join(result)
def get_search_context(self, event):
return {
'text': [self.abs_path, self.filename, self.context_line],
}
class User(Interface):
"""
An interface which describes the authenticated User for a request.
All data is arbitrary and optional other than the ``id``
field which should be a string representing the user's unique identifier.
>>> {
>>> "id": "unique_id",
>>> "username": "my_user",
>>> "email": "[email protected]"
>>> }
"""
attrs = ('id', 'email', 'username', 'data')
def __init__(self, id=None, email=None, username=None, **kwargs):
self.id = id
self.email = email
self.username = username
self.data = kwargs
def serialize(self):
# XXX: legacy -- delete
if hasattr(self, 'is_authenticated'):
self.data['is_authenticated'] = self.is_authenticated
return {
'id': self.id,
'username': self.username,
'email': self.email,
'data': self.data,
}
def get_hash(self):
return []
def to_html(self, event, is_public=False, **kwargs):
if is_public:
return ''
return render_to_string('sentry/partial/interfaces/user.html', {
'is_public': is_public,
'event': event,
'user_id': self.id,
'user_username': self.username,
'user_email': self.email,
'user_data': self.data,
})
def get_search_context(self, event):
tokens = filter(bool, [self.id, self.username, self.email])
if not tokens:
return {}
return {
'text': tokens
}
|
###############################################################################
#
# Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
{
'name': 'Show photo switch',
'version': '0.1',
'category': 'Product',
'description': '''
Parameter for user to show photo in product form
''',
'author': 'Micronaet S.r.l. - Nicola Riolini',
'website': 'http://www.micronaet.it',
'license': 'AGPL-3',
'depends': [
'base',
'product',
'quotation_photo',
],
'init_xml': [],
'demo': [],
'data': [
'photo_view.xml',
],
'active': False,
'installable': True,
'auto_install': False,
}
|
#!/usr/bin/env python
from __future__ import print_function
import os
import json
from .files_and_paths import Dirs, Urls
from .utils import Utils
from .exp_file_metadata import ExpFileMetadata
class ExpFile(ExpFileMetadata):
def __init__(self, expID=None, fileID=None):
ExpFileMetadata.__init__(self)
self.expID = expID
self.fileID = fileID
# from http://stackoverflow.com/a/682545
@classmethod
def fromJson(cls, expID, fileID, j):
ret = cls(expID, fileID)
ret._parseJson(expID, fileID, j)
return ret
@classmethod
# in case file JSON is not part of the experiment json, for some unknown reason (revoked?)
def fromJsonFile(cls, expID, fileID, force):
ret = cls(expID, fileID)
jsonFnp = os.path.join(Dirs.encode_json, "exps", expID, fileID + ".json")
jsonUrl = Urls.base + "/files/{fileID}/?format=json".format(fileID=fileID)
Utils.ensureDir(jsonFnp)
Utils.download(jsonUrl, jsonFnp, True, force, skipSizeCheck=True)
with open(jsonFnp) as f:
j = json.load(f)
ret._parseJson(expID, fileID, j)
return ret
@classmethod
def fromWebservice(cls, expID, r):
ret = cls(expID, r["file"])
ret.parseWS(r)
return ret
@classmethod
def fromRoadmap(cls, eid, assay_term_name):
ret = cls(eid, eid)
ret.assembly = "hg19"
ret.assay_term_name = assay_term_name
ret.isPooled = True
return ret
def __repr__(self):
return "\t".join([str(x) for x in [self.fileID, self.file_format,
self.output_type,
"bio" + str(self.bio_rep),
"tech" + str(self.tech_rep),
"biological_replicates" +
str(self.biological_replicates),
self.jsonUrl, self.isPooled]])
def isPeaks(self):
return "peaks" == self.output_type
def isReplicatedPeaks(self):
return "replicated peaks" == self.output_type
def isBedNarrowPeak(self):
return "bed narrowPeak" == self.file_type
def isBedBroadPeak(self):
return "bed broadPeak" == self.file_type
def isIDRoptimal(self):
return "optimal idr thresholded peaks" == self.output_type
def isBed(self):
return "bed" == self.file_format
def isBigBed(self):
return "bigBed" == self.file_format
def isBam(self):
return "bam" == self.file_type
def isGtf(self):
return "gtf" == self.file_format
def isHdf5(self):
return "hdf5" == self.file_format
def isBigWig(self):
return "bigWig" == self.file_type
def isSignal(self):
return "signal" == self.output_type
def isRawSignal(self):
return "raw signal" == self.output_type
def isHotSpot(self):
return "hotspots" == self.output_type
def isFoldChange(self):
return "fold change over control" == self.output_type
def isIDR(self):
return "optimal idr thresholded peaks" == self.output_type
def isFastqOrFasta(self):
return "fasta" == self.file_type or "fastq" == self.file_type
def isTAD(self):
return "topologically associated domains" == self.output_type
def isTSV(self):
return "tsv" == self.file_type
def getControls(self):
x = set()
if "derived_from" in self.jsondata:
for i in self.jsondata["derived_from"]:
if "controlled_by" in i:
x.add(i["controlled_by"][0])
return list(x)
def fnp(self, s4s=False):
if self.expID.startswith("EN"):
d = os.path.join(Dirs.encode_data, self.expID)
fn = os.path.basename(self.url)
fnp = os.path.join(d, fn)
if s4s:
fnp = fnp.replace("/project/umw_", "/s4s/s4s_")
return fnp
if "H3K27ac" == self.assay_term_name:
fn = self.expID + "-H3K27ac.fc.signal.bigwig"
elif "DNase-seq" == self.assay_term_name:
fn = self.expID + "-DNase.fc.signal.bigwig"
else:
raise Exception("unknown ROADMAP file type")
return os.path.join(Dirs.roadmap_base, self.expID, fn)
def normFnp(self):
fnp = self.fnp()
fnp = fnp.replace("encode/data/", "encode/norm/")
fnp = fnp.replace("roadmap/data/consolidated",
"roadmap/data/norm/consolidated")
pre, ext = os.path.splitext(fnp)
if ".bigwig" == ext:
ext = ".bigWig"
return pre + ".norm" + ext
def download(self, force=None):
fnp = self.fnp()
Utils.ensureDir(fnp)
return Utils.download(self.url, fnp,
True, force, self.file_size_bytes)
def downloadPublic(self, force=None):
fnp = self.fnp()
Utils.ensureDir(fnp)
return Utils.download(self.url, fnp,
False, force, self.file_size_bytes)
def featurename(self):
return self.fileID
|
#!/usr/bin/env python3
# found some where on internet and added my own stuff to it.
import logging
import socket
import select
import subprocess
HOSTNAME = 'localhost'
PORT = '4000'
MAXIMUM_QUEUED_CONNECTIONS = 5
RECEIVING_BUFFER_SIZE = 4096
logger = logging.getLogger(__name__)
def start_server(hostname, port):
# Get all possible binding addresses for given hostname and port.
possible_addresses = socket.getaddrinfo(
hostname,
port,
family=socket.AF_UNSPEC,
type=socket.SOCK_STREAM,
flags=socket.AI_PASSIVE
)
server_socket = None
# Look for an address that will actually bind.
for family, socket_type, protocol, name, address in possible_addresses:
try:
# Create socket.
server_socket = socket.socket(family, socket_type, protocol)
# Make socket port reusable.
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Bind socket to the address.
server_socket.bind(address)
except OSError:
# Try another address.
continue
break
if server_socket is None:
logger.error("No suitable address available.")
return
# Listen for incoming connections.
server_socket.listen(MAXIMUM_QUEUED_CONNECTIONS)
logger.info("Listening on %s port %d." % server_socket.getsockname()[:2])
monitored_sockets = [server_socket]
try:
while True:
# Wait for any of the monitored sockets to become readable.
ready_to_read_sockets = select.select(
monitored_sockets,
tuple(),
tuple()
)[0]
for ready_socket in ready_to_read_sockets:
if ready_socket == server_socket:
# If server socket is readable, accept new client
# connection.
client_socket, client_address = server_socket.accept()
monitored_sockets.append(client_socket)
logger.info("New connection #%d on %s:%d." % (
client_socket.fileno(),
client_address[0],
client_address[1]
))
else:
message = ready_socket.recv(RECEIVING_BUFFER_SIZE)
if message:
# Client send correct message. Echo it.
if b'lista' in message:
print(message)
lista = subprocess.check_output(["ls", "-l"])
print(lista)
ready_socket.sendall(lista)
if b'long' in message:
print(message)
infile = open('serman/sermanwindow.cc')
lista = infile.readlines()
lista = ', '.join([str(x) for x in lista])
print(lista)
ready_socket.sendall(str.encode(lista))
else:
print(message)
ready_socket.sendall(message)
else:
# Client connection is lost. Handle it.
logger.info(
"Lost connection #%d." % ready_socket.fileno()
)
monitored_sockets.remove(ready_socket)
except KeyboardInterrupt:
pass
logger.info("Shutdown initiated.")
# Close client connections.
monitored_sockets.remove(server_socket)
for client_socket in monitored_sockets:
logger.info("Closing connection #%d." % client_socket.fileno())
client_socket.close()
# Close server socket.
logger.info("Shutting server down...")
server_socket.close()
if __name__ == '__main__':
# Configure logging.
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler())
# Start server.
start_server(HOSTNAME, PORT)
|
# -*- coding: utf-8 -*-
"""
A minimalist klout API interface. Use of this API
requires klout *developer key*. You can get registered and
get a key at
<http://klout.com/s/developers/v2>
Supports Python >= 2.5 and Python 3
====================
Quickstart
====================
Install the PyPi package::
pip install Klout
This short example shows how to get a kloutId first and fetch user's score using that kloutId::
from klout import *
# Make the Klout object
k = Klout('YOUR_KEY_HERE')
# Get kloutId of the user by inputting a twitter screenName
kloutId = k.identity.klout(screenName="erfaan").get('id')
# Get klout score of the user
score = k.user.score(kloutId=kloutId).get('score')
print "User's klout score is: %s" % (score)
# Optionally a timeout parameter (seconds) can also be sent with all calls
score = k.user.score(kloutId=kloutId, timeout=5).get('score')
"""
try:
import urllib.request as urllib_request
import urllib.error as urllib_error
import urllib.parse as urllib_parse
except ImportError:
import urllib2 as urllib_request
import urllib2 as urllib_error
import urllib as urllib_parse
try:
from cStringIO import StringIO
except ImportError:
from io import BytesIO as StringIO
import gzip
try:
import json
except ImportError:
import simplejson as json
import socket
class _DEFAULT(object):
pass
class KloutError( Exception ):
"""
Base Exception thrown by Klout object when there is a
general error interacting with the API.
"""
def __init__(self, e):
self.e = e
def __str__(self):
return repr(self)
def __repr__(self):
return ( "ERROR: %s" % self.e )
class KloutHTTPError( KloutError ):
"""
Exception thrown by Klout object when there is an
HTTP error interacting with api.klout.com.
"""
def __init__( self, e, uri ):
self.e = e
self.uri = uri
class KloutCall( object ):
def __init__(self, key, domain,
callable_cls, api_version = "",
uri = "", uriparts = None, secure=False):
self.key = key
self.domain = domain
self.api_version = api_version
self.callable_cls = callable_cls
self.uri = uri
self.secure = secure
self.uriparts = uriparts
def __getattr__(self, k):
try:
return object.__getattr__(self, k)
except AttributeError:
def extend_call(arg):
return self.callable_cls(
key=self.key, domain=self.domain,
api_version=self.api_version,
callable_cls=self.callable_cls, secure=self.secure,
uriparts=self.uriparts + (arg,))
if k == "_":
return extend_call
else:
return extend_call(k)
def __call__(self, **kwargs):
# Build the uri.
uriparts = []
api_version = self.api_version
resource = "%s.json" % self.uriparts[0]
uriparts.append(api_version)
uriparts.append(resource)
params = {}
if self.key:
params['key'] = self.key
timeout = kwargs.pop('timeout', None)
# append input variables
for k, v in kwargs.items():
if k == 'screenName':
uriparts.append('twitter')
params[k] = v
elif k == 'kloutId':
uriparts.append(str(v))
else:
uriparts.append(k)
uriparts.append(str(v))
for uripart in self.uriparts[1:]:
if not uripart == 'klout':
uriparts.append(str(uripart))
uri = '/'.join(uriparts)
if len(params) > 0:
uri += '?' + urllib_parse.urlencode(params)
secure_str = ''
if self.secure:
secure_str = 's'
uriBase = "http%s://%s/%s" % (
secure_str, self.domain, uri)
headers = {'Accept-Encoding': 'gzip'}
req = urllib_request.Request(uriBase, headers=headers)
return self._handle_response(req, uri, timeout)
def _handle_response(self, req, uri, timeout=None):
kwargs = {}
if timeout:
socket.setdefaulttimeout(timeout)
try:
handle = urllib_request.urlopen(req)
if handle.info().get('Content-Encoding') == 'gzip':
# Handle gzip decompression
buf = StringIO(handle.read())
f = gzip.GzipFile(fileobj=buf)
data = f.read()
else:
data = handle.read()
res = json.loads(data.decode('utf8'))
return res
except urllib_error.HTTPError:
import sys
_, e, _ = sys.exc_info()
raise KloutHTTPError( e, uri)
class Klout(KloutCall):
"""
A minimalist yet fully featured klout API interface.
Get RESTful data by accessing members of this class. The result
is decoded python objects (dicts and lists).
The klout API is documented at:
http://klout.com/s/developers/v2
Examples:
We need a *developer key* to call any Klout API function
>>> f = open('key')
>>> key= f.readline().strip()
>>> f.close()
By default all communication with Klout API is not secure (HTTP).
It can be made secure (HTTPS) by passing an optional `secure=True`
to `Klout` constructor like this:
>>> k = Klout(key, secure=True)
**Identity Resource**
All calls to the Klout API now require a unique kloutId.
To facilitate this, you must first translate a {network}/{networkId} into a kloutId.
* Get kloutId by twitter id
>>> k.identity.klout(tw="11158872")
{u'id': u'11747', u'network': u'ks'}
* Get kloutId by twitter screenName
>>> k.identity.klout(screenName="erfaan")
{u'id': u'11747', u'network': u'ks'}
* Get kloutId by google plus id
>>> k.identity.klout(gp="112975106809988327760")
{u'id': u'11747', u'network': u'ks'}
**User Resource**
Once we have kloutId, we can use this resource to lookup user's score, influcent or topics
* Get user score
>>> k.user.score(kloutId='11747') # doctest: +ELLIPSIS
... # doctest: +NORMALIZE_WHITESPACE
{u'score': ..., u'scoreDelta': {u'dayChange': ..., u'monthChange': ...}}
* Get user influences
>>> k.user.influence(kloutId='11747') # doctest: +ELLIPSIS
... # doctest: +NORMALIZE_WHITESPACE
{u'myInfluencersCount': ..., u'myInfluenceesCount': ..., \
u'myInfluencers': [...], u'myInfluencees': [...]}
* Get user topics
>>> k.user.topics(kloutId='11747') # doctest: +ELLIPSIS
... # doctest: +NORMALIZE_WHITESPACE
[{u'displayName': ..., u'name': ..., u'imageUrl': ..., u'id': ..., u'topicType': ..., u'slug': ...}, ...]
"""
def __init__(
self, key, domain="api.klout.com", secure=False,
api_version=_DEFAULT):
"""
Create a new klout API connector.
Pass a `key` parameter to use::
k = Klout(key='YOUR_KEY_HERE')
`domain` lets you change the domain you are connecting. By
default it's `api.klout.com`
If `secure` is True you will connect with HTTPS instead of
HTTP.
`api_version` is used to set the base uri. By default it's
'v2'.
"""
if api_version is _DEFAULT:
api_version = "v2"
KloutCall.__init__(
self, key=key, domain = domain,
api_version = api_version,
callable_cls=KloutCall, secure=secure,
uriparts=())
__all__ = ["Klout", "KloutError", "KloutHTTPError"]
|
# $Id: selftest.py 1758 2004-03-28 17:36:59Z fredrik $
# -*- coding: iso-8859-1 -*-
# elementtidy selftest program (in progress)
from elementtree import ElementTree
def sanity():
"""
Make sure everything can be imported.
>>> import _elementtidy
>>> from elementtidy.TidyHTMLTreeBuilder import *
"""
HTML1 = "<title>Foo</title><ul><li>Foo!<li>åäö"
XML1 = """\
<html:html xmlns:html="http://www.w3.org/1999/xhtml">
<html:head>
<html:meta content="TIDY" name="generator" />
<html:title>Foo</html:title>
</html:head>
<html:body>
<html:ul>
<html:li>Foo!</html:li>
<html:li>åäö</html:li>
</html:ul>
</html:body>
</html:html>"""
def check(a, b):
import re
a = ElementTree.tostring(ElementTree.XML(a))
a = re.sub("HTML Tidy[^\"]+", "TIDY", a)
a = re.sub("\r\n", "\n", a)
if a != b:
print a
print "Expected:"
print b
def testdriver():
"""
Check basic driver interface.
>>> import _elementtidy
>>> xml, errors = _elementtidy.fixup(HTML1)
>>> check(xml, XML1)
"""
def testencoding():
"""
Check basic driver interface.
>>> import _elementtidy
>>> xml, errors = _elementtidy.fixup(HTML1, 'ascii')
>>> check(xml, XML1)
>>> xml, errors = _elementtidy.fixup(HTML1, 'latin1')
>>> check(xml, XML1)
"""
def xmltoolkit35():
"""
@XMLTOOLKIT35
elementtidy crashes on really broken pages.
>>> import _elementtidy
>>> xml, errors = _elementtidy.fixup("<crash>")
>>> tree = ElementTree.XML(xml)
"""
def xmltoolkit48():
"""
@XMLTOOLKIT48
elementtidy gives up on some pages.
>>> import _elementtidy
>>> html = "<table><form><tr><td>test</td></tr></form></table>"
>>> xml, errors = _elementtidy.fixup(html)
>>> tree = ElementTree.XML(xml)
"""
if __name__ == "__main__":
import doctest, selftest
failed, tested = doctest.testmod(selftest)
print tested - failed, "tests ok."
|
import random
import itertools
rand = 'rand'
roundr = 'roundr'
leastc = 'leastc'
weightr = 'weightr'
weightlc = 'weightlc'
sticky = 'sticky'
def schedulerFactory(lbType, tracker):
"""
A dispatch function for a service's scheduler.
"""
if lbType == rand:
return RandomScheduler(tracker)
elif lbType == roundr:
return RoundRobinScheduler(tracker)
elif lbType == leastc:
return LeastConnsScheduler(tracker)
elif lbType == weightr:
return RandomWeightedScheduler(tracker)
else:
raise ValueError, "Unknown scheduler type `%s'" % lbType
class BaseScheduler(object):
"""
schedulers need the following:
* access to a proxy's hosts
* a proxy's open connections
* the "lastclose" for a host (don't know what that is yet)
"""
def __init__(self, tracker):
self.tracker = tracker
self.tracker.scheduler = self
def hasHost(self):
"""
"""
if self.tracker.available.keys():
return True
return False
class RandomScheduler(BaseScheduler):
"""
Select a random proxied host to receive the next request.
"""
schedulerName = rand
def nextHost(self, clientAddr):
if not self.hasHost():
return
pick = random.choice(self.hosts)
return pick
class RoundRobinScheduler(BaseScheduler):
"""
This scheduler presents a simple algorighm for selecting hosts based on
nothing other than who's next in the list.
"""
schedulerName = roundr
counter = 0
def nextHost(self, clientAddr):
if not self.hasHost():
return
if self.counter >= len(self.tracker.hosts):
self.counter = 0
if self.tracker.hosts:
d = self.tracker.hosts[self.counter]
self.counter += 1
return d
class LeastConnsScheduler(BaseScheduler):
"""
This scheduler passes the connection to the destination with the least
number of current open connections. If multiple machines have the same
number of open connections, send to the least recently used.
"""
schedulerName = leastc
counter = 0
def nextHost(self, clientAddr):
if not self.hasHost():
return
hosts = [(x[1], self.tracker.lastclose.get(x[0],0), x[0])
for x in self.tracker.available.items()]
hosts.sort()
return hosts[0][2]
class RandomWeightedScheduler(BaseScheduler):
"""
This scheduler passes the connection in a semi-random fashion, with the
highest likelihood of selection going to the host with the largest weight
value.
In particular, it uses hosts and their associated weights to build a
"simulated population" of hosts. These to not get place into memory
en-masse, thanks to the existence of iterators. A single host in the
"population" is chosen, with hosts of greater weights being selected more
often (over time).
"""
schedulerName = weightr
def nextHost(self, clientAddr):
if not self.hasHost():
return
group = self.tracker.group
# hosts is a list of (host, port) tuples
# XXX
# this is pretty slow... perhaps the weight data should also be stored
# on the tracker object and we should put the getWeightDistribution and
# getWeights methods on this scheduler...
# XXX
# or we can cache the computed values and refresh them in a tracker
hosts = self.tracker.available.keys()
population = group.getWeightDistribution(hostPorts=hosts)
populationSize = sum([weight for hostPort, weight
in group.getWeights().items() if hostPort in hosts])
index = random.randint(0, populationSize - 1)
return itertools.islice(population, index, None).next()
|
import abc
from typing import Union, Optional, Callable, Type
import h11
from h11._readers import ChunkedReader, ContentLengthReader, Http10Reader
from h11._receivebuffer import ReceiveBuffer
from mitmproxy import exceptions, http
from mitmproxy.net import http as net_http
from mitmproxy.net.http import http1, status_codes
from mitmproxy.net.http.http1 import read_sansio as http1_sansio
from mitmproxy.proxy2 import commands, events, layer
from mitmproxy.proxy2.context import Connection, ConnectionState, Context
from mitmproxy.proxy2.layers.http._base import ReceiveHttp, StreamId
from mitmproxy.proxy2.utils import expect
from mitmproxy.utils import human
from ._base import HttpConnection
from ._events import HttpEvent, RequestData, RequestEndOfMessage, RequestHeaders, RequestProtocolError, ResponseData, \
ResponseEndOfMessage, ResponseHeaders, ResponseProtocolError
TBodyReader = Union[ChunkedReader, Http10Reader, ContentLengthReader]
class Http1Connection(HttpConnection, metaclass=abc.ABCMeta):
stream_id: Optional[StreamId] = None
request: Optional[http.HTTPRequest] = None
response: Optional[http.HTTPResponse] = None
request_done: bool = False
response_done: bool = False
# this is a bit of a hack to make both mypy and PyCharm happy.
state: Union[Callable[[events.Event], layer.CommandGenerator[None]], Callable]
body_reader: TBodyReader
buf: ReceiveBuffer
ReceiveProtocolError: Type[Union[RequestProtocolError, ResponseProtocolError]]
ReceiveData: Type[Union[RequestData, ResponseData]]
ReceiveEndOfMessage: Type[Union[RequestEndOfMessage, ResponseEndOfMessage]]
def __init__(self, context: Context, conn: Connection):
super().__init__(context, conn)
self.buf = ReceiveBuffer()
@abc.abstractmethod
def send(self, event: HttpEvent) -> layer.CommandGenerator[None]:
yield from () # pragma: no cover
@abc.abstractmethod
def read_headers(self, event: events.ConnectionEvent) -> layer.CommandGenerator[None]:
yield from () # pragma: no cover
def _handle_event(self, event: events.Event) -> layer.CommandGenerator[None]:
if isinstance(event, HttpEvent):
yield from self.send(event)
else:
if isinstance(event, events.DataReceived) and self.state != self.passthrough:
self.buf += event.data
yield from self.state(event)
@expect(events.Start)
def start(self, _) -> layer.CommandGenerator[None]:
self.state = self.read_headers
yield from ()
state = start
def read_body(self, event: events.Event) -> layer.CommandGenerator[None]:
assert self.stream_id
while True:
try:
if isinstance(event, events.DataReceived):
h11_event = self.body_reader(self.buf)
elif isinstance(event, events.ConnectionClosed):
h11_event = self.body_reader.read_eof()
else:
raise AssertionError(f"Unexpected event: {event}")
except h11.ProtocolError as e:
yield commands.CloseConnection(self.conn)
yield ReceiveHttp(self.ReceiveProtocolError(self.stream_id, f"HTTP/1 protocol error: {e}"))
return
if h11_event is None:
return
elif isinstance(h11_event, h11.Data):
data: bytes = bytes(h11_event.data)
if data:
yield ReceiveHttp(self.ReceiveData(self.stream_id, data))
elif isinstance(h11_event, h11.EndOfMessage):
assert self.request
if h11_event.headers:
raise NotImplementedError(f"HTTP trailers are not implemented yet.")
if self.request.data.method.upper() != b"CONNECT":
yield ReceiveHttp(self.ReceiveEndOfMessage(self.stream_id))
is_request = isinstance(self, Http1Server)
yield from self.mark_done(
request=is_request,
response=not is_request
)
return
def wait(self, event: events.Event) -> layer.CommandGenerator[None]:
"""
We wait for the current flow to be finished before parsing the next message,
as we may want to upgrade to WebSocket or plain TCP before that.
"""
assert self.stream_id
if isinstance(event, events.DataReceived):
return
elif isinstance(event, events.ConnectionClosed):
# for practical purposes, we assume that a peer which sent at least a FIN
# is not interested in any more data from us, see
# see https://github.com/httpwg/http-core/issues/22
if event.connection.state is not ConnectionState.CLOSED:
yield commands.CloseConnection(event.connection)
yield ReceiveHttp(self.ReceiveProtocolError(self.stream_id, f"Client disconnected.",
code=status_codes.CLIENT_CLOSED_REQUEST))
else: # pragma: no cover
raise AssertionError(f"Unexpected event: {event}")
def done(self, event: events.ConnectionEvent) -> layer.CommandGenerator[None]:
yield from () # pragma: no cover
def make_pipe(self) -> layer.CommandGenerator[None]:
self.state = self.passthrough
if self.buf:
already_received = self.buf.maybe_extract_at_most(len(self.buf))
yield from self.state(events.DataReceived(self.conn, already_received))
self.buf.compress()
def passthrough(self, event: events.Event) -> layer.CommandGenerator[None]:
assert self.stream_id
if isinstance(event, events.DataReceived):
yield ReceiveHttp(self.ReceiveData(self.stream_id, event.data))
elif isinstance(event, events.ConnectionClosed):
if isinstance(self, Http1Server):
yield ReceiveHttp(RequestEndOfMessage(self.stream_id))
else:
yield ReceiveHttp(ResponseEndOfMessage(self.stream_id))
def mark_done(self, *, request: bool = False, response: bool = False) -> layer.CommandGenerator[None]:
if request:
self.request_done = True
if response:
self.response_done = True
if self.request_done and self.response_done:
assert self.request
assert self.response
if should_make_pipe(self.request, self.response):
yield from self.make_pipe()
return
connection_done = (
http1_sansio.expected_http_body_size(self.request, self.response) == -1
or http1.connection_close(self.request.http_version, self.request.headers)
or http1.connection_close(self.response.http_version, self.response.headers)
# If we proxy HTTP/2 to HTTP/1, we only use upstream connections for one request.
# This simplifies our connection management quite a bit as we can rely on
# the proxyserver's max-connection-per-server throttling.
or (self.request.is_http2 and isinstance(self, Http1Client))
)
if connection_done:
yield commands.CloseConnection(self.conn)
self.state = self.done
return
self.request_done = self.response_done = False
self.request = self.response = None
if isinstance(self, Http1Server):
self.stream_id += 2
else:
self.stream_id = None
self.state = self.read_headers
if self.buf:
yield from self.state(events.DataReceived(self.conn, b""))
class Http1Server(Http1Connection):
"""A simple HTTP/1 server with no pipelining support."""
ReceiveProtocolError = RequestProtocolError
ReceiveData = RequestData
ReceiveEndOfMessage = RequestEndOfMessage
stream_id: int
def __init__(self, context: Context):
super().__init__(context, context.client)
self.stream_id = 1
def send(self, event: HttpEvent) -> layer.CommandGenerator[None]:
assert event.stream_id == self.stream_id
if isinstance(event, ResponseHeaders):
self.response = response = event.response
if response.is_http2:
response = response.copy()
# Convert to an HTTP/1 response.
response.http_version = "HTTP/1.1"
# not everyone supports empty reason phrases, so we better make up one.
response.reason = status_codes.RESPONSES.get(response.status_code, "")
# Shall we set a Content-Length header here if there is none?
# For now, let's try to modify as little as possible.
raw = http1.assemble_response_head(response)
yield commands.SendData(self.conn, raw)
elif isinstance(event, ResponseData):
assert self.response
if "chunked" in self.response.headers.get("transfer-encoding", "").lower():
raw = b"%x\r\n%s\r\n" % (len(event.data), event.data)
else:
raw = event.data
if raw:
yield commands.SendData(self.conn, raw)
elif isinstance(event, ResponseEndOfMessage):
assert self.response
if "chunked" in self.response.headers.get("transfer-encoding", "").lower():
yield commands.SendData(self.conn, b"0\r\n\r\n")
yield from self.mark_done(response=True)
elif isinstance(event, ResponseProtocolError):
if not self.response:
resp = http.make_error_response(event.code, event.message)
raw = http1.assemble_response(resp)
yield commands.SendData(self.conn, raw)
yield commands.CloseConnection(self.conn)
else:
raise AssertionError(f"Unexpected event: {event}")
def read_headers(self, event: events.ConnectionEvent) -> layer.CommandGenerator[None]:
if isinstance(event, events.DataReceived):
request_head = self.buf.maybe_extract_lines()
if request_head:
request_head = [bytes(x) for x in request_head] # TODO: Make url.parse compatible with bytearrays
try:
self.request = http1_sansio.read_request_head(request_head)
expected_body_size = http1_sansio.expected_http_body_size(self.request, expect_continue_as_0=False)
except (ValueError, exceptions.HttpSyntaxException) as e:
yield commands.Log(f"{human.format_address(self.conn.peername)}: {e}")
yield commands.CloseConnection(self.conn)
self.state = self.done
return
yield ReceiveHttp(RequestHeaders(self.stream_id, self.request, expected_body_size == 0))
self.body_reader = make_body_reader(expected_body_size)
self.state = self.read_body
yield from self.state(event)
else:
pass # FIXME: protect against header size DoS
elif isinstance(event, events.ConnectionClosed):
buf = bytes(self.buf)
if buf.strip():
yield commands.Log(f"Client closed connection before completing request headers: {buf!r}")
yield commands.CloseConnection(self.conn)
else:
raise AssertionError(f"Unexpected event: {event}")
def mark_done(self, *, request: bool = False, response: bool = False) -> layer.CommandGenerator[None]:
yield from super().mark_done(request=request, response=response)
if self.request_done and not self.response_done:
self.state = self.wait
class Http1Client(Http1Connection):
"""A simple HTTP/1 client with no pipelining support."""
ReceiveProtocolError = ResponseProtocolError
ReceiveData = ResponseData
ReceiveEndOfMessage = ResponseEndOfMessage
def __init__(self, context: Context):
super().__init__(context, context.server)
def send(self, event: HttpEvent) -> layer.CommandGenerator[None]:
if not self.stream_id:
assert isinstance(event, RequestHeaders)
self.stream_id = event.stream_id
self.request = event.request
assert self.stream_id == event.stream_id
if isinstance(event, RequestHeaders):
request = event.request
if request.is_http2:
# Convert to an HTTP/1 request.
request = request.copy() # (we could probably be a bit more efficient here.)
request.http_version = "HTTP/1.1"
if "Host" not in request.headers and request.authority:
request.headers.insert(0, "Host", request.authority)
request.authority = ""
raw = http1.assemble_request_head(request)
yield commands.SendData(self.conn, raw)
elif isinstance(event, RequestData):
assert self.request
if "chunked" in self.request.headers.get("transfer-encoding", "").lower():
raw = b"%x\r\n%s\r\n" % (len(event.data), event.data)
else:
raw = event.data
if raw:
yield commands.SendData(self.conn, raw)
elif isinstance(event, RequestEndOfMessage):
assert self.request
if "chunked" in self.request.headers.get("transfer-encoding", "").lower():
yield commands.SendData(self.conn, b"0\r\n\r\n")
elif http1_sansio.expected_http_body_size(self.request, self.response) == -1:
yield commands.CloseConnection(self.conn, half_close=True)
yield from self.mark_done(request=True)
elif isinstance(event, RequestProtocolError):
yield commands.CloseConnection(self.conn)
return
else:
raise AssertionError(f"Unexpected event: {event}")
def read_headers(self, event: events.ConnectionEvent) -> layer.CommandGenerator[None]:
if isinstance(event, events.DataReceived):
if not self.request:
# we just received some data for an unknown request.
yield commands.Log(f"Unexpected data from server: {bytes(self.buf)!r}")
yield commands.CloseConnection(self.conn)
return
assert self.stream_id
response_head = self.buf.maybe_extract_lines()
if response_head:
response_head = [bytes(x) for x in response_head] # TODO: Make url.parse compatible with bytearrays
try:
self.response = http1_sansio.read_response_head(response_head)
expected_size = http1_sansio.expected_http_body_size(self.request, self.response)
except (ValueError, exceptions.HttpSyntaxException) as e:
yield commands.CloseConnection(self.conn)
yield ReceiveHttp(ResponseProtocolError(self.stream_id, f"Cannot parse HTTP response: {e}"))
return
yield ReceiveHttp(ResponseHeaders(self.stream_id, self.response, expected_size == 0))
self.body_reader = make_body_reader(expected_size)
self.state = self.read_body
yield from self.state(event)
else:
pass # FIXME: protect against header size DoS
elif isinstance(event, events.ConnectionClosed):
if self.conn.state & ConnectionState.CAN_WRITE:
yield commands.CloseConnection(self.conn)
if self.stream_id:
if self.buf:
yield ReceiveHttp(ResponseProtocolError(self.stream_id,
f"unexpected server response: {bytes(self.buf)!r}"))
else:
# The server has closed the connection to prevent us from continuing.
# We need to signal that to the stream.
# https://tools.ietf.org/html/rfc7231#section-6.5.11
yield ReceiveHttp(ResponseProtocolError(self.stream_id, "server closed connection"))
else:
return
else:
raise AssertionError(f"Unexpected event: {event}")
def should_make_pipe(request: net_http.Request, response: net_http.Response) -> bool:
if response.status_code == 101:
return True
elif response.status_code == 200 and request.method.upper() == "CONNECT":
return True
else:
return False
def make_body_reader(expected_size: Optional[int]) -> TBodyReader:
if expected_size is None:
return ChunkedReader()
elif expected_size == -1:
return Http10Reader()
else:
return ContentLengthReader(expected_size)
__all__ = [
"Http1Client",
"Http1Server",
]
|
import mock
import unittest
import tempfile
from .helper import _ResourceMixin
class DisputeTest(_ResourceMixin, unittest.TestCase):
def _getTargetClass(self):
from .. import Dispute
return Dispute
def _getCollectionClass(self):
from .. import Collection
return Collection
def _getLazyCollectionClass(self):
from .. import LazyCollection
return LazyCollection
def _makeOne(self):
return self._getTargetClass().from_data({
'object': 'dispute',
'id': 'dspt_test',
'livemode': False,
'location': '/disputes/dspt_test',
'amount': 100000,
'currency': 'thb',
'status': 'open',
'message': None,
'charge': 'chrg_test',
'created': '2015-03-23T05:24:39Z'
})
@mock.patch('requests.get')
def test_retrieve(self, api_call):
class_ = self._getTargetClass()
self.mockResponse(api_call, """{
"object": "dispute",
"id": "dspt_test",
"livemode": false,
"location": "/disputes/dspt",
"amount": 100000,
"currency": "thb",
"status": "pending",
"message": null,
"charge": "chrg_test",
"created": "2015-03-23T05:24:39Z"
}""")
dispute = class_.retrieve('dspt_test')
self.assertTrue(isinstance(dispute, class_))
self.assertEqual(dispute.id, 'dspt_test')
self.assertEqual(dispute.amount, 100000)
self.assertEqual(dispute.currency, 'thb')
self.assertEqual(dispute.status, 'pending')
self.assertEqual(dispute.charge, 'chrg_test')
self.assertEqual(dispute.message, None)
self.assertRequest(
api_call,
'https://api.omise.co/disputes/dspt_test')
self.mockResponse(api_call, """{
"object": "dispute",
"id": "dspt_test",
"livemode": false,
"location": "/disputes/dspt_test",
"amount": 100000,
"currency": "thb",
"status": "pending",
"message": "Foobar Baz",
"charge": "chrg_test",
"created": "2015-03-23T05:24:39Z"
}""")
dispute.reload()
self.assertEqual(dispute.message, 'Foobar Baz')
@mock.patch('requests.get')
def test_retrieve_no_args(self, api_call):
class_ = self._getTargetClass()
collection_class_ = self._getCollectionClass()
self.mockResponse(api_call, """{
"object": "list",
"from": "1970-01-01T07:00:00+07:00",
"to": "2015-03-23T05:24:39+07:00",
"offset": 0,
"limit": 20,
"total": 1,
"data": [
{
"object": "dispute",
"id": "dspt_test",
"livemode": false,
"location": "/disputes/dspt_test",
"amount": 100000,
"currency": "thb",
"status": "pending",
"message": "Foobar Baz",
"charge": "chrg_test",
"created": "2015-03-23T05:24:39Z"
}
]
}""")
disputes = class_.retrieve()
self.assertTrue(isinstance(disputes, collection_class_))
self.assertTrue(isinstance(disputes[0], class_))
self.assertTrue(disputes[0].id, 'dspt_test')
self.assertTrue(disputes[0].amount, 100000)
self.assertRequest(api_call, 'https://api.omise.co/disputes')
@mock.patch('requests.get')
def test_retrieve_kwargs(self, api_call):
class_ = self._getTargetClass()
collection_class_ = self._getCollectionClass()
self.mockResponse(api_call, """{
"object": "list",
"from": "1970-01-01T07:00:00+07:00",
"to": "2015-03-23T05:24:39+07:00",
"offset": 0,
"limit": 20,
"total": 1,
"data": [
{
"object": "dispute",
"id": "dspt_test",
"livemode": false,
"location": "/disputes/dspt_test",
"amount": 100000,
"currency": "thb",
"status": "closed",
"message": "Foobar Baz",
"charge": "chrg_test",
"created": "2015-03-23T05:24:39Z"
}
]
}""")
disputes = class_.retrieve('closed')
self.assertTrue(isinstance(disputes, collection_class_))
self.assertTrue(isinstance(disputes[0], class_))
self.assertTrue(disputes[0].id, 'dspt_test')
self.assertTrue(disputes[0].status, 'closed')
self.assertRequest(api_call, 'https://api.omise.co/disputes/closed')
@mock.patch('requests.get')
def test_list(self, api_call):
class_ = self._getTargetClass()
lazy_collection_class_ = self._getLazyCollectionClass()
self.mockResponse(api_call, """{
"object": "list",
"from": "1970-01-01T07:00:00+07:00",
"to": "2015-03-23T05:24:39+07:00",
"offset": 0,
"limit": 20,
"total": 1,
"data": [
{
"object": "dispute",
"id": "dspt_test",
"livemode": false,
"location": "/disputes/dspt_test",
"amount": 100000,
"currency": "thb",
"status": "pending",
"message": "Foobar Baz",
"charge": "chrg_test",
"created": "2015-03-23T05:24:39Z"
}
]
}""")
disputes = class_.list()
self.assertTrue(isinstance(disputes, lazy_collection_class_))
disputes = list(disputes)
self.assertTrue(isinstance(disputes[0], class_))
self.assertTrue(disputes[0].id, 'dspt_test')
self.assertTrue(disputes[0].amount, 100000)
@mock.patch('requests.patch')
def test_update(self, api_call):
dispute = self._makeOne()
class_ = self._getTargetClass()
self.mockResponse(api_call, """{
"object": "dispute",
"id": "dspt_test",
"livemode": false,
"location": "/disputes/dspt_test",
"amount": 100000,
"currency": "thb",
"status": "pending",
"message": "Foobar Baz",
"charge": "chrg_test",
"created": "2015-03-23T05:24:39Z"
}""")
self.assertTrue(isinstance(dispute, class_))
self.assertEqual(dispute.message, None)
dispute.message = 'Foobar Baz'
dispute.update()
self.assertEqual(dispute.message, 'Foobar Baz')
self.assertRequest(
api_call,
'https://api.omise.co/disputes/dspt_test',
{'message': 'Foobar Baz'}
)
@mock.patch('requests.patch')
def test_accept(self, api_call):
dispute = self._makeOne()
class_ = self._getTargetClass()
self.mockResponse(api_call, """{
"object": "dispute",
"id": "dspt_test",
"livemode": false,
"status": "lost"
}""")
self.assertTrue(isinstance(dispute, class_))
self.assertEqual(dispute.status, 'open')
dispute.accept()
self.assertEqual(dispute.status, 'lost')
self.assertRequest(
api_call,
'https://api.omise.co/disputes/dspt_test/accept'
)
@mock.patch('requests.get')
@mock.patch('requests.post')
def test_upload_document(self, api_call, reload_call):
dispute = self._makeOne()
class_ = self._getTargetClass()
self.mockResponse(api_call, """{
"object": "document",
"livemode": false,
"id": "docu_test",
"deleted": false,
"filename": "evidence.png",
"location": "/disputes/dspt_test/documents/docu_test",
"download_uri": null,
"created_at": "2021-02-05T10:40:32Z"
}""")
self.mockResponse(reload_call, """{
"object": "dispute",
"id": "dspt_test",
"livemode": false,
"location": "/disputes/dspt_test",
"currency": "THB",
"amount": 1101000,
"funding_amount": 1101000,
"funding_currency": "THB",
"metadata": {
},
"charge": "chrg_test_5m7wj8yi1pa9vlk9bq8",
"documents": {
"object": "list",
"data": [
{
"object": "document",
"livemode": false,
"id": "docu_test",
"deleted": false,
"filename": "evidence.png",
"location": "/disputes/dspt_test/documents/docu_test",
"download_uri": null,
"created_at": "2021-02-05T10:40:32Z"
}
],
"limit": 20,
"offset": 0,
"total": 1,
"location": "/disputes/dspt_test/documents",
"order": "chronological",
"from": "1970-01-01T00:00:00Z",
"to": "2021-02-05T10:42:02Z"
},
"transactions": [
{
"object": "transaction",
"id": "trxn_test",
"livemode": false,
"currency": "THB",
"amount": 1101000,
"location": "/transactions/trxn_test",
"direction": "debit",
"key": "dispute.started.debit",
"origin": "dspt_test",
"transferable_at": "2021-02-04T12:08:04Z",
"created_at": "2021-02-04T12:08:04Z"
}
],
"admin_message": null,
"message": null,
"reason_code": "goods_or_services_not_provided",
"reason_message": "Services not provided or Merchandise not received",
"status": "open",
"closed_at": null,
"created_at": "2021-02-04T12:08:04Z"
}""")
self.assertTrue(isinstance(dispute, class_))
files = tempfile.TemporaryFile()
document = dispute.upload_document(files)
files.close()
self.assertEqual(dispute.id, 'dspt_test')
self.assertEqual(document.filename, 'evidence.png')
self.assertUpload(api_call, 'https://api.omise.co/disputes/dspt_test/documents', files)
|
from __future__ import division
from phenix.command_line import superpose_pdbs
from iotbx import pdb
from iotbx.pdb import fetch
from libtbx import easy_run
from libtbx.utils import Sorry
import shutil
import tempfile
import os,sys
def run(fn):
''' '''
# Test if FAB
# Devide to
pdb_hierarchy_var_H,pdb_hierarchy_const_H = get_pdb_protions(pdb_file_name='1bbd',chain_ID='H',limit=113)
pdb_hierarchy_var_L,pdb_hierarchy_const_L = get_pdb_protions(pdb_file_name='1bbd',chain_ID='L',limit=103)
sites_var_heavy,sites_const_heavy,selection_var_H,selection_const_H,pdb_hierarchy = get_sites_protions(pdb_file_name='1bbd',chain_ID='H',limit=113)
sites_var_light,sites_const_light,selection_var_L,selection_const_L,pdb_hierarchy = get_sites_protions(pdb_file_name='1bbd',chain_ID='L',limit=107)
def get_file(fn):
if not os.path.isfile(fn + '.pdb'):
sf_fn = fetch.get_pdb (fn,data_type='pdb',mirror='rcsb',log=sys.stdout)
def set_work_folder():
if sys.platform.startswith('win'):
wrokpath = r'C:\Phenix\Dev\Work\work\FAB'
else:
workpath = '~youval/Work/work/FAB'
os.chdir(wrokpath)
def check_pdb_file_name(file_name):
tmp = os.path.basename(file_name)
tmp = tmp.split('.')
assert len(tmp[0])==4
if len(tmp)==2 and tmp[1]=='pdb':
fn = file_name
else:
fn = tmp[0] + '.pdb'
return fn
def get_pdb_protions(pdb_file_name,chain_ID,limit):
'''(str,str,int) -> pdb_hierarchy,pdb_hierarchy
create a pdb_hierarchy from pdb_file_name, takes a chain,
with chain_ID, and devides it to two, at the limit position.
Example:
>>>pdb_heavy_var, pdb_heavy_const = get_pdb_protions(pdb_file_name='1bbd',chain_ID='H',limit=113)
Arguments:
----------
pdb_file_name : pdb file name
chain_ID : PDB chain ID
limit : the cutoff between the Variable and the Constant FAB domains
Returns:
--------
pdb_hierarchy_var : 0 to limit portion of the pdb_hierarchy
pdb_hierarchy_const : limit to end portion of the pdb_hierarchy
'''
fn = check_pdb_file_name(pdb_file_name)
pdb_hierarchy = pdb.hierarchy.input(file_name=fn).hierarchy
chains = pdb_hierarchy.models()[0].chains()
chain_names = [x.id for x in chains]
# check if correct name is given and find the correct chain
if chain_ID in chain_names:
# get the chain residue group, to check its length
indx = chain_names.index(chain_ID)
# get the chain with the chain_ID and index indx
chain_res = pdb_hierarchy.models()[0].chains()[indx].residue_groups()
chain_length = len(chain_res)
selection_var = 'chain {0} resseq {1}:{2}'.format(chain_ID,1,limit)
selection_const = 'chain {0} resseq {1}:{2}'.format(chain_ID,limit,chain_length)
pdb_hierarchy_var = pdb_hierarchy.atom_selection_cache().selection(selection_var)
pdb_hierarchy_const = pdb_hierarchy.atom_selection_cache().selection(selection_const)
else:
raise Sorry('The is not chain with {0} name in {1}'.format(chain_ID,fn))
return pdb_hierarchy_var,pdb_hierarchy_const
def get_sites_protions(pdb_file_name,chain_ID,limit):
'''(str,str,int) -> pdb_hierarchy,pdb_hierarchy
create a pdb_hierarchy from pdb_file_name, takes a chain,
with chain_ID, and devides it to two, at the limit position.
Example:
>>>pdb_heavy_var, pdb_heavy_const = get_pdb_protions(pdb_file_name='1bbd',chain_ID='H',limit=113)
Arguments:
----------
pdb_file_name : pdb file name
chain_ID : PDB chain ID
limit : the cutoff between the Variable and the Constant FAB domains
Returns:
--------
sites_var,sites_const
sites_var : atoms sites of 0 to limit portion of the pdb_hierarchy
sites_const : atoms sites of limit to end portion of the pdb_hierarchy
'''
fn = check_pdb_file_name(pdb_file_name)
pdb_inp = pdb.input(file_name=fn)
pdb_hierarchy = pdb_inp.construct_hierarchy()
xrs = pdb_inp.xray_structure_simple()
sites_cart_all = xrs.sites_cart()
chains = pdb_hierarchy.models()[0].chains()
chain_names = [x.id for x in chains]
# check if correct name is given and find the correct chain
if chain_ID in chain_names:
# get the chain residue group, to check its length
indx = chain_names.index(chain_ID)
# get the chain with the chain_ID and index indx
chain_res = pdb_hierarchy.models()[0].chains()[indx].residue_groups()
chain_length = len(chain_res)
selection_var = 'chain {0} resseq {1}:{2}'.format(chain_ID,1,limit)
selection_const = 'chain {0} resseq {1}:{2}'.format(chain_ID,limit,chain_length)
pdb_var_selection = pdb_hierarchy.atom_selection_cache().selection(string=selection_var)
pdb_const_selection = pdb_hierarchy.atom_selection_cache().selection(string=selection_const)
# get atoms
params = superpose_pdbs.master_params.extract()
x = superpose_pdbs.manager(
params,
log='log.txt',
pdb_hierarchy_moving=pdb_const_selection,
pdb_hierarchy_fixed=pdb_var_selection)
sites_var = sites_cart_all.select(pdb_var_selection)
sites_const = sites_cart_all.select(pdb_const_selection)
chain = chain_res = pdb_hierarchy.models()[0].chains()[indx]
x1 = superpose_pdbs.manager.extract_sequence_and_sites_chain(chain,'resseq 0:113')
x2 = superpose_pdbs.manager.extract_sequence_and_sites_chain(chain,'resseq 113:190')
else:
raise Sorry('The is not chain with {0} name in {1}'.format(chain_ID,fn))
return sites_var,sites_const,selection_var,selection_const
class FAB_elbow_angle(object):
def __init__(self,
file_nam,
chain_name_light,
chain_name_heavy,
limit_light=107,
limit_heavy=113):
'''Get elbow angle for Fragment antigen-binding (Fab)'''
if __name__=='__main__':
fn = '1bbd'
set_work_folder()
get_file(fn)
run(fn)
print 'Done'
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author igor
# Created by iFantastic on 16-6-14
'''
Computing User Profiles with Spark
data:
/data/tracks.csv
/data/cust.csv
'''
import os
import csv
# os.environ["PYSPARK_PYTHON"] = "/home/igor/anaconda3/bin/ipython"
# os.environ["PYSPARK_DRIVER_PYTHON"] = "python3"
try:
from pyspark import SparkContext
from pyspark import SparkConf
from pyspark.mllib.stat import Statistics
except ImportError as e:
print("Error importing Spark Modules", e)
TRACKS_PATH = '/data/tracks.csv'
CUST_PATH = '/data/cust.csv'
def make_tracks_kv(str):
l = str.split(",")
return [l[1], [[int(l[2]), l[3], int(l[4]), l[5]]]]
def compute_stats_byuser(tracks):
mcount = morn = aft = eve = night = 0
tracklist = []
for t in tracks:
trackid, dtime, mobile, zip_code = t
if trackid not in tracklist:
tracklist.append(trackid)
d, t = dtime.split(" ")
hourofday = int(t.split(":")[0])
mcount += mobile
if (hourofday < 5):
night += 1
elif (hourofday < 12):
morn += 1
elif (hourofday < 17):
aft += 1
elif (hourofday < 22):
eve += 1
else:
night += 1
return [len(tracklist), morn, aft, eve, night, mcount]
def main():
conf = SparkConf()
conf.setMaster("spark://192.168.199.123:8070")
conf.setAppName("User Profile Spark")
sc = SparkContext(conf=conf)
print("connection sucessed with Master", conf)
data = [1, 2, 3, 4]
distData = sc.parallelize(data)
print(distData.collect())
#
raw = open(TRACKS_PATH, 'r').read().split("\n")
tackfile = sc.parallelize(raw)
tackfile = tackfile.filter(lambda line: len(line.split(',')) == 6)
tbycust = tackfile.map(lambda line: make_tracks_kv(line)).reduceByKey(lambda a, b: a + b)
custdata = tbycust.mapValues(lambda a: compute_stats_byuser(a))
print(custdata.first())
# # compute aggreage stats for entire track history
# # aggdata = Statistics.colStats(custdata.map(lambda x: x[1]))
# #
# # print(aggdata)
# print("SUCCESS")
if __name__ == '__main__':
main()
|
from __future__ import unicode_literals
import sys
import functools
import json
try:
import jsonschema
except ImportError:
jsonschema = None
try:
import requests
except ImportError:
requests = None
__version__ = '1.0.0.dev1'
__all__ = ['ensure', 'JsonProbe']
# --------------
# Py2 compat
# --------------
PY2 = sys.version_info[0] == 2
if PY2:
string_types = (str, unicode)
else:
string_types = (str,)
# --------------
class JsonProbe(object):
"""
An instance that knows how to perform validations against json-schema.
"""
_jsonschema = jsonschema
def __init__(self, schema):
"""
:param schema: json-schema as json-encoded text or python datastructures.
"""
if self._jsonschema is None:
raise TypeError('Missing dependency `jsonschema`.')
self.schema = self._normalize_input(schema)
def validate(self, input):
"""
Validate `input` agains the given schema.
:param input: json-encoded text or python datastructures.
:returns: boolean
"""
data = self._normalize_input(input)
try:
jsonschema.validate(data, self.schema)
except self._jsonschema.ValidationError:
return False
else:
return True
def _normalize_input(self, input):
"""
Always return python datastructures.
:param input: json-encoded text or python datastructures.
"""
if isinstance(input, string_types):
return json.loads(input)
else:
return input
def ensure(probe):
"""
Decorator that asserts the returned value is valid against `probe`.
"""
def ensure_decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
result = f(*args, **kwargs)
if probe.validate(result):
return result
else:
raise TypeError('Returned data does not conform with the given schema.')
return wrapper
return ensure_decorator
class TestCaseMixin(object):
def assertSchemaIsValid(self, probe, resource_url, msg=None):
api_sample = requests.get(resource_url)
if not probe.validate(api_sample.json()):
raise self.failureException(msg or 'Schema is invalid.')
|
import re
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
VERSION_REGEX = re.compile(b'''
^
release
\s*
=
\s*
['"]
(?P<version>
[^'"]+
)
['"]
\s*
$
''', re.VERBOSE)
def get_version():
with open('docs/conf.py', 'rb') as f:
for line in f:
match = VERSION_REGEX.search(line)
if match:
return match.group('version').decode('utf-8')
raise AssertionError('version not specified')
def get_long_description():
with open('README.rst', 'rb') as f:
return f.read().decode('utf-8')
setup(
name='unittest_expander',
version=get_version(),
py_modules=['unittest_expander'],
author='Jan Kaliszewski (zuo)',
author_email='[email protected]',
description='Easy and flexible unittest parameterization.',
long_description=get_long_description(),
keywords='unittest testing parameterization parametrization',
url='https://github.com/zuo/unittest_expander',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Topic :: Software Development :: Testing',
],
)
|
"""
Plugin to scrape prometheus endpoint
"""
# This file uses 'print' as a function rather than a statement, a la Python3
from __future__ import print_function
import math
import requests
# import prometheus client dependency dynamically
from monasca_agent.common import util
from requests import RequestException
try:
import prometheus_client.parser as prometheus_client_parser
except ImportError:
prometheus_client_parser = None
# stdlib
import logging
from datetime import datetime
import calendar
# project
import monasca_agent.collector.checks.utils as utils
import monasca_agent.collector.checks.services_checks as services_checks
import monasca_agent.common.exceptions as exceptions
log = logging.getLogger(__name__)
class Prometheus(services_checks.ServicesCheck):
"""
Collect metrics and events
"""
def __init__(self, name, init_config, agent_config, instances=None):
super(Prometheus, self).__init__(name, init_config, agent_config, instances)
# last time of polling
self._last_ts = {}
self._publisher = utils.DynamicCheckHelper(self)
self._config = {}
for inst in instances:
url = inst['url']
# for Prometheus federation URLs, set the name match filter according to the mapping
if url.endswith('/federate'):
mapped_metrics = self._publisher.get_mapped_metrics(inst)
url += '?match[]={__name__=~"' + ("|".join(mapped_metrics) + '"')
for key, value in inst.get('match_labels', {}).items():
if isinstance(value, list):
url += ',{}=~"{}"'.format(key, "|".join(value))
else:
url += ',{}=~"{}"'.format(key, value)
url += '}'
log.info("Fetching from Prometheus federation URL: %s", url)
self._config[inst['name']] = {'url': url, 'timeout': int(inst.get('timeout', 5)),
'collect_response_time': bool(inst.get('collect_response_time', False))}
def _check(self, instance):
if prometheus_client_parser is None:
self.log.error("Skipping prometheus plugin check due to missing 'prometheus_client' module.")
return
self._update_metrics(instance)
# overriding method to catch Infinity exception
def get_metrics(self, prettyprint=False):
"""Get all metrics, including the ones that are tagged.
@return the list of samples
@rtype list of Measurement objects from monasca_agent.common.metrics
"""
try:
return super(Prometheus, self).get_metrics(prettyprint)
except exceptions.Infinity as ex:
# self._disabledMetrics.append(metric_name)
self.log.exception("Caught infinity exception in prometheus plugin.")
if not prettyprint:
self.log.error("More dimensions needs to be mapped in order to resolve clashing measurements")
return self.get_metrics(True)
else:
self.rate('monasca.agent.mapping_errors', 1, dimensions={'agent_check': 'prometheus',
'metric': ex.metric})
return []
@staticmethod
def _convert_timestamp(timestamp):
# convert from string '2016-03-16T16:48:59.900524303Z' to a float monasca can handle 164859.900524
# conversion using strptime() works only for 6 digits in microseconds so the timestamp is limited to
# 26 characters
ts = datetime.strptime(timestamp[:25] + timestamp[-1], "%Y-%m-%dT%H:%M:%S.%fZ")
return calendar.timegm(datetime.timetuple(ts))
def _update_container_metrics(self, instance, metric_name, container, timestamp=None,
fixed_dimensions=None):
# TBD determine metric from Prometheus input
labels = container[1]
value = float(container[2])
if math.isnan(value):
self.log.debug('filtering out NaN value provided for metric %s{%s}', metric_name, labels)
return
self._publisher.push_metric(instance,
metric=metric_name,
value=value,
labels=labels,
timestamp=timestamp,
fixed_dimensions=fixed_dimensions)
def _retrieve_and_parse_metrics(self, url, timeout, collect_response_time, instance_name):
"""
Metrics from prometheus come in plain text from the endpoint and therefore need to be parsed.
To do that the prometheus client's text_string_to_metric_families -method is used. That method returns a
generator object.
The method consumes the metrics from the endpoint:
# HELP container_cpu_system_seconds_total Cumulative system cpu time consumed in seconds.
# TYPE container_cpu_system_seconds_total counter
container_cpu_system_seconds_total{id="/",name="/"} 1.59578817e+06
....
and produces a metric family element with (returned from generator) with the following attributes:
name -> e.g. ' container_cpu_system_seconds_total '
documentation -> e.g. ' container_cpu_system_seconds_total Cumulative system cpu time consumed in seconds. '
type -> e.g. ' counter '
samples -> e.g. ' [.. ,("container_cpu_system_seconds_total", {id="/",name="/"}, 1.59578817e+06),
('container_cpu_system_seconds_total', {u'id': u'/docker', u'name': u'/docker'},
922.66),
..] '
:param url: the url of the prometheus metrics
:return: metric_families iterable
"""
timer = util.Timer()
try:
response = requests.get(url, timeout=timeout)
# report response time first, even when there is HTTP errors
if collect_response_time:
# Stop the timer as early as possible
running_time = timer.total()
self.gauge('monasca.agent.check_collect_time', running_time, dimensions={'agent_check': 'prometheus',
'instance': instance_name})
response.raise_for_status()
body = response.text
except RequestException:
self.log.exception("Retrieving metrics from endpoint %s failed", url)
self.rate('monasca.agent.check_collect_errors', 1, dimensions={'agent_check': 'prometheus',
'instance': instance_name})
return []
metric_families = prometheus_client_parser.text_string_to_metric_families(body)
return metric_families
def _update_metrics(self, instance):
cfg = self._config[instance['name']]
metric_families_generator = self._retrieve_and_parse_metrics(cfg['url'], cfg['timeout'],
cfg['collect_response_time'], instance['name'])
for metric_family in metric_families_generator:
container = None
try:
for container in metric_family.samples:
# currently there is no support for detecting metric types from P8S
self._update_container_metrics(instance, metric_family.name, container)
except Exception as e:
self.log.warning("Unable to collect metric: {0} for container: {1} . - {2} ".format(
metric_family.name, container[1].get('name'), repr(e)))
self.rate('monasca.agent.check_collect_errors', 1, dimensions={'agent_check': 'prometheus',
'instance': instance['name']})
def _update_last_ts(self, instance_name):
utc_now = datetime.utcnow()
self._last_ts[instance_name] = utc_now.isoformat('T')
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
#
# Unit test for the HardwareSwitch module.
#
# Copyright (c) 2015 carlosperate https://github.com/carlosperate/
#
# Licensed under The MIT License (MIT), a copy can be found in the LICENSE file
#
# These test require the Wemo Switch to be on the network at the defined IP
# address.
#
from __future__ import unicode_literals, absolute_import
import io
import mock
import unittest
from time import sleep
try:
import LightUpHardware.HardwareSwitch as HardwareSwitch
from LightUpHardware.pywemoswitch.WemoSwitch import WemoSwitch
except ImportError:
import os
import sys
file_dir = os.path.dirname(os.path.realpath(__file__))
package_dir = os.path.dirname(os.path.dirname(file_dir))
sys.path.insert(0, package_dir)
import LightUpHardware.HardwareSwitch as HardwareSwitch
from LightUpHardware.pywemoswitch.WemoSwitch import WemoSwitch
class HardwareSwitchTestCase(unittest.TestCase):
"""
Tests for HardwareSwitch functions.
These test require the Wemo Switch to be on the network at the defined IP
address.
"""
#
# Helper methods
#
def assert_stderr(self, test_srderr, equal=False):
""" Checks the stderr error string and resets it for next test. """
if equal is True:
self.assertEqual(test_srderr.getvalue(), '')
else:
self.assertNotEqual(test_srderr.getvalue(), '')
test_srderr.truncate(0)
test_srderr.write('')
self.assertEqual(test_srderr.getvalue(), '')
#
# Tests
#
def test__get_switch(self):
"""
Tests if an error is set when a switch cannot be connected. Due to the
connection timeout this test can take several seconds to complete.
"""
# We capture stderr to check for invalid input IP
with mock.patch('sys.stderr', new=io.StringIO()) as test_srderr:
# Invalid _coffee_switch_name causes to print an error
switch = HardwareSwitch._get_switch('127.0.0.1')
self.assert_stderr(test_srderr)
self.assertIsNone(switch)
# Test that the default IP returns a connected switch instance
switch = HardwareSwitch._get_switch()
self.assertEqual(type(switch), WemoSwitch)
def test_switch_on_off(self):
"""
Tests the switch Turns ON and OFF with the default input and a given
switch.
"""
state = HardwareSwitch.switch_on()
self.assertTrue(state)
sleep(1)
state = HardwareSwitch.switch_off()
self.assertFalse(state)
switch = HardwareSwitch._get_switch()
state = HardwareSwitch.switch_on(switch)
self.assertTrue(state)
sleep(1)
state = HardwareSwitch.switch_off(switch)
self.assertFalse(state)
def test_safe_on(self):
""" Tests the default switch Turns ON only if already ON. """
switch = HardwareSwitch._get_switch()
switch_is_on = switch.get_state()
if switch_is_on is True:
switch.turn_off()
switch_is_on = switch.get_state()
self.assertFalse(switch_is_on)
HardwareSwitch.safe_on()
switch_is_on = switch.get_state()
self.assertTrue(switch_is_on)
# We capture stderr to check for swtich already ON when called and
# mock the turn off method to check if it was called
with mock.patch('sys.stderr', new=io.StringIO()) as test_srderr:
with mock.patch('LightUpHardware.pywemoswitch.WemoSwitch') as \
mock_switch:
self.assert_stderr(test_srderr, True)
HardwareSwitch.safe_on()
self.assertEqual(mock_switch.turn_off.call_count, 0)
self.assert_stderr(test_srderr)
switch_is_on = switch.get_state()
self.assertTrue(switch_is_on)
# to clean up, turn the switch off
sleep(1)
switch.turn_off()
if __name__ == '__main__':
unittest.main()
|
import os
import json
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
#from mhacks.equities import Field
EQUITY_MAP = {
'AAPL': 'AAPL US EQUITY'
}
def home_page(request):
return render(request, 'home.html')
def uber_page(request):
return render(request, 'final_uber.html')
def enter_page(request):
return render(request, 'enter.html')
def airline_page(request):
return render(request, 'flightanimation.html')
def bubble_page(request):
return render(request, 'custom_final_bubble.html')
def globe_page(request):
return render(request, 'custom_final_globe.html')
def chord_page(request):
return render(request, 'custom_final_chord.html')
def line_page(request):
return render(request, 'custom_final_line.html')
def chloropleth_page(request):
return render(request, 'custom_final_chloropleth.html')
def final_custom_page(request, page, id):
return render(request, 'custom_final.html', {'page' : page, 'id': id})
def fileupload_page(request, page, id):
return render(request, 'fileupload.html', {'page' : page, 'id': id})
def upload_page(request):
return render(request, 'upload1.html')
def upload_unique_page(request, id):
return render(request, 'upload_unique.html', {'page' : id})
def visualization_page(request, page, id):
return render(request, 'visualization.html', {'page': page, 'id': id})
@csrf_exempt
def handle_upload(request):
#equities = request.post['equities']
#str_param = EQUITY_MAP.get(equities)
root = os.path.dirname(__file__)
json_file = '%s/equities/fixtures/newstock.json' % root
json_data = open(json_file).read()
equities = json.loads(json_data.replace('\n', ''))
#field = Field(str_param)
#return HttpResponse(field.getData(), content_type="application/json")
return JsonResponse(equities)
|
# Copyright 2014 Diamond Light Source Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
.. module:: I18stxm_loader
:platform: Unix
:synopsis: A class for loading I18's stxm data
.. moduleauthor:: Aaron Parsons <[email protected]>
"""
from savu.plugins.loaders.multi_modal_loaders.base_i18_multi_modal_loader import BaseI18MultiModalLoader
from savu.plugins.utils import register_plugin
@register_plugin
class I18stxmLoader(BaseI18MultiModalLoader):
"""
A class to load tomography data from an NXstxm file
:param stxm_detector: path to stxm. Default:'entry1/raster_counterTimer01/It'.
"""
def __init__(self, name='I18stxmLoader'):
super(I18stxmLoader, self).__init__(name)
def setup(self):
"""
Define the input nexus file
:param path: The full path of the NeXus file to load.
:type path: str
"""
data_str = self.parameters['stxm_detector']
data_obj = self.multi_modal_setup('stxm')
data_obj.data = data_obj.backing_file[data_str]
data_obj.set_shape(data_obj.data.shape)
self.set_motors(data_obj, 'stxm')
self.add_patterns_based_on_acquisition(data_obj, 'stxm')
self.set_data_reduction_params(data_obj)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
**ui_constants.py**
**Platform:**
Windows, Linux, Mac Os X.
**Description:**
Defines **Umbra** package ui constants through the :class:`UiConstants` class.
**Others:**
"""
from __future__ import unicode_literals
__author__ = "Thomas Mansencal"
__copyright__ = "Copyright (C) 2008 - 2014 - Thomas Mansencal"
__license__ = "GPL V3.0 - http://www.gnu.org/licenses/"
__maintainer__ = "Thomas Mansencal"
__email__ = "[email protected]"
__status__ = "Production"
__all__ = ["UiConstants"]
class UiConstants():
"""
Defines **Umbra** package ui constants.
"""
ui_file = "Umbra.ui"
"""
:param ui_file: Application ui file.
:type ui_file: unicode
"""
processing_ui_file = "Processing.ui"
"""
:param processing_ui_file: Processing ui file.
:type processing_ui_file: unicode
"""
reporter_ui_file = "Reporter.ui"
"""
:param reporter_ui_file: Reporter ui file.
:type reporter_ui_file: unicode
"""
windows_stylesheet_file = "styles/Windows_styleSheet.qss"
"""
:param windows_stylesheet_file: Application Windows Os stylesheet file.
:type windows_stylesheet_file: unicode
"""
darwin_stylesheet_file = "styles/Darwin_styleSheet.qss"
"""
:param darwin_stylesheet_file: Application Mac Os X Os stylesheet file.
:type darwin_stylesheet_file: unicode
"""
linux_stylesheet_file = "styles/Linux_styleSheet.qss"
"""
:param linux_stylesheet_file: Application Linux Os stylesheet file.
:type linux_stylesheet_file: unicode
"""
windows_full_screen_stylesheet_file = "styles/Windows_FullScreen_styleSheet.qss"
"""
:param windows_full_screen_stylesheet_file: Application Windows Os fullscreen stylesheet file.
:type windows_full_screen_stylesheet_file: unicode
"""
darwin_full_screen_stylesheet_file = "styles/Darwin_FullScreen_styleSheet.qss"
"""
:param darwin_full_screen_stylesheet_file: Application Mac Os X Os fullscreen stylesheet file.
:type darwin_full_screen_stylesheet_file: unicode
"""
linux_full_screen_stylesheet_file = "styles/Linux_FullScreen_styleSheet.qss"
"""
:param linux_full_screen_stylesheet_file: Application Linux Os fullscreen stylesheet file.
:type linux_full_screen_stylesheet_file: unicode
"""
windows_style = "plastique"
"""
:param windows_style: Application Windows Os style.
:type windows_style: unicode
"""
darwin_style = "plastique"
"""
:param darwin_style: Application Mac Os X Os style.
:type darwin_style: unicode
"""
linux_style = "plastique"
"""
:param linux_style: Application Linux Os style.
:type linux_style: unicode
"""
settings_file = "preferences/Default_Settings.rc"
"""
:param settings_file: Application defaults settings file.
:type settings_file: unicode
"""
layouts_file = "layouts/Default_Layouts.rc"
"""
:param layouts_file: Application defaults layouts file.
:type layouts_file: unicode
"""
application_windows_icon = "images/Icon_Dark.png"
"""
:param application_windows_icon: Application icon file.
:type application_windows_icon: unicode
"""
splash_screen_image = "images/Umbra_SpashScreen.png"
"""
:param splash_screen_image: Application splashscreen image.
:type splash_screen_image: unicode
"""
logo_image = "images/Umbra_Logo.png"
"""
:param logo_image: Application logo image.
:type logo_image: unicode
"""
default_toolbar_icon_size = 32
"""
:param default_toolbar_icon_size: Application toolbar icons size.
:type default_toolbar_icon_size: int
"""
custom_layouts_icon = "images/Custom_Layouts.png"
"""
:param custom_layouts_icon: Application **Custom Layouts** icon.
:type custom_layouts_icon: unicode
"""
custom_layouts_hover_icon = "images/Custom_Layouts_Hover.png"
"""
:param custom_layouts_hover_icon: Application **Custom Layouts** hover icon.
:type custom_layouts_hover_icon: unicode
"""
custom_layouts_active_icon = "images/Custom_Layouts_Active.png"
"""
:param custom_layouts_active_icon: Application **Custom Layouts** active icon.
:type custom_layouts_active_icon: unicode
"""
miscellaneous_icon = "images/Miscellaneous.png"
"""
:param miscellaneous_icon: Application **Miscellaneous** icon.
:type miscellaneous_icon: unicode
"""
miscellaneous_hover_icon = "images/Miscellaneous_Hover.png"
"""
:param miscellaneous_hover_icon: Application **Miscellaneous** hover icon.
:type miscellaneous_hover_icon: unicode
"""
miscellaneous_active_icon = "images/Miscellaneous_Active.png"
"""
:param miscellaneous_active_icon: Application **Miscellaneous** active icon.
:type miscellaneous_active_icon: unicode
"""
development_icon = "images/Development.png"
"""
:param development_icon: Application **Development** icon.
:type development_icon: unicode
"""
development_hover_icon = "images/Development_Hover.png"
"""
:param development_hover_icon: Application **Development** hover icon.
:type development_hover_icon: unicode
"""
development_active_icon = "images/Development_Active.png"
"""
:param development_active_icon: Application **Development** active icon.
:type development_active_icon: unicode
"""
preferences_icon = "images/Preferences.png"
"""
:param preferences_icon: Application **Preferences** icon.
:type preferences_icon: unicode
"""
preferences_hover_icon = "images/Preferences_Hover.png"
"""
:param preferences_hover_icon: Application **Preferences** hover icon.
:type preferences_hover_icon: unicode
"""
preferences_active_icon = "images/Preferences_Active.png"
"""
:param preferences_active_icon: Application **Preferences** active icon.
:type preferences_active_icon: unicode
"""
startup_layout = "startup_centric"
"""
:param startup_layout: Application startup layout.
:type startup_layout: unicode
"""
help_file = "http://thomasmansencal.com/Sharing/Umbra/Support/Documentation/Help/Umbra_Manual.html"
"""
:param help_file: Application online help file.
:type help_file: unicode
"""
api_file = "http://thomasmansencal.com/Sharing/Umbra/Support/Documentation/Api/index.html"
"""
:param api_file: Application online Api file.
:type api_file: unicode
"""
development_layout = "development_centric"
"""
:param development_layout: Application development layout.
:type development_layout: unicode
"""
python_grammar_file = "grammars/Python/Python.grc"
"""
:param python_grammar_file: Python language grammar file.
:type python_grammar_file: unicode
"""
logging_grammar_file = "grammars/Logging/Logging.grc"
"""
:param logging_grammar_file: Logging language grammar file.
:type logging_grammar_file: unicode
"""
text_grammar_file = "grammars/Text/Text.grc"
"""
:param text_grammar_file: Text language grammar file.
:type text_grammar_file: unicode
"""
invalid_link_html_file = "htmls/Invalid_Link.html"
"""
:param invalid_link_html_file: Invalid link html file.
:type invalid_link_html_file: unicode
"""
crittercism_id = "5075c158d5f9b9796b000002"
"""
:param crittercism_id: Crittercism Id.
:type crittercism_id: unicode
"""
|
# Copyright 2015 Hewlett-Packard Development Company, L.P.
#
# Author: Endre Karlson <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
from oslo_config import cfg
from designate import coordination
from designate import service
from designate.tests import fixtures
from designate.tests import TestCase
cfg.CONF.register_group(cfg.OptGroup("service:dummy"))
cfg.CONF.register_opts([
], group="service:dummy")
class CoordinatedService(service.Service):
def __init__(self):
super(CoordinatedService, self).__init__()
self.coordination = coordination.Coordination(
self.service_name, self.tg
)
def start(self):
super(CoordinatedService, self).start()
self.coordination.start()
@property
def service_name(self):
return "dummy"
class TestCoordination(TestCase):
def setUp(self):
super(TestCoordination, self).setUp()
self.name = 'coordination'
self.tg = mock.Mock()
self.config(backend_url="zake://", group="coordination")
def test_start(self):
service = coordination.Coordination(self.name, self.tg)
service.start()
self.assertTrue(service.started)
service.stop()
def test_start_with_grouping_enabled(self):
service = coordination.Coordination(
self.name, self.tg, grouping_enabled=True
)
service.start()
self.assertTrue(service.started)
self.assertIn(self.name.encode('utf-8'),
service.coordinator.get_groups().get())
self.assertIn(service.coordination_id.encode('utf-8'),
service.coordinator.get_members(
self.name.encode('utf-8')).get())
service.stop()
def test_stop(self):
service = coordination.Coordination(self.name, self.tg)
service.start()
service.stop()
self.assertFalse(service.started)
def test_stop_with_grouping_enabled(self):
service = coordination.Coordination(
self.name, self.tg, grouping_enabled=True
)
service.start()
service.stop()
self.assertFalse(service.started)
def test_start_no_coordination(self):
self.config(backend_url=None, group="coordination")
service = coordination.Coordination(self.name, self.tg)
service.start()
self.assertIsNone(service.coordinator)
def test_stop_no_coordination(self):
self.config(backend_url=None, group="coordination")
service = coordination.Coordination(self.name, self.tg)
self.assertIsNone(service.coordinator)
service.start()
service.stop()
class TestPartitioner(TestCase):
def _get_partitioner(self, partitions, host=b'a'):
fixture = self.useFixture(fixtures.CoordinatorFixture(
'zake://', host))
group = 'group'
fixture.coordinator.create_group(group)
fixture.coordinator.join_group(group)
return coordination.Partitioner(fixture.coordinator, group, host,
partitions), fixture.coordinator
def test_callbacks(self):
cb1 = mock.Mock()
cb2 = mock.Mock()
partitions = list(range(0, 10))
p_one, c_one = self._get_partitioner(partitions)
p_one.start()
p_one.watch_partition_change(cb1)
p_one.watch_partition_change(cb2)
# Initial partitions are calucated upon service bootup
cb1.assert_called_with(partitions, None, None)
cb2.assert_called_with(partitions, None, None)
cb1.reset_mock()
cb2.reset_mock()
# Startup a new partioner that will cause the cb's to be called
p_two, c_two = self._get_partitioner(partitions, host=b'b')
p_two.start()
# We'll get the 5 first partition ranges
c_one.run_watchers()
cb1.assert_called_with(partitions[:5], [b'a', b'b'], mock.ANY)
cb2.assert_called_with(partitions[:5], [b'a', b'b'], mock.ANY)
def test_two_even_partitions(self):
partitions = list(range(0, 10))
p_one, c_one = self._get_partitioner(partitions)
p_two, c_two = self._get_partitioner(partitions, host=b'b')
p_one.start()
p_two.start()
# Call c_one watchers making it refresh it's partitions
c_one.run_watchers()
self.assertEqual([0, 1, 2, 3, 4], p_one.my_partitions)
self.assertEqual([5, 6, 7, 8, 9], p_two.my_partitions)
def test_two_odd_partitions(self):
partitions = list(range(0, 11))
p_one, c_one = self._get_partitioner(partitions)
p_two, c_two = self._get_partitioner(partitions, host=b'b')
p_one.start()
p_two.start()
# Call c_one watchers making it refresh it's partitions
c_one.run_watchers()
self.assertEqual([0, 1, 2, 3, 4, 5], p_one.my_partitions)
self.assertEqual([6, 7, 8, 9, 10], p_two.my_partitions)
def test_three_even_partitions(self):
partitions = list(range(0, 10))
p_one, c_one = self._get_partitioner(partitions)
p_two, c_two = self._get_partitioner(partitions, host=b'b')
p_three, c_three = self._get_partitioner(partitions, host=b'c')
p_one.start()
p_two.start()
p_three.start()
# Call c_one watchers making it refresh it's partitions
c_one.run_watchers()
c_two.run_watchers()
self.assertEqual([0, 1, 2, 3], p_one.my_partitions)
self.assertEqual([4, 5, 6, 7], p_two.my_partitions)
self.assertEqual([8, 9], p_three.my_partitions)
def test_three_odd_partitions(self):
partitions = list(range(0, 11))
p_one, c_one = self._get_partitioner(partitions)
p_two, c_two = self._get_partitioner(partitions, host=b'b')
p_three, c_three = self._get_partitioner(partitions, host=b'c')
p_one.start()
p_two.start()
p_three.start()
c_one.run_watchers()
c_two.run_watchers()
self.assertEqual([0, 1, 2, 3], p_one.my_partitions)
self.assertEqual([4, 5, 6, 7], p_two.my_partitions)
self.assertEqual([8, 9, 10], p_three.my_partitions)
class TestPartitionerWithoutBackend(TestCase):
def test_start(self):
# We test starting the partitioner and calling the watch func first
partitions = list(range(0, 10))
cb1 = mock.Mock()
cb2 = mock.Mock()
partitioner = coordination.Partitioner(
None, 'group', 'meme', partitions)
partitioner.watch_partition_change(cb1)
partitioner.watch_partition_change(cb2)
partitioner.start()
cb1.assert_called_with(partitions, None, None)
cb2.assert_called_with(partitions, None, None)
def test_cb_on_watch(self):
partitions = list(range(0, 10))
cb = mock.Mock()
partitioner = coordination.Partitioner(
None, 'group', 'meme', partitions)
partitioner.start()
partitioner.watch_partition_change(cb)
cb.assert_called_with(partitions, None, None)
|
"""
STDM Import/Export module
"""
__author__ = 'John Gitau'
__license__ = 'GNU Lesser General Public License (LGPL)'
__url__ = 'http://www.unhabitat.org'
from stdm.settings import QGISRegistryConfig
from .exceptions import TranslatorException
from .reader import OGRReader
from .writer import OGRWriter
from .value_translators import (
MultipleEnumerationTranslator,
SourceValueTranslator,
ValueTranslatorManager,
RelatedTableTranslator
)
_UIGroup = "UI"
_lastVectorDirKey = "lastVectorFileFilterDir"
def vectorFileDir():
"""
Returns the directory of the last vector file accessed by QGIS.
"""
qgisReg = QGISRegistryConfig(_UIGroup)
regValues = qgisReg.read([_lastVectorDirKey])
if len(regValues) == 0:
return ""
else:
return regValues[_lastVectorDirKey]
def setVectorFileDir(dir):
"""
Update the last vector file directory.
"""
qgisReg = QGISRegistryConfig(_UIGroup)
qgisReg.write({_lastVectorDirKey:dir})
|
import webracer
import nose.plugins.attrib
from . import utils
from .apps import form_app
utils.app_runner_setup(__name__, form_app.app, 8059)
@nose.plugins.attrib.attr('client')
@webracer.config(host='localhost', port=8059)
class RequestViaFormTest(webracer.WebTestCase):
def test_get_form_as_url(self):
self.get('/method_check_form')
self.assert_status(200)
form = self.response.form()
self.get(form)
self.assertEqual('GET', self.response.body)
def test_post_form_as_url(self):
self.get('/textarea')
self.assert_status(200)
form = self.response.form()
self.post(form)
self.assertEqual('{}', self.response.body)
def test_post_form_with_elements(self):
self.get('/textarea')
self.assert_status(200)
form = self.response.form()
elements = form.elements
self.post(form, elements)
json = self.response.json
self.assertEqual(dict(field='hello world'), json)
def test_post_form_with_mutated_elements(self):
self.get('/textarea')
self.assert_status(200)
form = self.response.form()
elements = form.elements.mutable
elements.set_value('field', 'changed')
self.post(form, elements)
json = self.response.json
self.assertEqual(dict(field='changed'), json)
|
import csv
import nltk
from nltk.tokenize import word_tokenize
import string
from nltk import pos_tag
from gensim.models.word2vec import Word2Vec
from gensim import matutils
from numpy import array, float32 as REAL
from sklearn.cluster import MiniBatchKMeans, KMeans
from multiprocessing import Pool
from collections import Counter
#string.punctuation
#string.digits
file = 'training.1600000.processed.noemoticon2.csv'
#file = 'testdata.manual.2009.06.14.csv'
tags = ["NNP", "NN", "NNS"]
ncls = 1000
niters = 1000
nreplay_kmeans = 1
lower = False
redundant = ["aw", "aww", "awww", "awwww", "haha", "lol", "wow", "wtf", "xd", "yay", "http", "www", "com", "ah", "ahh", "ahhh", "amp"]
def preprocess(tweet):
ret_tweet = ""
i = -1
nn = []
raw_tweet = tweet
for ch in string.punctuation.replace("'","") + string.digits:
tweet = tweet.replace(ch, " ")
tweet_pos = {}
if lower:
tweet = tweet.lower()
try:
toks = word_tokenize(tweet)
pos = pos_tag(toks)
nn = [p for p in pos if p[1] in tags]
#nn = [p for p in pos if p == 'NNP']
except:
pass
if(len(nn)):
tweet_pos["NN"] = nn
ret_tweet = tweet_pos
return ret_tweet
raw = []
with open(file, 'rb') as csvfile:
content = csv.reader(csvfile, delimiter=',', quotechar='"')
for row in content:
tweet = row[5]
raw.append(tweet)
p = Pool(6)
tweets = p.map(preprocess, raw)
t1 = []
t2 = []
for i in range(len(tweets)):
if len(tweets[i]):
t1.append(raw[i])
t2.append(tweets[i])
raw = t1
tweets = t2
print "Loading model..."
wv = Word2Vec.load_word2vec_format('GoogleNews-vectors-negative300.bin', binary=True)
vectors = []
for i in range(len(tweets)):
tweet = tweets[i]
nns = tweet['NN']
vector = []
#print nns
mean = []
no_wv_tweet = True
for w in nns:
if len(w[0]) > 1 and w[0] in wv and w[0].lower() not in redundant:
no_wv_tweet = False
#print w[0]
weight = 1
if w[1] == 'NNP':
weight = 100
mean.append(weight * wv[w[0]])
if(len(mean)):
vectors.append(matutils.unitvec(array(mean).mean(axis=0)).astype(REAL))
else:
vectors.append([])
t1 = []
t2 = []
t3 = []
for i in range(len(vectors)):
if vectors[i] != None and len(vectors[i]):
t1.append(raw[i])
t2.append(tweets[i])
t3.append(vectors[i])
raw = t1
tweets = t2
vectors = t3
#kmeans = KMeans(init='k-means++', n_clusters=ncls, n_init=1)
kmeans = MiniBatchKMeans(init='k-means++', n_clusters=ncls, n_init=nreplay_kmeans, max_iter=niters)
kmeans.fit(vectors)
clss = kmeans.predict(vectors)
clusters = [[] for i in range(ncls)]
for i in range(len(vectors)):
cls = clss[i]
clusters[cls].append(i)
clusterstags = [[] for i in range(ncls)]
countarr = []
for c in clusters:
counts = Counter()
for i in c:
t = [x[0] for x in tweets[i]["NN"] ]#if x[1] == "NNP"]
#tn = [x[1] for x in tweets[i]["NN"]]
sentence = " ".join(t) #+ tn)
counts.update(word.strip('.,?!"\'').lower() for word in sentence.split())
countarr.append(counts)
output = ""
for i in range(ncls):
output = "Most common words for this cluster:\n"
output += str(countarr[i].most_common(12))
output += "\n\n\n\n\n\n"
output += "Word2vec space of related words:\n"
wv_rel = wv.most_similar([kmeans.cluster_centers_[i]], topn=10)
output += str(wv_rel)
output += "\n\n\n\n\n\n"
for t in clusters[i]:
output += str(raw[t]) + "\n"
#output += "\n\n\n"
nm = [x[0] for x in countarr[i].most_common(5)]
nm = str(" ".join(nm))
for ch in string.punctuation:
nm = nm.replace(ch, " ")
f = open('clusters/' + nm +'.txt', 'wb')
f.write(output)
f.close()
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack LLC
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2010 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Utility methods for working with WSGI servers."""
import socket
import sys
import eventlet.wsgi
import routes.middleware
import ssl
import webob.dec
import webob.exc
from keystone.common import logging
from keystone.common import utils
from keystone import config
from keystone import exception
from keystone.openstack.common import importutils
from keystone.openstack.common import jsonutils
CONF = config.CONF
LOG = logging.getLogger(__name__)
# Environment variable used to pass the request context
CONTEXT_ENV = 'openstack.context'
# Environment variable used to pass the request params
PARAMS_ENV = 'openstack.params'
class WritableLogger(object):
"""A thin wrapper that responds to `write` and logs."""
def __init__(self, logger, level=logging.DEBUG):
self.logger = logger
self.level = level
def write(self, msg):
self.logger.log(self.level, msg)
class Server(object):
"""Server class to manage multiple WSGI sockets and applications."""
def __init__(self, application, host=None, port=None, threads=1000):
self.application = application
self.host = host or '0.0.0.0'
self.port = port or 0
self.pool = eventlet.GreenPool(threads)
self.socket_info = {}
self.greenthread = None
self.do_ssl = False
self.cert_required = False
def start(self, key=None, backlog=128):
"""Run a WSGI server with the given application."""
LOG.debug(_('Starting %(arg0)s on %(host)s:%(port)s') %
{'arg0': sys.argv[0],
'host': self.host,
'port': self.port})
# TODO(dims): eventlet's green dns/socket module does not actually
# support IPv6 in getaddrinfo(). We need to get around this in the
# future or monitor upstream for a fix
info = socket.getaddrinfo(self.host,
self.port,
socket.AF_UNSPEC,
socket.SOCK_STREAM)[0]
_socket = eventlet.listen(info[-1],
family=info[0],
backlog=backlog)
if key:
self.socket_info[key] = _socket.getsockname()
# SSL is enabled
if self.do_ssl:
if self.cert_required:
cert_reqs = ssl.CERT_REQUIRED
else:
cert_reqs = ssl.CERT_NONE
sslsocket = eventlet.wrap_ssl(_socket, certfile=self.certfile,
keyfile=self.keyfile,
server_side=True,
cert_reqs=cert_reqs,
ca_certs=self.ca_certs)
_socket = sslsocket
self.greenthread = self.pool.spawn(self._run,
self.application,
_socket)
def set_ssl(self, certfile, keyfile=None, ca_certs=None,
cert_required=True):
self.certfile = certfile
self.keyfile = keyfile
self.ca_certs = ca_certs
self.cert_required = cert_required
self.do_ssl = True
def kill(self):
if self.greenthread:
self.greenthread.kill()
def wait(self):
"""Wait until all servers have completed running."""
try:
self.pool.waitall()
except KeyboardInterrupt:
pass
def _run(self, application, socket):
"""Start a WSGI server in a new green thread."""
log = logging.getLogger('eventlet.wsgi.server')
eventlet.wsgi.server(socket, application, custom_pool=self.pool,
log=WritableLogger(log))
class Request(webob.Request):
pass
class BaseApplication(object):
"""Base WSGI application wrapper. Subclasses need to implement __call__."""
@classmethod
def factory(cls, global_config, **local_config):
"""Used for paste app factories in paste.deploy config files.
Any local configuration (that is, values under the [app:APPNAME]
section of the paste config) will be passed into the `__init__` method
as kwargs.
A hypothetical configuration would look like:
[app:wadl]
latest_version = 1.3
paste.app_factory = nova.api.fancy_api:Wadl.factory
which would result in a call to the `Wadl` class as
import nova.api.fancy_api
fancy_api.Wadl(latest_version='1.3')
You could of course re-implement the `factory` method in subclasses,
but using the kwarg passing it shouldn't be necessary.
"""
return cls()
def __call__(self, environ, start_response):
r"""Subclasses will probably want to implement __call__ like this:
@webob.dec.wsgify(RequestClass=Request)
def __call__(self, req):
# Any of the following objects work as responses:
# Option 1: simple string
res = 'message\n'
# Option 2: a nicely formatted HTTP exception page
res = exc.HTTPForbidden(detail='Nice try')
# Option 3: a webob Response object (in case you need to play with
# headers, or you want to be treated like an iterable, or or or)
res = Response();
res.app_iter = open('somefile')
# Option 4: any wsgi app to be run next
res = self.application
# Option 5: you can get a Response object for a wsgi app, too, to
# play with headers etc
res = req.get_response(self.application)
# You can then just return your response...
return res
# ... or set req.response and return None.
req.response = res
See the end of http://pythonpaste.org/webob/modules/dec.html
for more info.
"""
raise NotImplementedError('You must implement __call__')
class Application(BaseApplication):
@webob.dec.wsgify
def __call__(self, req):
arg_dict = req.environ['wsgiorg.routing_args'][1]
action = arg_dict.pop('action')
del arg_dict['controller']
LOG.debug(_('arg_dict: %s'), arg_dict)
# allow middleware up the stack to provide context & params
context = req.environ.get(CONTEXT_ENV, {})
context['query_string'] = dict(req.params.iteritems())
context['path'] = req.environ['PATH_INFO']
params = req.environ.get(PARAMS_ENV, {})
if 'REMOTE_USER' in req.environ:
context['REMOTE_USER'] = req.environ['REMOTE_USER']
elif context.get('REMOTE_USER', None) is not None:
del context['REMOTE_USER']
params.update(arg_dict)
# TODO(termie): do some basic normalization on methods
method = getattr(self, action)
# NOTE(vish): make sure we have no unicode keys for py2.6.
params = self._normalize_dict(params)
try:
result = method(context, **params)
except exception.Unauthorized as e:
LOG.warning(_("Authorization failed. %s from %s")
% (e, req.environ['REMOTE_ADDR']))
return render_exception(e)
except exception.Error as e:
LOG.warning(e)
return render_exception(e)
except TypeError as e:
logging.exception(e)
return render_exception(exception.ValidationError(e))
except Exception as e:
logging.exception(e)
return render_exception(exception.UnexpectedError(exception=e))
if result is None:
return render_response(status=(204, 'No Content'))
elif isinstance(result, basestring):
return result
elif isinstance(result, webob.Response):
return result
elif isinstance(result, webob.exc.WSGIHTTPException):
return result
response_code = self._get_response_code(req)
return render_response(body=result, status=response_code)
def _get_response_code(self, req):
req_method = req.environ['REQUEST_METHOD']
controller = importutils.import_class('keystone.common.controller')
code = None
if isinstance(self, controller.V3Controller) and req_method == 'POST':
code = (201, 'Created')
return code
def _normalize_arg(self, arg):
return str(arg).replace(':', '_').replace('-', '_')
def _normalize_dict(self, d):
return dict([(self._normalize_arg(k), v)
for (k, v) in d.iteritems()])
def assert_admin(self, context):
if not context['is_admin']:
try:
user_token_ref = self.token_api.get_token(
context=context, token_id=context['token_id'])
except exception.TokenNotFound as e:
raise exception.Unauthorized(e)
creds = user_token_ref['metadata'].copy()
try:
creds['user_id'] = user_token_ref['user'].get('id')
except AttributeError:
logging.debug('Invalid user')
raise exception.Unauthorized()
try:
creds['tenant_id'] = user_token_ref['tenant'].get('id')
except AttributeError:
logging.debug('Invalid tenant')
raise exception.Unauthorized()
# NOTE(vish): this is pretty inefficient
creds['roles'] = [self.identity_api.get_role(context, role)['name']
for role in creds.get('roles', [])]
# Accept either is_admin or the admin role
self.policy_api.enforce(context, creds, 'admin_required', {})
class Middleware(Application):
"""Base WSGI middleware.
These classes require an application to be
initialized that will be called next. By default the middleware will
simply call its wrapped app, or you can override __call__ to customize its
behavior.
"""
@classmethod
def factory(cls, global_config, **local_config):
"""Used for paste app factories in paste.deploy config files.
Any local configuration (that is, values under the [filter:APPNAME]
section of the paste config) will be passed into the `__init__` method
as kwargs.
A hypothetical configuration would look like:
[filter:analytics]
redis_host = 127.0.0.1
paste.filter_factory = nova.api.analytics:Analytics.factory
which would result in a call to the `Analytics` class as
import nova.api.analytics
analytics.Analytics(app_from_paste, redis_host='127.0.0.1')
You could of course re-implement the `factory` method in subclasses,
but using the kwarg passing it shouldn't be necessary.
"""
def _factory(app):
conf = global_config.copy()
conf.update(local_config)
return cls(app)
return _factory
def __init__(self, application):
self.application = application
def process_request(self, request):
"""Called on each request.
If this returns None, the next application down the stack will be
executed. If it returns a response then that response will be returned
and execution will stop here.
"""
return None
def process_response(self, request, response):
"""Do whatever you'd like to the response, based on the request."""
return response
@webob.dec.wsgify(RequestClass=Request)
def __call__(self, request):
response = self.process_request(request)
if response:
return response
response = request.get_response(self.application)
return self.process_response(request, response)
class Debug(Middleware):
"""Helper class for debugging a WSGI application.
Can be inserted into any WSGI application chain to get information
about the request and response.
"""
@webob.dec.wsgify(RequestClass=Request)
def __call__(self, req):
LOG.debug('%s %s %s', ('*' * 20), 'REQUEST ENVIRON', ('*' * 20))
for key, value in req.environ.items():
LOG.debug('%s = %s', key, value)
LOG.debug('')
LOG.debug('%s %s %s', ('*' * 20), 'REQUEST BODY', ('*' * 20))
for line in req.body_file:
LOG.debug(line)
LOG.debug('')
resp = req.get_response(self.application)
LOG.debug('%s %s %s', ('*' * 20), 'RESPONSE HEADERS', ('*' * 20))
for (key, value) in resp.headers.iteritems():
LOG.debug('%s = %s', key, value)
LOG.debug('')
resp.app_iter = self.print_generator(resp.app_iter)
return resp
@staticmethod
def print_generator(app_iter):
"""Iterator that prints the contents of a wrapper string."""
LOG.debug('%s %s %s', ('*' * 20), 'RESPONSE BODY', ('*' * 20))
for part in app_iter:
LOG.debug(part)
yield part
class Router(object):
"""WSGI middleware that maps incoming requests to WSGI apps."""
def __init__(self, mapper):
"""Create a router for the given routes.Mapper.
Each route in `mapper` must specify a 'controller', which is a
WSGI app to call. You'll probably want to specify an 'action' as
well and have your controller be an object that can route
the request to the action-specific method.
Examples:
mapper = routes.Mapper()
sc = ServerController()
# Explicit mapping of one route to a controller+action
mapper.connect(None, '/svrlist', controller=sc, action='list')
# Actions are all implicitly defined
mapper.resource('server', 'servers', controller=sc)
# Pointing to an arbitrary WSGI app. You can specify the
# {path_info:.*} parameter so the target app can be handed just that
# section of the URL.
mapper.connect(None, '/v1.0/{path_info:.*}', controller=BlogApp())
"""
# if we're only running in debug, bump routes' internal logging up a
# notch, as it's very spammy
if CONF.debug:
logging.getLogger('routes.middleware').setLevel(logging.INFO)
self.map = mapper
self._router = routes.middleware.RoutesMiddleware(self._dispatch,
self.map)
@webob.dec.wsgify(RequestClass=Request)
def __call__(self, req):
"""Route the incoming request to a controller based on self.map.
If no match, return a 404.
"""
return self._router
@staticmethod
@webob.dec.wsgify(RequestClass=Request)
def _dispatch(req):
"""Dispatch the request to the appropriate controller.
Called by self._router after matching the incoming request to a route
and putting the information into req.environ. Either returns 404
or the routed WSGI app's response.
"""
match = req.environ['wsgiorg.routing_args'][1]
if not match:
return render_exception(
exception.NotFound(_('The resource could not be found.')))
app = match['controller']
return app
class ComposingRouter(Router):
def __init__(self, mapper=None, routers=None):
if mapper is None:
mapper = routes.Mapper()
if routers is None:
routers = []
for router in routers:
router.add_routes(mapper)
super(ComposingRouter, self).__init__(mapper)
class ComposableRouter(Router):
"""Router that supports use by ComposingRouter."""
def __init__(self, mapper=None):
if mapper is None:
mapper = routes.Mapper()
self.add_routes(mapper)
super(ComposableRouter, self).__init__(mapper)
def add_routes(self, mapper):
"""Add routes to given mapper."""
pass
class ExtensionRouter(Router):
"""A router that allows extensions to supplement or overwrite routes.
Expects to be subclassed.
"""
def __init__(self, application, mapper=None):
if mapper is None:
mapper = routes.Mapper()
self.application = application
self.add_routes(mapper)
mapper.connect('{path_info:.*}', controller=self.application)
super(ExtensionRouter, self).__init__(mapper)
def add_routes(self, mapper):
pass
@classmethod
def factory(cls, global_config, **local_config):
"""Used for paste app factories in paste.deploy config files.
Any local configuration (that is, values under the [filter:APPNAME]
section of the paste config) will be passed into the `__init__` method
as kwargs.
A hypothetical configuration would look like:
[filter:analytics]
redis_host = 127.0.0.1
paste.filter_factory = nova.api.analytics:Analytics.factory
which would result in a call to the `Analytics` class as
import nova.api.analytics
analytics.Analytics(app_from_paste, redis_host='127.0.0.1')
You could of course re-implement the `factory` method in subclasses,
but using the kwarg passing it shouldn't be necessary.
"""
def _factory(app):
conf = global_config.copy()
conf.update(local_config)
return cls(app)
return _factory
def render_response(body=None, status=None, headers=None):
"""Forms a WSGI response."""
headers = headers or []
headers.append(('Vary', 'X-Auth-Token'))
if body is None:
body = ''
status = status or (204, 'No Content')
else:
body = jsonutils.dumps(body, cls=utils.SmarterEncoder)
headers.append(('Content-Type', 'application/json'))
status = status or (200, 'OK')
return webob.Response(body=body,
status='%s %s' % status,
headerlist=headers)
def render_exception(error):
"""Forms a WSGI response based on the current error."""
body = {'error': {
'code': error.code,
'title': error.title,
'message': str(error)
}}
if isinstance(error, exception.AuthPluginException):
body['error']['identity'] = error.authentication
return render_response(status=(error.code, error.title), body=body)
|
# -*- coding: utf-8 -*-
#
# Copyright © 2007-2014 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use, modify,
# copy, or redistribute it subject to the terms and conditions of the GNU
# General Public License v.2. This program is distributed in the hope that it
# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
# implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details. You should have
# received a copy of the GNU General Public License along with this program;
# if not, write to the Free Software Foundation, Inc., 51 Franklin Street,
# Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat trademarks that are
# incorporated in the source code or documentation are not subject to the GNU
# General Public License and may only be used or replicated with the express
# permission of Red Hat, Inc.
#
# Author(s): Toshio Kuratomi <[email protected]>
# Ricky Zhou <[email protected]>
# Adapted from code in the TurboGears project licensed under the MIT license.
'''
This plugin provides authentication of passwords against the Fedora Account
System.
'''
import crypt
try:
from hashlib import sha1 as hash_constructor
except ImportError:
from sha import new as hash_constructor
from sqlalchemy.orm import class_mapper
from turbogears import config, identity, flash
from turbogears.database import session
from turbogears.util import load_class
from turbogears.identity import set_login_attempted
from fas.model import People, Configs
import pytz
from datetime import datetime
import sys, os, re
import urllib2
import cherrypy
import gettext
t = gettext.translation('fas', '/usr/share/locale', fallback=True)
_ = t.ugettext
import logging
log = logging.getLogger('turbogears.identity.safasprovider')
try:
set, frozenset
except NameError:
# :W0622: We need a set type on earlier pythons.
from sets import Set as set # pylint: disable-msg=W0622
from sets import ImmutableSet as frozenset # pylint: disable-msg=W0622
# Global class references --
# these will be set when the provider is initialised.
user_class = None
visit_class = None
def get_configs(configs_list):
configs = {}
for config in configs_list:
configs[config.attribute] = config.value
if 'enabled' not in configs:
configs['enabled'] = '0'
if 'prefix' not in configs:
configs['prefix'] = 'Not Defined'
return configs
def otp_check(key):
'''Check otp key string'''
if config.get('yubi_enabled', False) and config.get('yubi_server_prefix', False):
if len(key) == 44 and key.startswith('ccccc'):
log.debug('OTP key matches criteria.')
return True
log.debug('OTP key check failed!')
return False
def otp_validate(user_name, otp):
'''
Check supplied otp key and username against existing credentials
:arg user_name: User login
:arg otp: Given OTP key
:returns: True if given args match from OTP provider
'''
client_id = '1'
target = People.by_username(user_name)
configs = get_configs(Configs.query.filter_by(person_id=target.id, application='yubikey').all())
if not otp.startswith(configs['prefix']):
return False
server_prefix = config.get('yubi_server_prefix', 'http://localhost/yk-val/verify?id=')
auth_regex = re.compile('^status=(?P<rc>\w{2})')
server_url = server_prefix + client_id + "&otp=" + otp
fh = urllib2.urlopen(server_url)
for line in fh:
match = auth_regex.search(line.strip('\n'))
if match:
if match.group('rc') == 'OK':
return True
else:
return False
break
return False
class SaFasIdentity(object):
'''Identity that uses a model from a database (via SQLAlchemy).'''
def __init__(self, visit_key=None, user=None, using_ssl=False):
self.visit_key = visit_key
self._visit_link = None
if user:
self._user = user
if visit_key is not None:
self.login(using_ssl)
def __retrieve_user(self, visit):
'''Attempt to load the user from the visit_key.
:returns: a user or None
'''
# I hope this is a safe place to double-check the SSL variables.
# TODO: Double check my logic with this - is it unnecessary to
# check that the username matches up?
if visit.ssl and cherrypy.request.headers['X-Client-Verify'] != 'SUCCESS':
self.logout()
return None
user = user_class.query.get(visit.user_id)
# This is a hack, need to talk to Toshio abvout it.w
user.approved_memberships
if user.status in ('inactive', 'expired', 'admin_disabled'):
log.warning("User %(username)s has status %(status)s, logging them out." % \
{ 'username': user.username, 'status': user.status })
self.logout()
user = None
return user
def _get_user(self):
'''Get user instance for this identity.'''
visit = self.visit_link
if not visit:
self._user = None
else:
if (not '_csrf_token' in cherrypy.request.params or
cherrypy.request.params['_csrf_token'] !=
hash_constructor(self.visit_key).hexdigest()):
log.info("Bad _csrf_token")
if '_csrf_token' in cherrypy.request.params:
log.info("visit: %s token: %s" % (self.visit_key,
cherrypy.request.params['_csrf_token']))
else:
log.info('No _csrf_token present')
cherrypy.request.fas_identity_failure_reason = 'bad_csrf'
self._user = None
try:
return self._user
except AttributeError:
# User hasn't already been set
# Attempt to load the user. After this code executes, there
# *will* be a _user attribute, even if the value is None.
self._user = self.__retrieve_user(visit)
return self._user
user = property(_get_user)
def _get_token(self):
if self.visit_key:
return hash_constructor(self.visit_key).hexdigest()
else:
return ''
csrf_token = property(_get_token)
def _get_user_name(self):
'''Get user name of this identity.'''
if not self.user:
return None
### TG: Difference: Different name for the field
return self.user.username
user_name = property(_get_user_name)
### TG: Same as TG-1.0.8
def _get_user_id(self):
'''Get user id of this identity.'''
if not self.user:
return None
return self.user.user_id
user_id = property(_get_user_id)
### TG: Same as TG-1.0.8
def _get_anonymous(self):
'''Return true if not logged in.'''
return not self.user
anonymous = property(_get_anonymous)
def _get_only_token(self):
'''
In one specific instance in the login template we need to know whether
an anonymous user is just lacking a token.
'''
visit = self.visit_link
if visit and self.__retrieve_user(visit):
# user is valid, just the token is missing
return True
# Else the user still has to login
return False
only_token = property(_get_only_token)
def _get_permissions(self):
'''Get set of permission names of this identity.'''
### TG difference: No permissions in FAS
return frozenset()
permissions = property(_get_permissions)
def _get_groups(self):
'''Get set of group names of this identity.'''
try:
return self._groups
except AttributeError:
# Groups haven't been computed yet
pass
if not self.user:
self._groups = frozenset()
else:
### TG: Difference. Our model has a many::many for people:groups
# And an association proxy that links them together
self._groups = frozenset([g.name for g in self.user.approved_memberships])
return self._groups
groups = property(_get_groups)
def _get_group_ids(self):
'''Get set of group IDs of this identity.'''
try:
return self._group_ids
except AttributeError:
# Groups haven't been computed yet
pass
if not self.user:
self._group_ids = frozenset()
else:
### TG: Difference. Our model has a many::many for people:groups
# And an association proxy that links them together
self._group_ids = frozenset([g.id for g in self.user.approved_memberships])
return self._group_ids
group_ids = property(_get_group_ids)
### TG: Same as TG-1.0.8
def _get_visit_link(self):
'''Get the visit link to this identity.'''
if self._visit_link:
return self._visit_link
if self.visit_key is None:
self._visit_link = None
else:
self._visit_link = visit_class.query.filter_by(visit_key=self.visit_key).first()
return self._visit_link
visit_link = property(_get_visit_link)
### TG: Same as TG-1.0.8
def _get_login_url(self):
'''Get the URL for the login page.'''
return identity.get_failure_url()
login_url = property(_get_login_url)
### TG: Same as TG-1.0.8
def login(self, using_ssl=False):
'''Set the link between this identity and the visit.'''
visit = self.visit_link
if visit:
visit.user_id = self._user.id
visit.ssl = using_ssl
else:
visit = visit_class()
visit.visit_key = self.visit_key
visit.user_id = self._user.id
visit.ssl = using_ssl
session.flush()
### TG: Same as TG-1.0.8
def logout(self):
'''Remove the link between this identity and the visit.'''
visit = self.visit_link
if visit:
session.delete(visit)
session.flush()
# Clear the current identity
identity.set_current_identity(SaFasIdentity())
class SaFasIdentityProvider(object):
'''
IdentityProvider that authenticates users against the fedora account system
'''
def __init__(self):
super(SaFasIdentityProvider, self).__init__()
global user_class
global visit_class
user_class_path = config.get("identity.saprovider.model.user", None)
user_class = load_class(user_class_path)
visit_class_path = config.get("identity.saprovider.model.visit", None)
log.info(_("Loading: %(visitmod)s") % \
{'visitmod': visit_class_path})
visit_class = load_class(visit_class_path)
def create_provider_model(self):
'''
Create the database tables if they don't already exist.
'''
class_mapper(user_class).local_table.create(checkfirst=True)
class_mapper(visit_class).local_table.create(checkfirst=True)
def validate_identity(self, user_name, password, visit_key, otp=None):
'''
Look up the identity represented by user_name and determine whether the
password is correct.
Must return either None if the credentials weren't valid or an object
with the following properties:
user_name: original user name
user: a provider dependant object (TG_User or similar)
groups: a set of group IDs
permissions: a set of permission IDs
Side Effects:
:cherrypy.request.fas_provided_username: set to user_name
:cherrypy.request.fas_identity_failure_reason: if we fail to validate
the user, set to the reason validation failed. Values can be:
:no_user: The username was not present in the db.
:status_inactive: User is disabled but can reset their password
to restore service.
:status_expired: User is expired, account is no more.
:status_admin_disabled: User is disabled and has to talk to an
admin before they are re-enabled.
:bad_password: The username and password do not match.
Arguments:
:arg user_name: user_name we're authenticating. If None, we'll try
to lookup a username from SSL variables
:arg password: password to authenticate user_name with
:arg visit_key: visit_key from the user's session
:arg otp: One Time Password key to authenticate within the password
This is an extras argument we add to request parameters
in order to add 2nd factor authentication to TG1.
'''
# Save the user provided username so we can do other checks on it in
# outside of this method.
cherrypy.request.fas_provided_username = user_name
cherrypy.request.fas_identity_failure_reason = None
using_ssl = False
email_domain = '@' + config.get('email_host', '')
if email_domain != '@' and user_name.endswith(email_domain):
user_name = user_name[:-len(email_domain)]
if '@' in user_name:
user = user_class.query.filter_by(email=user_name).first()
else:
user = user_class.query.filter_by(username=user_name).first()
if not user:
log.warning("No such user: %s", user_name)
cherrypy.request.fas_identity_failure_reason = 'no_user'
return None
if user.status in ('inactive', 'expired', 'admin_disabled'):
log.warning("User %(username)s has status %(status)s" %
{'username': user_name, 'status': user.status})
cherrypy.request.fas_identity_failure_reason = 'status_%s'% user.status
return None
# Get extras args from request params to increase auth check
# then pop it out if found to don't mess with other object's method
if 'otp' in cherrypy.request.params:
otp = cherrypy.request.params.pop('otp')
if not self.validate_password(user, user_name, password, otp):
log.info("Passwords don't match for user: %s", user_name)
cherrypy.request.fas_identity_failure_reason = 'bad_password'
return None
# user + password is sufficient to prove the user is in
# control
cherrypy.request.params['_csrf_token'] = hash_constructor(
visit_key).hexdigest()
log.info("Associating user (%s) with visit (%s)",
user_name, visit_key)
user.last_seen = datetime.now(pytz.utc)
return SaFasIdentity(visit_key, user, using_ssl)
def validate_password(self, user, user_name, password, otp=None):
'''
Check the supplied user_name and password against existing credentials.
Note: user_name is not used here, but is required by external
password validation schemes that might override this method.
If you use SaFasIdentityProvider, but want to check the passwords
against an external source (i.e. PAM, LDAP, Windows domain, etc),
subclass SaFasIdentityProvider, and override this method.
:user: User information. Not used.
:user_name: Given username.
:password: Given plaintext password.
:otp: Given OTP (one time password)
:returns: True if the password matches the username. Otherwise False.
Can return False for problems within the Account System as well.
'''
# crypt.crypt(stuff, '') == ''
# Just kill any possibility of blanks.
if not user.password:
return False
if not password:
return False
# Check if given password matches existing one
check_pw = (user.password == crypt.crypt(password.encode('utf-8'), user.password))
# Check if combo login (password+otp) has been requested.
if otp:
# If so, make sure we got a correct otp key value before go ahead
if otp_check(otp):
if otp_validate(user_name, otp) and check_pw:
return True
else:
log.debug('Invalid OTP or password!')
return False
else:
# Do not validate if otp check failed,
# as both password and otp are required to get through.
return False
# TG identity providers take user_name in case an external provider
# needs it so we can't get rid of it. (W0613)
# pylint: disable-msg=W0613
return check_pw
def load_identity(self, visit_key):
'''Lookup the principal represented by visit_key.
:arg visit_key: The session key for whom we're looking up an identity.
:return: an object with the following properties:
:user_name: original user name
:user: a provider dependant object (TG_User or similar)
:groups: a set of group IDs
:permissions: a set of permission IDs
'''
ident = SaFasIdentity(visit_key)
if 'csrf_login' in cherrypy.request.params:
cherrypy.request.params.pop('csrf_login')
set_login_attempted(True)
return ident
def anonymous_identity(self):
'''Returns an anonymous user object
:return: an object with the following properties:
:user_name: original user name
:user: a provider dependant object (TG_User or similar)
:groups: a set of group IDs
:permissions: a set of permission IDs
'''
return SaFasIdentity(None)
def authenticated_identity(self, user):
'''
Constructs Identity object for user that has no associated visit_key.
:arg user: The user structure the identity is constructed from
:return: an object with the following properties:
:user_name: original user name
:user: a provider dependant object (TG_User or similar)
:groups: a set of group IDs
:permissions: a set of permission IDs
'''
return SaFasIdentity(None, user)
|
"""
UhbdSingleFunctions.py
Functions for running single-site calculations using UHBD. Replaces the
prepares and doinps binaries.
"""
import os
TITRATABLE = {"HISA":"NE2","HISB":"ND1","HISN":"ND1","HISC":"ND1",
"LYS":"NZ","LYSN":"NZ","LYSC":"NZ",
"ARG":"CZ","ARGN":"CZ","ARGC":"CZ",
"ASP":"CG","ASPN":"CG","ASPC":"CG",
"GLU":"CD","GLUN":"CD","GLUC":"CD",
"TYR":"OH","TYRN":"OH","TYRC":"OH",
"CYS":"SG","CYSN":"SG","CYSC":"SG"}
def writeOutput(output_file,data_list):
"""
Mini function that writes output files.
"""
g = open(output_file,'w')
g.writelines(data_list)
g.close()
def prepareSingle():
"""
A python implementation of UHBD fortran "prepares.f" It does not direclty
write out uhbdini.inp. See the makeUhbdini function for that.
"""
# Open pdb file and read it
f = open("proteinH.pdb","r")
pdb = f.readlines()
f.close()
# Pull only titratable atoms from the pdb
n_terminus = [l for l in pdb if l[0:4] == "ATOM"
and l[20:21] == "N"]
titr_groups = [l for l in pdb if l[0:4] == "ATOM"
and l[17:21].strip() in TITRATABLE.keys()]
c_terminus = [l for l in pdb if l[0:4] == "ATOM"
and l[20:21] == "C"]
# Create list of all titratable groups in the pdb file
titr_resid = []
titr_resid.extend(n_terminus)
titr_resid.extend(titr_groups)
titr_resid.extend(c_terminus)
titr_resid = ["%s\n" % l[:54] for l in titr_resid]
# Grab list of all unique residues
resid_list = [titr_resid[0][21:26]]
for l in titr_resid:
if resid_list[-1] != l[21:26]:
resid_list.append(l[21:26])
# Create tempor output file, listing all atoms of all titratable residues
# in the order of the original file
tempor = []
for residue in resid_list:
residue_atoms = [l for l in titr_resid if l[21:26] == residue]
residue_atoms = ["%6s%5i%s" % (a[0:6],i+1,a[11:])
for i, a in enumerate(residue_atoms)]
tempor.extend(residue_atoms)
# Create sitesinpr and titraa files, which list all titratable atoms and
# all titratable residues with titratable atom in first position.
sitesinpr = []
titraa = []
for residue in resid_list:
residue_atoms = [l for l in titr_resid if l[21:26] == residue]
# Figure out what the titratable atom is for this residue
try:
titr_atom = TITRATABLE[residue_atoms[0][17:21].strip()]
except KeyError:
if residue_atoms[0][20] == "N":
titr_atom = "N"
elif residue_atoms[0][20] == "C":
titr_atom = "C"
titr_line = [l for l in residue_atoms
if l[12:16].strip() == titr_atom][0]
sitesinpr.append(titr_line)
residue_atoms = [l for l in residue_atoms if l != titr_line]
residue_atoms.insert(0,titr_line)
residue_atoms = ["%6s%5i%s" % (a[0:6],i+1,a[11:])
for i, a in enumerate(residue_atoms)]
titraa.extend(residue_atoms)
# Close sitesinpr file
sitesinpr.insert(0,"%-54s\n" % (pdb[0].strip()))
sitesinpr.append("END")
# Write output files
writeOutput("tempor.pdb",tempor)
writeOutput("sitesinpr.pdb",sitesinpr)
writeOutput("titraa.pdb",titraa)
def makeUhbdini(calc_param):
"""
Write out uhbdini.inp.
"""
short_param_file = os.path.split(calc_param.param_file)[-1]
uhbdini = [\
"read mol 1 file \"%s\" pdb end\n" % "proteinH.pdb",
"set charge radii file \"%s\" para mine end\n" % short_param_file,
"\n elec setup mol 1\ncenter\n",
" spacing %.2F dime %i %i %i\n" % (calc_param.grid[0][0],
calc_param.grid[0][1],
calc_param.grid[0][2],
calc_param.grid[0][3]),
" nmap %.1F\n" % calc_param.map_sphere,
" nsph %i\n" % calc_param.map_sample,
" sdie %.2F\n" % calc_param.solvent_dielec,
" pdie %.2F\n" % calc_param.protein_dielec,
"end\n\n",
"write grid epsi binary file \"coarse.epsi\" end\n",
"write grid epsj binary file \"coarse.epsj\" end\n",
"write grid epsk binary file \"coarse.epsk\" end\n\n"
"stop\n"]
writeOutput("pkaS-uhbdini.inp",uhbdini)
def runPrepares(calc_param):
prepareSingle()
makeUhbdini(calc_param)
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('actuators', '0007_auto_20150812_1520'),
]
operations = [
migrations.AlterField(
model_name='actuatoreffect',
name='control_profile',
field=models.ForeignKey(to='actuators.ControlProfile', related_name='effects'),
),
migrations.AlterField(
model_name='actuatoreffect',
name='effect_on_active',
field=models.FloatField(default=0),
),
migrations.AlterField(
model_name='actuatoreffect',
name='property',
field=models.ForeignKey(to='resources.ResourceProperty', related_name='+'),
),
migrations.AlterField(
model_name='actuatoreffect',
name='threshold',
field=models.FloatField(default=0),
),
migrations.AlterField(
model_name='controlprofile',
name='properties',
field=models.ManyToManyField(through='actuators.ActuatorEffect', editable=False, to='resources.ResourceProperty', related_name='+'),
),
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.