splinter icon indicating copy to clipboard operation
splinter copied to clipboard

Suggested updates to the `FlaskClient` driver

Open anthonyjb opened this issue 10 years ago • 9 comments

Hi - first off thank you for this wonderful library. I'm using it in conjunction with pytest-bdd and Flask and for the most part it's been plain sailing, however I am currently using a custom FlaskClient that overrides the _do_method to resolve 2 issues/traits I came across.

302 and 303 behaviour

By default most browser (correctly or incorrectly) will use the GET method when redirecting based on a 302 response, and 303s (I believe) specifically address this confusion by declaring that the 303 response from a POST request is to a GET resource.

At the moment using the FlaskClient all 30X responses retain the current method, so if a 303 response is received from a POST request then the _do_method will make another request using the post not the intended get method.

args and form data

Flask provides access to data transmitted via POST or PUT through request.form, alternatively data transmitted in the URL (e.g via GET) is available through request.args (there's also request.values which allows you to access data in either but that's not important here).

Using the FlaskClient when you submit a form with a method attribute of GET (e.g <form method="GET" ...>) the request will be made as using the GET method but the data will be sent as if POSTed and will end up in the request.form attribute. As you can imagine this then causes issues because the view being called is looking for the submitted data in request.args.

The cause of the issue is that data is always sent in the _do_method using the data keyword argument when calling the func_method, but for a GET request (I believe) the data keyword should not sent as None and the data should be set against the URL as a query.

Fixing these issues

As I mentioned at the start of the issue I'm currently using a patched driver based on the existing FlaskClient to resolve these issues/traits. I've included the code below in case others come across the same issues in the short-term and as a suggestion as to how they might be fixed. If you'd like me to contribute the changes as a pull request I'm more than happy to have a look at doing so over the weekend.

Note: My patch is using Python3.4+, hence from urllib import parse so would need to be made compatible with 2.7+ though I think that would be a relatively easy task.

from urllib import parse

from splinter.browser import _DRIVERS
from splinter.driver import flaskclient

__all__ = ['FlaskClient']


class FlaskClient(flaskclient.FlaskClient):
    """
    A patched `FlaskClient` driver that implements more standard `302`/`303`
    behaviour and that sets data for `GET` requests against the URL.
    """

    driver_name = 'flask'

    def _do_method(self, method, url, data=None):

        # Set the initial URL and client/HTTP method
        self._url = url
        func_method = getattr(self._browser, method.lower())

        # Continue to make requests until a non 30X response is recieved
        while True:
            self._last_urls.append(url)

            # If we're making a GET request set the data against the URL as a
            # query.
            if method.lower() == 'get':

                # Parse the existing URL and it's query
                url_parts = parse.urlparse(url)
                url_params = parse.parse_qs(url_parts.query)

                # Update any existing query dictionary with the `data` argument
                url_params.update(data or {})
                url_parts = url_parts._replace(
                        query=parse.urlencode(url_params, doseq=True))

                # Rebuild the URL
                url = parse.urlunparse(url_parts)

                # As the `data` argument will be passed as a keyword argument to
                # the `func_method` we set it `None` to prevent it populating
                # `flask.request.form` on `GET` requests.
                data = None

            # Call the flask client
            self._response = func_method(
                url,
                headers=self._custom_headers,
                data=data,
                follow_redirects=False
                )

            # Implement more standard `302`/`303` behaviour
            if self._response.status_code in (302, 303):
                func_method = getattr(self._browser, 'get')

            # If the response was not in the `30X` range we're done
            if self._response.status_code not in (301, 302, 303, 305, 307):
                break

            # If the response was in the `30X` range get next URL to request
            url = self._response.headers['Location']

        self._url = self._last_urls[-1]
        self._post_load()


# Patch the default `FlaskClient` driver
_DRIVERS['flask'] = FlaskClient

anthonyjb avatar Sep 20 '16 16:09 anthonyjb

Hi, nice catch!

I'm +1 for these improvements.

Can you send a PR with this improvements?

andrewsmedina avatar Sep 22 '16 22:09 andrewsmedina

@andrewsmedina - Happy to, will give it a shot this weekend :)

anthonyjb avatar Sep 23 '16 09:09 anthonyjb

@andrewsmedina OK I've pushed a pull request for this #517.

anthonyjb avatar Sep 25 '16 15:09 anthonyjb

@anthonyjb thank you for contribute. can you add some tests for this pr?

andrewsmedina avatar Sep 27 '16 01:09 andrewsmedina

Hi @andrewsmedina,

Yes sorry I merely checked it passed existing flask tests, should have added tests for the identified issues. However, before I do I found another issues yesterday where checkbox input values can't be sent through, they need to be pre converted to a list before being passed in data, e.g:

# Ensure all data has been converted to a supported type
if data:
    for k, v in data.items():
        if isinstance(v, CheckboxValues):
            v = list(v)
        data[k] = v

If you don't convert this then with the FlaskClient at least you get the __repr__ string for the CheckboxValues object through instead of the values themselves.

I'll post a fix for this in the next couple of days but I want to check;

  1. should the issue be solved in the FlaskClient or should it be fixed in the submit method of LxmlDriver.
  2. Are there other input types that have the same issue, e.g a select field with multiple options checked.

I'll review and post an update as soon as I know a long with a PR and some tests checking these issues are resolved.

anthonyjb avatar Sep 27 '16 08:09 anthonyjb

Just wanted to chime in and say that the patch mentioned up top worked great. Thanks @anthonyjb!

afeld avatar Oct 24 '16 07:10 afeld

Hi, I've just started using splinter with Flask and have run into the redirect issue; rather than having to patch things ourselves it would be really nice to see the fix merged. Would you be okay @anthonyjb @andrewsmedina if I opened a new pull request with @anthonyjb's fix (#517) plus some tests?

lfdebrux avatar Oct 01 '19 16:10 lfdebrux

@lfdebrux I'm ok with that ;)

andrewsmedina avatar Oct 01 '19 20:10 andrewsmedina

Fixed by #721

javascript-error avatar Mar 08 '20 14:03 javascript-error