Table of Contents
1. Write coroutine function
2. Call the coroutine function
Example: Call the coroutine function through the coroutine function
Example: When IOLoo has not been started, call it through the run_sync() function of IOLoop.
When the program has not entered the running state of IOLoop, the coroutine function can be called through the run_sync() function. " >When the program has not entered the running state of IOLoop, the coroutine function can be called through the run_sync() function.
Example: When IOLoop is started, call through the spawn_callback() function" >Example: When IOLoop is started, call through the spawn_callback() function
3. Call the blocking function in the coroutine
4. Waiting for multiple asynchronous calls in the coroutine
Example: Use list method to pass multiple asynchronous calls" >Example: Use list method to pass multiple asynchronous calls
Example: Pass multiple asynchronous calls in dictionary mode: " >Example: Pass multiple asynchronous calls in dictionary mode:
Home Backend Development Python Tutorial Detailed explanation of the use of Tornado coroutines in Python (with examples)

Detailed explanation of the use of Tornado coroutines in Python (with examples)

Oct 16, 2018 pm 04:03 PM
python

This article brings you a detailed explanation of the use of Tornado coroutines in Python (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Using Tornado coroutines can develop asynchronous behavior similar to synchronous code. At the same time, because the coroutine itself does not use threads, it reduces the overhead of thread context switching and is an efficient development model.

1. Write coroutine function

Example: Using coroutine technology to develop web page access function

#用协程技术开发网页访问功能
from tornado import  gen #引入协程库gen
from tornado.httpclient import AsyncHTTPClient
import time

#使用gen.coroutine修饰器
@gen.coroutine
def coroutine_visit():
    http_client=AsyncHTTPClient()
    response=yield http_client.fetch("http://www.baidu.com")
    print(response.body)
Copy after login

In this example, the asynchronous client AsyncHTTPClient is still used for page access. The decorator @gen.coroutine declares that this is a coroutine function. Due to the yield keyword, there is no need to write a callback function in the code to process the access results. Instead, the result processing statement can be written directly after the yield statement.

2. Call the coroutine function

Since the Tornado coroutine is implemented based on Python's yield keyword, it cannot be called directly like an ordinary function.
Coroutine functions can be called in the following three ways:

  • Called through the yield keyword within a function that is itself a coroutine.

  • When IOLoop has not started, call it through the run_sync() function of IOLoop.

  • When IOLoop has been started, it is called through the spawn_callback() function of IOLoop.

Example: Call the coroutine function through the coroutine function

Code:

#用协程技术开发网页访问功能
from tornado import  gen #引入协程库gen
from tornado.httpclient import AsyncHTTPClient
import time

#使用gen.coroutine修饰器
@gen.coroutine
def coroutine_visit():
    http_client=AsyncHTTPClient()
    response=yield http_client.fetch("http://www.baidu.com")
    print(response.body)

@gen.coroutine
def outer_coroutine():
    print("start call coroutine_visit")
    yield coroutine_visit()
    print("end call coroutine_cisit")
Copy after login

In this example, outer_coroutine() and coroutine_visit() are both coroutine functions Program functions, so they can be called through the yield keyword. _

Example: When IOLoo has not been started, call it through the run_sync() function of IOLoop.
IOLoop is the main event loop object of Tornado, through which the Tornado program listens to access requests from external clients and performs corresponding operations.

Code:

#用协程技术开发网页访问功能
from tornado import  gen #引入协程库gen
from tornado.httpclient import AsyncHTTPClient
from tornado.ioloop import IOLoop  #引入IOLoop对象

#使用gen.coroutine修饰器
@gen.coroutine
def coroutine_visit():
    http_client=AsyncHTTPClient()
    response=yield http_client.fetch("http://www.baidu.com")
    print(response.body)

def func_normal():
    print("start call coroutine_visit")
    IOLoop.current().run_sync(lambda :coroutine_visit())
    print("end call coroutine_visit")
Copy after login
When the program has not entered the running state of IOLoop, the coroutine function can be called through the run_sync() function.

Note: The run_sync() function will block the call of the current function until the execution of the called coroutine is completed.

In fact, Tornado requires that the coroutine function can be called in the running state of IOLoop, but the run_sync function automatically completes the steps of starting and stopping IOLoop. Its implementation logic is:

[Start IOLoop]》[Call the coroutine function encapsulated by lambda]》[Stop IOLoop]

Example: When IOLoop is started, call through the spawn_callback() function

Code:

#用协程技术开发网页访问功能
from tornado import  gen #引入协程库gen
from tornado.httpclient import AsyncHTTPClient
from tornado.ioloop import IOLoop  #引入IOLoop对象

#使用gen.coroutine修饰器
@gen.coroutine
def coroutine_visit():
    http_client=AsyncHTTPClient()
    response=yield http_client.fetch("http://www.baidu.com")
    print(response.body)

def func_normal():
    print("start call coroutine_visit")
    IOLoop.current().spawn_callback(coroutine_visit)
    print("end call coroutine_visit")
Copy after login

The spawn_callback() function will not wait for the execution of the called coroutine to be completed. All the upper and lower print statements will be completed immediately, and coroutine__visit itself will be called by IOLoop at the appropriate time.

Note: IOLoop's spawn_callback() function does not provide developers with a method to obtain the return value of a coroutine function call, so span_callback() can only be used to call a coroutine function without a return value.

3. Call the blocking function in the coroutine

Directly calling the blocking function in the coroutine will affect the performance of the coroutine itself, so Tornado provides the use of thread pools to schedule blocking functions in the coroutine, thus Methods that do not affect the continued execution of the coroutine itself.

Code example:

from concurrent.futures import ThreadPoolExecutor
from tornado import gen

#定义线程池
thread_pool=ThreadPoolExecutor(2)

def mySleep(count):
    import time
    for x in range(count):
        time.sleep(1)

@gen.coroutine
def call_blocking():
    print("start")
    yield thread_pool.submit(mySleep,10)
    print("end")
Copy after login

The code first references the ThreadPoolExecutor class of concurrent.futures and instantiates a thread pool thread_pool consisting of two threads. In the coroutine call_blocking that needs to call a blocking function, use thread_pool.submit to call the blocking function and return it through yield. This will not block the continued execution of the thread where the coroutine is located, and also ensure the execution order of the code before and after the blocking function.

4. Waiting for multiple asynchronous calls in the coroutine

So far, we know the programming method of waiting for an asynchronous call with a yield keyword in the coroutine. In fact, Tornado allows you to use a yield keyword in a coroutine to wait for multiple asynchronous calls. You only need to pass these calls to the yield keyword in the form of a list or dictionary.
Example: Use list method to pass multiple asynchronous calls
#使用列表方式传递多个异步调用
from tornado import gen  #引入协程库gen
from tornado.httpclient import AsyncHTTPClient

@gen.coroutine   #使用gen.coroutine修饰器
def coroutine_visit():
    http_client=AsyncHTTPClient()
    list_response=yield [
        http_client.fetch("http://www.baidu.com"),
        http_client.fetch("http://www.api.jiutouxiang.com")
    ]
    for response in list_response:
        print(response.body)
Copy after login

Still use @gen.coroutine decorator to define coroutine in the code, and use list to pass several where yield is required An asynchronous call, yield will return and continue execution only after all calls in the list are completed. yield returns the call results in a list.

Example: Pass multiple asynchronous calls in dictionary mode:
#使用列表方式传递多个异步调用
from tornado import gen  #引入协程库gen
from tornado.httpclient import AsyncHTTPClient

@gen.coroutine   #使用gen.coroutine修饰器
def coroutine_visit():
    http_client=AsyncHTTPClient()
    dict_response=yield {
       "baidu": http_client.fetch("http://www.baidu.com"),
        "9siliao":http_client.fetch("http://www.api.jiutouxiang.com")
    }
    print(dict_response["baidu"].body)
Copy after login

The above is the detailed content of Detailed explanation of the use of Tornado coroutines in Python (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Concurrency and Multithreading Golang vs. Python: Concurrency and Multithreading Apr 17, 2025 am 12:20 AM

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Can vscode run ipynb Can vscode run ipynb Apr 15, 2025 pm 07:30 PM

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.

See all articles