Running webserver and other code simultaneously

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
mvincm
Posts: 6
Joined: Sun Sep 17, 2017 10:59 pm

Re: Running webserver and other code simultaneously

Post by mvincm » Sun Apr 07, 2019 11:27 pm

Thank you very very much !!! I will follow your link!

Best regards,
MM

mekanixms
Posts: 1
Joined: Fri Oct 18, 2019 3:46 pm

Re: Running webserver and other code simultaneously

Post by mekanixms » Fri Oct 18, 2019 3:57 pm

bitninja wrote:
Sat May 26, 2018 7:01 pm
Here is a simple web server based on the uasyncio example, that I know works on the ESP8266 and the D1 Mini. I have yet to implement another coro but perhaps Peter's tutorial will help you with that.

Code: Select all

#
# Simple HTTP server based on the uasyncio example script
# by J.G. Wezensky (joewez@gmail.com)
#

import uasyncio as asyncio
import uos
import pkg_resources

webroot = 'wwwroot'
default = 'index.html'

# Breaks an HTTP request into its parts and boils it down to a physical file (if possible)
def decode_path(req):
    cmd, headers = req.decode("utf-8").split('\r\n', 1)
    parts = cmd.split(' ')
    method, path = parts[0], parts[1]
    # remove any query string
    query = ''
    r = path.find('?')
    if r > 0:
        query = path[r:]
        path = path[:r]
    # check for use of default document
    if path == '/':
        path = default
    else:
        path = path[1:]
    # return the physical path of the response file
    return webroot + '/' + path

# Looks up the content-type based on the file extension
def get_mime_type(file):
    if file.endswith(".html"):
        return "text/html", False
    if file.endswith(".css"):
        return "text/css", True
    if file.endswith(".js"):
        return "text/javascript", True
    if file.endswith(".png"):
        return "image/png", True
    if file.endswith(".gif"):
        return "image/gif", True
    if file.endswith(".jpeg") or file.endswith(".jpg"):
        return "image/jpeg", True
    return "text/plain", False

# Quick check if a file exists
def exists(file):
    try:
        s = uos.stat(file)
        return True
    except:
        return False    

@asyncio.coroutine
def serve(reader, writer):
    try:
        file = decode_path((yield from reader.read()))
        if exists(file):
            mime_type, cacheable = get_mime_type(file)
            yield from writer.awrite("HTTP/1.0 200 OK\r\n")
            yield from writer.awrite("Content-Type: {}\r\n".format(mime_type))
            if cacheable:
                yield from writer.awrite("Cache-Control: max-age=86400\r\n")
            yield from writer.awrite("\r\n")

            f = open(file, "rb")
            buffer = f.read(512)
            while buffer != b'':
                yield from writer.awrite(buffer)
                buffer = f.read(512)
            f.close()
        else:
            yield from writer.awrite("HTTP/1.0 404 NA\r\n\r\n")
    except:
        raise
    finally:
        yield from writer.aclose()

def start():
    import logging
    logging.basicConfig(level=logging.ERROR)

    loop = asyncio.get_event_loop()
    loop.call_soon(asyncio.start_server(serve, "0.0.0.0", 80, 20))
    loop.run_forever()
    loop.close()
Good luck!
Hi!

Nice piece of code, thanks for sharing!
I am trying to implement GET and POST methods by changing the decode_path function as follows:

Code: Select all

def decode_path(req):
    global http_query, GET

    cmd, headers = req.decode("utf-8").split('\r\n', 1)
    parts = cmd.split(' ')
    method, path = parts[0], parts[1]
    # remove any query string
    query = ''
    r = path.find('?')
    if r > 0:
        http_query = path[r:]
        path = path[:r]
    # check for use of default document
    if path == '/':
        path = default
    else:
        path = path[1:]
    # return the physical path of the response file
    GET = {}
    gargs = http_query.split('&')
    for arg in gargs:
        t = arg.split('=')
        if len(t) > 1:
            k, v = arg.split('=')
            GET[k] = v

    print(GET)

    return webroot + '/' + path
Has anyone successfully made an implementation of GET and POST? Any better suggestion?

Post Reply