- Hands-On Reactive Programming with Python
- Romain Picard
- 322字
- 2021-06-24 18:25:21
Bootstrapping the event loop
Now that the driver implementation is done, one has to instantiate it. As explained in the Observable cycles section, this server contains an observable cycle. This cycle is handled with Subject. Here is the code for the bootstrapping phase:
http_proxy = Subject()
sources = {
'http': http_driver(http_proxy, loop),
}
sinks = echo_server(sources)
sinks["http"].subscribe(http_proxy)
The application logic of the server is implemented as a component in the echo_server function. Its implementation is detailed as follows: the source and sinks of this component are Python dictionaries that contain one field named HTTP. This field contains an observable carrying HTTP requests in the sources dictionary and HTTP responses in the sinks dictionary. It is possible to use an observable directly for the sources and sinks since they contain only one field, but this is a base structure that will be more complex as features are added to this server.
The first line creates a subject and stores it in the http_proxy variable. Then the sources object is created with an HTTP field set with the result of the http_driver function. As seen before, this returns a stream of HTTP requests. The input parameters are the subject created before and a reference to the asyncio events loop.
Then the echo_server component is called, with sources as an input parameter. This function returns a sinks object, whose HTTP field contains an observable with the HTTP responses. Finally, the cycle is completed by making the HTTP sink subscribe to the HTTP proxy.
The whole code of this bootstrapping is implemented in the main function, which looks like this:
def main():
loop = asyncio.get_event_loop()
http_proxy = Subject()
sources = {
'http': http_driver(http_proxy, loop),
}
sinks = echo_server(sources)
sinks["http"].subscribe(http_proxy)
loop.run_forever()
loop.close()
The default asyncio event loop is retrieved at the beginning so that it can be provided to the HTTP driver, and then the event loop is run forever after the cycle is set up.
- 網(wǎng)絡(luò)操作系統(tǒng):Windows Server 2003管理與應(yīng)用
- 嵌入式應(yīng)用程序設(shè)計(jì)綜合教程(微課版)
- AutoCAD 2014中文版從入門到精通
- ElasticSearch Cookbook
- Linux軟件管理平臺設(shè)計(jì)與實(shí)現(xiàn)
- iOS 10快速開發(fā):18天零基礎(chǔ)開發(fā)一個(gè)商業(yè)應(yīng)用
- bash shell腳本編程經(jīng)典實(shí)例(第2版)
- 完美應(yīng)用Ubuntu(第2版)
- 操作系統(tǒng)之哲學(xué)原理第2版
- Docker容器技術(shù)與運(yùn)維
- Responsive Web Design with AngularJS
- Linux指令從初學(xué)到精通
- 樹莓派+傳感器:創(chuàng)建智能交互項(xiàng)目的實(shí)用方法、工具及最佳實(shí)踐
- Instant Responsive Web Design
- 物聯(lián)網(wǎng)操作系統(tǒng)AliOS Things探索與實(shí)踐