Using sockets but keep getting syntax error.

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
kiltedpython
Posts: 4
Joined: Mon Jul 06, 2020 11:33 pm

Using sockets but keep getting syntax error.

Post by kiltedpython » Thu Jul 16, 2020 11:04 pm

Just need some basic http stuff but cannot seem to get some hidden syntax error. Any help is appreciated.

Code: Select all

import socket


def http_get(url):
    _, _, host, path = url.split('/', 3)
    addr = socket.getaddrinfo(host, 8060)[0][-1]
    s = socket.socket()
    s.connect(addr)
    s.send(bytes('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host), 'utf8'))
    while True:
        date = s.recv(100)
        if data:
            print(str(data, 'utf8'), end='')
        else:
            break
    s.close()


def http_post(url):
    _, _, host, path = url.split('/', 3)
    addr = socket.getaddrinfo(host, 8060)[0][-1]
    s = socket.socket()
    s.connect(addr)
    s.send(bytes('POST /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host), 'utf8'))
    while True:
        date = s.recv(100)
        if data:
            print(str(data, 'utf8'), end='')
        else:
            break
    s.close()
    
    

User avatar
jimmo
Posts: 2015
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: Using sockets but keep getting syntax error.

Post by jimmo » Fri Jul 17, 2020 4:51 am

I can't see any reason for a SyntaxError, however on line 12 you have

Code: Select all

date = s.recv(100)
which should be "data"

Also, I'd recommend using the "urequests" library if possible.

kiltedpython
Posts: 4
Joined: Mon Jul 06, 2020 11:33 pm

Re: Using sockets but keep getting syntax error.

Post by kiltedpython » Fri Jul 17, 2020 2:37 pm

Thanks for the spelling fix but still seeing syntax error.

Code: Select all

MicroPython v1.12-2 on 2020-05-01; linux version
Use Ctrl-D to exit, Ctrl-E for paste mode
>>> import pyokuets
>>> http_get(http://192.168.1.8/query/apps)
Traceback (most recent call last):
  File "<stdin>", line 1
SyntaxError: invalid syntax
There is no information on why or what. Just poke and guess?

As far as using urequests; the board that is being used does not have 'upip' or many libs installed by default. Trying to build an image for the board that will have all the libs that would be nice to have but until then going with 'sockets' for this.

User avatar
dhylands
Posts: 3482
Joined: Mon Jan 06, 2014 6:08 pm
Location: Peachland, BC, Canada
Contact:

Re: Using sockets but keep getting syntax error.

Post by dhylands » Fri Jul 17, 2020 2:56 pm

You need to surround the argument to http_get in quotes.

kiltedpython
Posts: 4
Joined: Mon Jul 06, 2020 11:33 pm

Re: Using sockets but keep getting syntax error.

Post by kiltedpython » Fri Jul 17, 2020 6:11 pm

Thank you so much. That was the ticket. :)

Post Reply