怎么if __name__ == "__main__":
办?
# Threading example
import time, thread
def myfunction(string, sleeptime, lock, *args):
while True:
lock.acquire()
time.sleep(sleeptime)
lock.release()
time.sleep(sleeptime)
if __name__ == "__main__":
lock = thread.allocate_lock()
thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))
Run Code Online (Sandbox Code Playgroud) 我有以下代码:
import time
from fastapi import FastAPI, Request
app = FastAPI()
@app.get("/ping")
async def ping(request: Request):
print("Hello")
time.sleep(5)
print("bye")
return {"ping": "pong!"}
Run Code Online (Sandbox Code Playgroud)
如果我在本地主机上运行我的代码 - 例如http://localhost:8501/ping
- 在同一浏览器窗口的不同选项卡中,我得到:
Hello
bye
Hello
bye
Run Code Online (Sandbox Code Playgroud)
代替:
Hello
Hello
bye
bye
Run Code Online (Sandbox Code Playgroud)
我已经阅读过有关使用的内容httpx
,但仍然无法实现真正的并行化。有什么问题?
python asynchronous concurrent-processing python-asyncio fastapi
我正在尝试将我的服务器配置为请求超时,但我找不到有关它的任何信息。我看到uvicorn
有一个名为 的属性keep_alive_timeout
,默认为 5 秒。但这似乎也不起作用。
例如:
app = FastAPI()
@app.get('/test')
def test_endpoint():
sleep(10)
Run Code Online (Sandbox Code Playgroud)
我希望请求在 5 秒后断开连接并超时,但它仍然存在并返回 200。
有人知道如何设置吗?
我正在调试 FastAPI 应用程序,并且遇到了与本文中提到的问题类似的问题:asyncio.wait_for
对应该超时的调用却没有超时:
try:
await wait_for(completion_event.wait(), 1.0)
except TimeoutError:
logging.info("timeout")
return SubmissionResult(post_id=post_id, language_check_pending=True)
Run Code Online (Sandbox Code Playgroud)
此代码片段是 FastAPI 的 POST 请求处理程序的一部分。这里,completion_event
是一个asyncio.Event
对象。我可以在带有 的行上放置一个断点wait_for
,观察它卡住超过 1 秒的时间,然后直接移过该except
块。毫无疑问,这wait_for
并没有达到预期的效果。
我不知道为什么它会这样。此时,我开始怀疑 FastAPI 的内部结构,因为它使用uvloop作为“更快的异步替代品”。但我不知道如何检验这个假设,更不知道如何解决这个问题(如果确实如此)。
有什么建议么?