簡體   English   中英

“RuntimeError:線程 'Thread-2' 中沒有當前事件循環。” 錯誤是什么意思?

[英]what does a "RuntimeError: There is no current event loop in thread 'Thread-2'." error mean?

所以我一直在嘗試用 pyppeteer 制作一個簡單的比特幣價格檢查器。 它就像一個魅力,但每當我嘗試將它實現到 flask 時,我都會遇到運行時錯誤。

本質上,我想構建一個 web api 調用,每當我單擊一個按鈕時,它都會調用 webscraper 文件。

如果有人可以幫助指導我,那將不勝感激!

Flask 服務器

import webscraper
import asyncio

from flask import Flask, redirect, url_for, render_template, request

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html', title="Home")

@app.route('/api/scrape', methods=['POST'])
def scrape():
    webscraper.crypto_price('https://coinmarketcap.com/currencies/bitcoin/')
    return redirect(url_for('index'))

if(__name__ == '__main__'):
    app.run()

Pyppeteer 文件

import asyncio
from pyppeteer import browser, launch

def write_to_file(file, text):
    f = open(file, 'w')
    f.write(text)
    f.close

def crypto_price(link):
    async def main():
        browser = await launch()
        page = await browser.newPage()
        await page.setViewport({'width': 1920, 'height': 1080})

        await page.goto(link, {'waitUntil': 'networkidle2'})
        data = await page.evaluate('''()=> {
            return {
                price: document.querySelector('#__next > div > div.main-content > div.sc-57oli2-0.dEqHl.cmc-body-wrapper > div > div.sc-16r8icm-0.hNsOU.container > div.sc-16r8icm-0.kXPxnI.container___lbFzk > div.sc-16r8icm-0.kXPxnI.priceSection___3kA4m > div.sc-16r8icm-0.kXPxnI.priceTitle___1cXUG > div').innerText
            }
        }''')

        await browser.close()

        write_to_file('./webscrape_result.txt', data['price'])

    asyncio.get_event_loop().run_until_complete(main())

錯誤

[2021-05-14 09:30:15,007] ERROR in app: Exception on /api/scrape [POST]
Traceback (most recent call last):
  File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1936, in dispatch_request     
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Users\gabri\Desktop\Python Web Scraper\server.py", line 14, in scrape
    webscraper.crypto_price('https://coinmarketcap.com/currencies/bitcoin/')
  File "C:\Users\gabri\Desktop\Python Web Scraper\webscraper.py", line 26, in crypto_price
    asyncio.get_event_loop().run_until_complete(main())
  File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\asyncio\events.py", line 642, in get_event_loop
    raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'Thread-2'.

您正在嘗試在主線程以外的某個線程中運行asyncio.get_event_loop() - 但是,asyncio 只會為主線程生成一個事件循環。

而是使用new_event_loop

asyncio.new_event_loop().run_until_complete(main())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM