예제 #1
0
class Form(object):
    """Representation of an HTML form."""
    def __init__(self, parsed):
        parsed = helpers.ensure_soup(parsed)
        if parsed.name != 'form':
            parsed = parsed.find('form')
        self.parsed = parsed
        self.action = self.parsed.get('action')
        self.method = self.parsed.get('method', 'get')
        self.fields = OrderedMultiDict()
        for field in _parse_fields(self.parsed):
            self.add_field(field)

    def add_field(self, field):
        """Add a field.

        :param field: Field to add
        :raise: ValueError if `field` is not an instance of `BaseField`.

        """
        if not isinstance(field, fields.BaseField):
            raise ValueError('Argument "field" must be an instance of '
                             'BaseField')
        self.fields.add(field.name, field)

    @property
    def submit_fields(self):
        return _filter_fields(self.fields,
                              lambda field: isinstance(field, fields.Submit))

    @encode_if_py2
    def __repr__(self):
        state = u', '.join([
            u'{0}={1}'.format(name, field.value)
            for name, field in self.fields.items(multi=True)
        ])
        if state:
            return u'<RoboForm {0}>'.format(state)
        return u'<RoboForm>'

    def keys(self):
        return self.fields.keys()

    def __getitem__(self, item):
        return self.fields[item]

    def __setitem__(self, key, value):
        self.fields[key].value = value

    def serialize(self, submit=None):
        """Serialize each form field to a Payload container.

        :param Submit submit: Optional `Submit` to click, if form includes
            multiple submits
        :return: Payload instance

        """
        include_fields = prepare_fields(self.fields, self.submit_fields,
                                        submit)
        return Payload.from_fields(include_fields)
예제 #2
0
class StatementHistory(object):
    """Keeps a history of SQL statements with execution time and offers some pretty printing options.
    No precautions for thread safety.
    """
    def __init__(self):
        self._reset()

    def _reset(self):
        self._statements = OrderedMultiDict()
        self.last_statement = None
        self.last_duration = None
        self.last_timestamp = None

    def append(self, stmt, timestamp, duration, notices):
        self.last_statement = stmt
        self.last_timestamp = timestamp
        self.last_duration = duration
        self.last_notices = notices
        self._statements.add(stmt, (timestamp, duration, notices))

    def clear(self):
        # clear() does not work on OrderedMultiDict, bug in werkzeug?
        self._reset()

    @property
    def statements(self):
        return self._statements.keys()

    @property
    def statements_with_all_infos(self):
        return iteritems(self._statements)

    @property
    def statements_with_time(self):
        return ((k, v[0]) for k, v in iteritems(self._statements))

    def format_statement(self,
                         stmt,
                         highlight=True,
                         time=0,
                         duration=0,
                         pygments_style=DEFAULT_PYGMENTS_STYLE,
                         formatter_cls=None):
        show_time = time and duration
        highlight_format_stmt = _make_statement_formatter(
            show_time, highlight, pygments_style, formatter_cls)
        return highlight_format_stmt(stmt)

    def print_last_statement(self,
                             show_time=True,
                             highlight=True,
                             pygments_style=DEFAULT_PYGMENTS_STYLE):
        if self.last_statement is None:
            print("history is empty")
            return

        highlight_format_stmt = _make_statement_formatter(
            show_time, highlight, pygments_style)
        print()
        print(
            highlight_format_stmt(self.last_statement, self.last_timestamp,
                                  self.last_duration))

    def print_statements(self,
                         show_time=True,
                         highlight=True,
                         pygments_style=DEFAULT_PYGMENTS_STYLE):
        if self.last_statement is None:
            print("history is empty")
            return

        highlight_format_stmt = _make_statement_formatter(
            show_time, highlight, pygments_style)
        print()

        for stmt, (timestamp, duration) in self._statements.items(multi=True):
            print(highlight_format_stmt(stmt, timestamp, duration))
예제 #3
0
파일: form.py 프로젝트: M157q/robobrowser
class Form(object):
    """Representation of an HTML form."""

    def __init__(self, parsed):
        parsed = helpers.ensure_soup(parsed)
        if parsed.name != 'form':
            parsed = parsed.find('form')
        self.parsed = parsed
        self.action = self.parsed.get('action')
        self.method = self.parsed.get('method', 'get')
        self.fields = OrderedMultiDict()
        for field in _parse_fields(self.parsed):
            self.add_field(field)

    def add_field(self, field):
        """Add a field.

        :param field: Field to add
        :raise: ValueError if `field` is not an instance of `BaseField`.

        """
        if not isinstance(field, fields.BaseField):
            raise ValueError('Argument "field" must be an instance of '
                             'BaseField')
        self.fields.add(field.name, field)

    @property
    def submit_fields(self):
        return _filter_fields(
            self.fields,
            lambda field: isinstance(field, fields.Submit)
        )

    @encode_if_py2
    def __repr__(self):
        state = u', '.join(
            [
                u'{0}={1}'.format(name, field.value)
                for name, field in self.fields.items(multi=True)
            ]
        )
        if state:
            return u'<RoboForm {0}>'.format(state)
        return u'<RoboForm>'

    def keys(self):
        return self.fields.keys()

    def __getitem__(self, item):
        return self.fields[item]

    def __setitem__(self, key, value):
        self.fields[key].value = value

    def serialize(self, submit=None):
        """Serialize each form field to a Payload container.

        :param Submit submit: Optional `Submit` to click, if form includes
            multiple submits
        :return: Payload instance

        """
        include_fields = prepare_fields(self.fields, self.submit_fields, submit)
        return Payload.from_fields(include_fields)
예제 #4
0
class StatementHistory(object):

    """Keeps a history of SQL statements with execution time and offers some pretty printing options.
    No precautions for thread safety.
    """

    def __init__(self):
        self._reset()

    def _reset(self):
        self._statements = OrderedMultiDict()
        self.last_statement = None
        self.last_duration = None
        self.last_timestamp = None

    def append(self, stmt, timestamp, duration, notices):
        self.last_statement = stmt
        self.last_timestamp = timestamp
        self.last_duration = duration
        self.last_notices = notices
        self._statements.add(stmt, (timestamp, duration, notices))

    def clear(self):
        # clear() does not work on OrderedMultiDict, bug in werkzeug?
        self._reset()

    @property
    def statements(self):
        return self._statements.keys()

    @property
    def statements_with_all_infos(self):
        return iteritems(self._statements)
    
    @property
    def statements_with_time(self):
        return ((k, v[0]) for k, v in iteritems(self._statements))

    def format_statement(self, stmt, highlight=True, time=0, duration=0, pygments_style=DEFAULT_PYGMENTS_STYLE, formatter_cls=None):
        show_time = time and duration
        highlight_format_stmt = _make_statement_formatter(show_time, highlight, pygments_style, formatter_cls)
        return highlight_format_stmt(stmt)

    def print_last_statement(self, show_time=True, highlight=True, pygments_style=DEFAULT_PYGMENTS_STYLE):
        if self.last_statement is None:
            print("history is empty")
            return

        highlight_format_stmt = _make_statement_formatter(show_time, highlight, pygments_style)
        print()
        print(highlight_format_stmt(self.last_statement, self.last_timestamp, self.last_duration))

    def print_statements(self, show_time=True, highlight=True, pygments_style=DEFAULT_PYGMENTS_STYLE):
        if self.last_statement is None:
            print("history is empty")
            return

        highlight_format_stmt = _make_statement_formatter(show_time, highlight, pygments_style)
        print()

        for stmt, (timestamp, duration) in self._statements.items(multi=True):
            print(highlight_format_stmt(stmt, timestamp, duration))
예제 #5
0
def test_ordered_multidict():
    """Test the OrderedMultiDict"""
    d = OrderedMultiDict()
    assert not d
    d.add("foo", "bar")
    assert len(d) == 1
    d.add("foo", "baz")
    assert len(d) == 1
    assert d.items() == [("foo", "bar")]
    assert list(d) == ["foo"]
    assert d.items(multi=True) == [("foo", "bar"), ("foo", "baz")]
    del d["foo"]
    assert not d
    assert len(d) == 0
    assert list(d) == []

    d.update([("foo", 1), ("foo", 2), ("bar", 42)])
    d.add("foo", 3)
    assert d.getlist("foo") == [1, 2, 3]
    assert d.getlist("bar") == [42]
    assert d.items() == [("foo", 1), ("bar", 42)]
    assert d.keys() == list(d) == list(d.iterkeys()) == ["foo", "bar"]
    assert d.items(multi=True) == [("foo", 1), ("foo", 2), ("bar", 42), ("foo", 3)]
    assert len(d) == 2

    assert d.pop("foo") == 1
    assert d.pop("blafasel", None) is None
    assert d.pop("blafasel", 42) == 42
    assert len(d) == 1
    assert d.poplist("bar") == [42]
    assert not d

    d.get("missingkey") is None

    d.add("foo", 42)
    d.add("foo", 23)
    d.add("bar", 2)
    d.add("foo", 42)
    assert d == MultiDict(d)
    id = ImmutableOrderedMultiDict(d)
    assert d == id
    d.add("foo", 2)
    assert d != id

    d.update({"blah": [1, 2, 3]})
    assert d["blah"] == 1
    assert d.getlist("blah") == [1, 2, 3]

    # setlist works
    d = OrderedMultiDict()
    d["foo"] = 42
    d.setlist("foo", [1, 2])
    assert d.getlist("foo") == [1, 2]

    assert_raises(OrderedMultiDict.KeyError, d.pop, "missing")
    assert_raises(OrderedMultiDict.KeyError, d.__getitem__, "missing")

    # popping
    d = OrderedMultiDict()
    d.add("foo", 23)
    d.add("foo", 42)
    d.add("foo", 1)
    assert d.popitem() == ("foo", 23)
    assert_raises(OrderedMultiDict.KeyError, d.popitem)
    assert not d

    d.add("foo", 23)
    d.add("foo", 42)
    d.add("foo", 1)
    assert d.popitemlist() == ("foo", [23, 42, 1])
    assert_raises(OrderedMultiDict.KeyError, d.popitemlist)
예제 #6
0
def test_ordered_multidict():
    """Test the OrderedMultiDict"""
    d = OrderedMultiDict()
    assert not d
    d.add('foo', 'bar')
    assert len(d) == 1
    d.add('foo', 'baz')
    assert len(d) == 1
    assert d.items() == [('foo', 'bar')]
    assert list(d) == ['foo']
    assert d.items(multi=True) == [('foo', 'bar'),
                                   ('foo', 'baz')]
    del d['foo']
    assert not d
    assert len(d) == 0
    assert list(d) == []

    d.update([('foo', 1), ('foo', 2), ('bar', 42)])
    d.add('foo', 3)
    assert d.getlist('foo') == [1, 2, 3]
    assert d.getlist('bar') == [42]
    assert d.items() == [('foo', 1), ('bar', 42)]
    assert d.keys() == list(d) == list(d.iterkeys()) == ['foo', 'bar']
    assert d.items(multi=True) == [('foo', 1), ('foo', 2),
                                   ('bar', 42), ('foo', 3)]
    assert len(d) == 2

    assert d.pop('foo') == 1
    assert d.pop('blafasel', None) is None
    assert d.pop('blafasel', 42) == 42
    assert len(d) == 1
    assert d.poplist('bar') == [42]
    assert not d

    d.get('missingkey') is None

    d.add('foo', 42)
    d.add('foo', 23)
    d.add('bar', 2)
    d.add('foo', 42)
    assert d == MultiDict(d)
    id = ImmutableOrderedMultiDict(d)
    assert d == id
    d.add('foo', 2)
    assert d != id

    d.update({'blah': [1, 2, 3]})
    assert d['blah'] == 1
    assert d.getlist('blah') == [1, 2, 3]

    # setlist works
    d = OrderedMultiDict()
    d['foo'] = 42
    d.setlist('foo', [1, 2])
    assert d.getlist('foo') == [1, 2]

    assert_raises(OrderedMultiDict.KeyError, d.pop, 'missing')
    assert_raises(OrderedMultiDict.KeyError, d.__getitem__, 'missing')

    # popping
    d = OrderedMultiDict()
    d.add('foo', 23)
    d.add('foo', 42)
    d.add('foo', 1)
    assert d.popitem() == ('foo', 23)
    assert_raises(OrderedMultiDict.KeyError, d.popitem)
    assert not d

    d.add('foo', 23)
    d.add('foo', 42)
    d.add('foo', 1)
    assert d.popitemlist() == ('foo', [23, 42, 1])
    assert_raises(OrderedMultiDict.KeyError, d.popitemlist)
예제 #7
0
def test_ordered_multidict():
    """Test the OrderedMultiDict"""
    d = OrderedMultiDict()
    assert not d
    d.add('foo', 'bar')
    assert len(d) == 1
    d.add('foo', 'baz')
    assert len(d) == 1
    assert d.items() == [('foo', 'bar')]
    assert list(d) == ['foo']
    assert d.items(multi=True) == [('foo', 'bar'), ('foo', 'baz')]
    del d['foo']
    assert not d
    assert len(d) == 0
    assert list(d) == []

    d.update([('foo', 1), ('foo', 2), ('bar', 42)])
    d.add('foo', 3)
    assert d.getlist('foo') == [1, 2, 3]
    assert d.getlist('bar') == [42]
    assert d.items() == [('foo', 1), ('bar', 42)]
    assert d.keys() == list(d) == list(d.iterkeys()) == ['foo', 'bar']
    assert d.items(multi=True) == [('foo', 1), ('foo', 2), ('bar', 42),
                                   ('foo', 3)]
    assert len(d) == 2

    assert d.pop('foo') == 1
    assert d.pop('blafasel', None) is None
    assert d.pop('blafasel', 42) == 42
    assert len(d) == 1
    assert d.poplist('bar') == [42]
    assert not d

    d.get('missingkey') is None

    d.add('foo', 42)
    d.add('foo', 23)
    d.add('bar', 2)
    d.add('foo', 42)
    assert d == MultiDict(d)
    id = ImmutableOrderedMultiDict(d)
    assert d == id
    d.add('foo', 2)
    assert d != id

    d.update({'blah': [1, 2, 3]})
    assert d['blah'] == 1
    assert d.getlist('blah') == [1, 2, 3]

    # setlist works
    d = OrderedMultiDict()
    d['foo'] = 42
    d.setlist('foo', [1, 2])
    assert d.getlist('foo') == [1, 2]

    assert_raises(OrderedMultiDict.KeyError, d.pop, 'missing')
    assert_raises(OrderedMultiDict.KeyError, d.__getitem__, 'missing')

    # popping
    d = OrderedMultiDict()
    d.add('foo', 23)
    d.add('foo', 42)
    d.add('foo', 1)
    assert d.popitem() == ('foo', 23)
    assert_raises(OrderedMultiDict.KeyError, d.popitem)
    assert not d

    d.add('foo', 23)
    d.add('foo', 42)
    d.add('foo', 1)
    assert d.popitemlist() == ('foo', [23, 42, 1])
    assert_raises(OrderedMultiDict.KeyError, d.popitemlist)