返回提交历史
Modified
g4f/Provider/base_provider.py
+7
-0
Modified
g4f/Provider/helper.py
+17
-21
XFEstudio/gpt4free
Patch event loop on win, Check event loop closed
ebc52215
代码差异
2 个文件
+24
-21
@@ -13,6 +13,13 @@ if sys.version_info < (3, 10):
13
13
else:
14
14
from types import NoneType
15
15
16
# Change event loop policy on windows for curl_cffi
17
if sys.platform == 'win32':
18
if isinstance(
19
asyncio.get_event_loop_policy(), asyncio.WindowsProactorEventLoopPolicy
20
):
21
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
22
16
23
class BaseProvider(ABC):
17
24
url: str
18
25
working: bool = False
@@ -7,9 +7,9 @@ import random
7
7
import string
8
8
import secrets
9
9
import os
10
from os import path
11
from asyncio import AbstractEventLoop
12
from platformdirs import user_config_dir
10
from os import path
11
from asyncio import AbstractEventLoop
12
from platformdirs import user_config_dir
13
13
from browser_cookie3 import (
14
14
chrome,
15
15
chromium,
@@ -25,37 +25,33 @@ from browser_cookie3 import (
25
25
from ..typing import Dict, Messages
26
26
from .. import debug
27
27
28
# Change event loop policy on windows
29
if sys.platform == 'win32':
30
if isinstance(
31
asyncio.get_event_loop_policy(), asyncio.WindowsProactorEventLoopPolicy
32
):
33
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
34
35
28
# Local Cookie Storage
36
29
_cookies: Dict[str, Dict[str, str]] = {}
37
30
38
# If event loop is already running, handle nested event loops
31
# If loop closed or not set, create new event loop.
32
# If event loop is already running, handle nested event loops.
39
33
# If "nest_asyncio" is installed, patch the event loop.
40
34
def get_event_loop() -> AbstractEventLoop:
41
35
try:
42
asyncio.get_running_loop()
36
loop = asyncio.get_event_loop()
37
loop._check_closed()
43
38
except RuntimeError:
44
try:
45
return asyncio.get_event_loop()
46
except RuntimeError:
47
asyncio.set_event_loop(asyncio.new_event_loop())
48
return asyncio.get_event_loop()
39
loop = asyncio.new_event_loop()
40
asyncio.set_event_loop(loop)
49
41
try:
50
event_loop = asyncio.get_event_loop()
51
if not hasattr(event_loop.__class__, "_nest_patched"):
42
# Is running event loop
43
asyncio.get_running_loop()
44
if not hasattr(loop.__class__, "_nest_patched"):
52
45
import nest_asyncio
53
nest_asyncio.apply(event_loop)
54
return event_loop
46
nest_asyncio.apply(loop)
47
except RuntimeError:
48
# No running event loop
49
pass
55
50
except ImportError:
56
51
raise RuntimeError(
57
52
'Use "create_async" instead of "create" function in a running event loop. Or install the "nest_asyncio" package.'
58
53
)
54
return loop
59
55
60
56
def init_cookies():
61
57
urls = [