P
P
pythonMyLife2022-01-22 20:15:25
Python
pythonMyLife, 2022-01-22 20:15:25

Why is Chrome sending empty requests endlessly?

I'm trying to learn web development in Python with asyncio. I'm creating a server with .start_server and .serve_forever. Here is the request handling code:

async def handle_client (reader, writer):
    print (f'New client!')
    request = None

    while request != 'quit':
        request = (await reader.read (1024)).decode ()

        response = generate_responce (request)

        writer.write (response.encode ())
        await writer.drain ()

    writer.close ()

def generate_responce (request: str) -> str:
    print (f'REQUEST: {request !r}')

    if request == '': return 'NO REQUEST' #(1)

    method, url = parse_request (request)
    headers, code = generate_headers (method, url)

    return headers + 'Hello World!'

def parse_request (request: str) -> tuple[str]:
    method, url, *_ = request.split (' ', maxsplit = 3)

    return method, url

def generate_headers (method: str, url: str) -> tuple[str, int]:
    if method != 'POST':
        return 'HTTP/1.1 405 Method not allowed\n\n', 405

    if url != '/':
        return 'HTTP/1.1 404 Not Found\n\n', 404

    return 'HTTP/1.1 200 OK\n\n', 200



(1) Done because of endless empty requests
New client!
New client!
REQUEST: 'GET / HTTP/1.1\r\nHost: localhost:5692\r\nConnection: keep-alive\r\nCache-Control: max-age=0\r\nsec-ch-ua: " Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"\r\nsec-ch-ua-mobile: ?0\r\nsec-ch-ua-platform: "Windows"\r\nDNT: 1\r\nUpgrade-Insecure-Requests: 1\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\r\nSec-Fetch-Site: none\r\nSec-Fetch-Mode: navigate\r\nSec-Fetch-User: ?1\r\nSec-Fetch-Dest: document\r\nAccept-Encoding: gzip, deflate, br\r\nAccept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7\r\n\r\n'
REQUEST: ''
REQUEST: ''
REQUEST: ''
REQUEST: ''
REQUEST: ''
REQUEST: ''
REQUEST: ''
REQUEST: ''
...

And so on, until I terminate the process. And only after interruption my squalor is shown in Chrome.
Is there a way to fix this?

PS: The code is brazenly borrowed from a 2018 video.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2022-01-22
@pythonMyLife

while request != 'quit':
Indeed, why the program loops...
If only the documentation described the behavior of read() when the connection to the client is closed!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question