Search code examples
python-3.xpython-requestsurllib3

requests get method how to use


I use requests to send some data to a server. The URL needs to look like "http://IP:PORT/api/json/v1/transfer/transferItem?organisation=Organisation&branch=1&itemnumber=1&operation=U&dyn=VARIABLE1=blabla;VARIABLE2=blabla"

I Used the following Code:

def send(self):
    for i in range(1, 8):
        try:
            self.statusBar().showMessage('Connection...')
            resp = requests.get(url,
                params={'organisation': 'Organisation', 'branch': '1', 'itemnumber': str(i), 'operation': 'U', 'dyn': {'VARIABLE1': 'blabla', 'VARIABLE2': 'blabla'} })
            print(resp.url)
            if resp.status_code == requests.codes.ok:
                self.statusBar().showMessage('Finished '+str(i) +' / 7')
                time.sleep(0.5)
        except requests.exceptions.ConnectionError:
            self.statusBar().showMessage('Connection Error')
            break

But the print(resp.url) always ends after ...dyn=VARIABLE1.


Solution

  • Your params aren't fit for a GET request as-is because they contain a nested item (dyn).

    What you should do in that particular case is encode this nested item separately in the format your server accepts. Which would give something like:

    def send(self):
        for i in range(1, 8):
            try:
                self.statusBar().showMessage('Connection...')
    
                params = {
                    'organisation': 'Organisation',
                    'branch': '1',
                    'itemnumber': str(i),
                    'operation': 'U',
                    'dyn': {'VARIABLE1': 'blabla', 'VARIABLE2': 'blabla'}
                }
                # Replace the 'dyn' param with a "key1=value1;key2=value2" representation
                params['dyn'] = ";".join("=".join(j) for j in params['dyn'].items())
    
                # EDIT: Got to encode the parameters ourselves or requests will urlencode them
                params = "&".join("=".join(k) for k in params.items())
    
                resp = requests.get(url, params)
                print(resp.url)
                if resp.status_code == requests.codes.ok:
                    self.statusBar().showMessage('Finished %d / 7' % i)
                    time.sleep(0.5)
            except requests.exceptions.ConnectionError:
                self.statusBar().showMessage('Connection Error')
                break
    

    Obviously I can't test it but that should be about it. Tell me if you have issues.

    However I want to stress that this isn't really good design on the server side; POST would be more appropriate for arbitrary nested data.