Skip to content

Commit

Permalink
Remove use of get_event_loop.
Browse files Browse the repository at this point in the history
Refs #916 - get_event_loop is deprecated in Python 3.10.

Fix #534.
  • Loading branch information
aaugustin committed May 2, 2021
1 parent 6b5d56f commit a08a005
Show file tree
Hide file tree
Showing 22 changed files with 85 additions and 81 deletions.
15 changes: 7 additions & 8 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,14 @@ Here's how a client sends and receives messages:
#!/usr/bin/env python
import asyncio
import websockets
from websockets import connect
async def hello(uri):
async with websockets.connect(uri) as websocket:
async with connect(uri) as websocket:
await websocket.send("Hello world!")
await websocket.recv()
asyncio.get_event_loop().run_until_complete(
hello('ws://localhost:8765'))
asyncio.run(hello('ws://localhost:8765'))
And here's an echo server:

Expand All @@ -65,15 +64,15 @@ And here's an echo server:
#!/usr/bin/env python
import asyncio
import websockets
from websockets import serve
async def echo(websocket, path):
async for message in websocket:
await websocket.send(message)
asyncio.get_event_loop().run_until_complete(
websockets.serve(echo, 'localhost', 8765))
asyncio.get_event_loop().run_forever()
async def main():
async with serve(echo, 'localhost', 8765):
await asyncio.Future() # run forever
Does that look good?

Expand Down
3 changes: 1 addition & 2 deletions compliance/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,4 @@ async def run_tests(server, agent):
await update_reports(server, agent)


main = run_tests(SERVER, urllib.parse.quote(AGENT))
asyncio.get_event_loop().run_until_complete(main)
asyncio.run(run_tests(SERVER, urllib.parse.quote(AGENT)))
14 changes: 8 additions & 6 deletions compliance/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@ async def echo(ws, path):
await ws.send(msg)


start_server = websockets.serve(echo, HOST, PORT, max_size=2 ** 25, max_queue=1)
async def main():
with websockets.serve(echo, HOST, PORT, max_size=2 ** 25, max_queue=1):
try:
await asyncio.Future()
except KeyboardInterrupt:
pass

try:
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
except KeyboardInterrupt:
pass

asyncio.run(main)
3 changes: 2 additions & 1 deletion docs/faq.rst
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,8 @@ Can I use ``websockets`` synchronously, without ``async`` / ``await``?
......................................................................

You can convert every asynchronous call to a synchronous call by wrapping it
in ``asyncio.get_event_loop().run_until_complete(...)``.
in ``asyncio.get_event_loop().run_until_complete(...)``. Unfortunately, this
is deprecated as of Python 3.10.

If this turns out to be impractical, you should use another library.

Expand Down
7 changes: 4 additions & 3 deletions docs/heroku.rst
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,11 @@ Here's the implementation of the app, an echo server. Save it in a file called
async for message in websocket:
await websocket.send(message)
start_server = websockets.serve(echo, "", int(os.environ["PORT"]))
async def main():
async with websockets.serve(echo, "", int(os.environ["PORT"])):
await asyncio.Future() # run forever
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
asyncio.run(main)
The server relies on the ``$PORT`` environment variable to tell on which port
it will listen, according to Heroku's conventions.
Expand Down
2 changes: 1 addition & 1 deletion example/basic_auth_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ async def hello():
greeting = await websocket.recv()
print(greeting)

asyncio.get_event_loop().run_until_complete(hello())
asyncio.run(hello())
17 changes: 9 additions & 8 deletions example/basic_auth_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,13 @@ async def hello(websocket, path):
greeting = f"Hello {websocket.username}!"
await websocket.send(greeting)

start_server = websockets.serve(
hello, "localhost", 8765,
create_protocol=websockets.basic_auth_protocol_factory(
realm="example", credentials=("mary", "p@ssw0rd")
),
)
async def main():
async with websockets.serve(
hello, "localhost", 8765,
create_protocol=websockets.basic_auth_protocol_factory(
realm="example", credentials=("mary", "p@ssw0rd")
),
):
await asyncio.Future() # run forever

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
asyncio.run(main)
2 changes: 1 addition & 1 deletion example/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@ async def hello():
greeting = await websocket.recv()
print(f"< {greeting}")

asyncio.get_event_loop().run_until_complete(hello())
asyncio.run(hello())
7 changes: 3 additions & 4 deletions example/counter.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ async def counter(websocket, path):
await unregister(websocket)


start_server = websockets.serve(counter, "localhost", 6789)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
async def main():
async with websockets.serve(counter, "localhost", 6789):
await asyncio.Future() # run forever
7 changes: 4 additions & 3 deletions example/echo.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ async def echo(websocket, path):
async for message in websocket:
await websocket.send(message)

start_server = websockets.serve(echo, "localhost", 8765)
async def main():
async with websockets.serve(echo, "localhost", 8765):
await asyncio.Future() # run forever

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
asyncio.run(main)
11 changes: 6 additions & 5 deletions example/health_check_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@ async def echo(websocket, path):
async for message in websocket:
await websocket.send(message)

start_server = websockets.serve(
echo, "localhost", 8765, process_request=health_check
)
async def main():
async with websockets.serve(
echo, "localhost", 8765, process_request=health_check
):
await asyncio.Future() # run forever

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
asyncio.run(main)
2 changes: 1 addition & 1 deletion example/hello.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ async def hello():
await websocket.send("Hello world!")
await websocket.recv()

asyncio.get_event_loop().run_until_complete(hello())
asyncio.run(hello())
2 changes: 1 addition & 1 deletion example/secure_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,4 @@ async def hello():
greeting = await websocket.recv()
print(f"< {greeting}")

asyncio.get_event_loop().run_until_complete(hello())
asyncio.run(hello())
11 changes: 6 additions & 5 deletions example/secure_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@ async def hello(websocket, path):
localhost_pem = pathlib.Path(__file__).with_name("localhost.pem")
ssl_context.load_cert_chain(localhost_pem)

start_server = websockets.serve(
hello, "localhost", 8765, ssl=ssl_context
)
async def main():
async with websockets.serve(
hello, "localhost", 8765, ssl=ssl_context
):
await asyncio.Future() # run forever

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
asyncio.run(main)
7 changes: 4 additions & 3 deletions example/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ async def hello(websocket, path):
await websocket.send(greeting)
print(f"> {greeting}")

start_server = websockets.serve(hello, "localhost", 8765)
async def main():
async with websockets.serve(hello, "localhost", 8765):
await asyncio.Future() # run forever

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
asyncio.run(main)
7 changes: 4 additions & 3 deletions example/show_time.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ async def time(websocket, path):
await websocket.send(now)
await asyncio.sleep(random.random() * 3)

start_server = websockets.serve(time, "127.0.0.1", 5678)
async def main():
async with websockets.serve(time, "localhost", 5678):
await asyncio.Future() # run forever

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
asyncio.run(main)
4 changes: 2 additions & 2 deletions example/shutdown_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@
async def client():
uri = "ws://localhost:8765"
async with websockets.connect(uri) as websocket:
loop = asyncio.get_running_loop()
# Close the connection when receiving SIGTERM.
loop = asyncio.get_event_loop()
loop.add_signal_handler(
signal.SIGTERM, loop.create_task, websocket.close())

# Process messages received on the connection.
async for message in websocket:
...

asyncio.get_event_loop().run_until_complete(client())
asyncio.run(client())
15 changes: 6 additions & 9 deletions example/shutdown_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,12 @@ async def echo(websocket, path):
async for message in websocket:
await websocket.send(message)

async def echo_server(stop):
async def server():
loop = asyncio.get_running_loop()
stop = loop.create_future()
# Set the stop condition when receiving SIGTERM.
loop.add_signal_handler(signal.SIGTERM, stop.set_result, None)
async with websockets.serve(echo, "localhost", 8765):
await stop

loop = asyncio.get_event_loop()

# The stop condition is set when receiving SIGTERM.
stop = loop.create_future()
loop.add_signal_handler(signal.SIGTERM, stop.set_result, None)

# Run the server until the stop condition is met.
loop.run_until_complete(echo_server(stop))
asyncio.run(server())
2 changes: 1 addition & 1 deletion example/unix_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@ async def hello():
greeting = await websocket.recv()
print(f"< {greeting}")

asyncio.get_event_loop().run_until_complete(hello())
asyncio.run(hello())
9 changes: 5 additions & 4 deletions example/unix_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@ async def hello(websocket, path):
await websocket.send(greeting)
print(f"> {greeting}")

socket_path = os.path.join(os.path.dirname(__file__), "socket")
start_server = websockets.unix_serve(hello, socket_path)
async def main():
socket_path = os.path.join(os.path.dirname(__file__), "socket")
async with websockets.unix_serve(hello, socket_path):
await asyncio.Future() # run forever

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
asyncio.run(main)
2 changes: 1 addition & 1 deletion performance/mem_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ async def mem_client(client):
await asyncio.sleep(CLIENTS * INTERVAL)


asyncio.get_event_loop().run_until_complete(
asyncio.run(
asyncio.gather(*[mem_client(client) for client in range(CLIENTS + 1)])
)

Expand Down
17 changes: 8 additions & 9 deletions performance/mem_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,11 @@ async def handler(ws, path):
await asyncio.sleep(CLIENTS * INTERVAL)


async def mem_server(stop):
async def mem_server():
loop = asyncio.get_running_loop()
stop = loop.create_future()
# Set the stop condition when receiving SIGTERM.
loop.add_signal_handler(signal.SIGTERM, stop.set_result, None)
async with websockets.serve(
handler,
"localhost",
Expand All @@ -44,19 +48,14 @@ async def mem_server(stop):
)
],
):
tracemalloc.start()
await stop


loop = asyncio.get_event_loop()
asyncio.run(mem_server())

stop = loop.create_future()
loop.add_signal_handler(signal.SIGINT, stop.set_result, None)

tracemalloc.start()

loop.run_until_complete(mem_server(stop))

# First connection incurs non-representative setup costs.
# First connection may incur non-representative setup costs.
del MEM_SIZE[0]

print(f"µ = {statistics.mean(MEM_SIZE) / 1024:.1f} KiB")
Expand Down

0 comments on commit a08a005

Please sign in to comment.