我正在尝试将flask应用程序移植quart到使用asyncio. 我认为我目前的方法行不通,因为我的整个函数链是在没有考虑异步的情况下编写的 - 考虑以下几点:
def long_running_task(task):
result = some_synchronous_function(task)
return result
@app.route('/<task>', methods=['GET'])
async def do_task(task):
ok = await long_running_task(task)
if ok:
return (ok.result)
else:
return ('Something went wrong')
Run Code Online (Sandbox Code Playgroud)
如果long_running_task和它的整个函数调用链都没有声明为async,我是否真的从我的路由被声明为中得到任何好处async?
尝试测试Flask应用程序时出现问题,无法访问该g变量。
经过测试的api如下所示:
user = query_object.get(g.user_id) # here the exception raises
Run Code Online (Sandbox Code Playgroud)
当我运行测试时,它会引发:
NameError: global name 'g' is not defined
Run Code Online (Sandbox Code Playgroud) 我仍然对asyncio如何工作感到困惑,所以我试图设置一个简单的例子但是无法实现它.
以下示例是一个Web服务器(Quart),它接收生成大型PDF的请求,然后服务器在开始处理PDF之前返回响应,然后开始处理它,并稍后将下载链接发送到电子邮件.
from quart import Quart
import asyncio
import time
app = Quart(__name__)
@app.route('/')
async def pdf():
t1 = time.time()
await generatePdf()
return 'Time to execute : {} seconds'.format(time.time() - t1)
async def generatePdf():
await asyncio.sleep(5)
#sync generatepdf
#send pdf link to email
app.run()
Run Code Online (Sandbox Code Playgroud)
我该怎么做?在上面的例子中,我不希望在返回之前等待5秒.
我甚至不确定asyncio是否是我需要的.
我担心在响应返回后阻止服务器应用程序不是应该做的事情,但也不确定.
此外,pdf库是同步的,但我想这是另一天的问题......
如何在Quart中的另一个异步方法内调用在主线程中获取事件循环的异步方法?
t.py
from telethon import TelegramClient, functions, types
client2 = TelegramClient(sn, api_id, api_hash).start()
async def create_contact():
return await client2(functions.contacts.ImportContactsRequest([
types.InputPhoneContact(0, '8', 'first_name', 'last_name')
]))
Run Code Online (Sandbox Code Playgroud)
应用程序
from quart import Quart, websocket,render_template,request
import t2
app = Quart(__name__)
@app.route('/wa2tg')
def wa2tg():
return render_template('wa2tg.html',nm=request.args.get('nm',''))
@app.websocket('/wa2tg2')
async def wa2tg2():
while True:
data = await websocket.receive()
await t2.create_contact()
# Thread(target=tele.client2.run_until_disconnected).start()
app.run(debug=1)
Run Code Online (Sandbox Code Playgroud)
错误:
Running on http://127.0.0.1:5000 (CTRL + C to quit)
[2019-06-21 16:31:42,035] 127.0.0.1:51696 GET /wa2tg 1.1 200 553 12995
[2019-06-21 16:31:42,486] 127.0.0.1:51698 GET /wa2tg2 1.1 101 …Run Code Online (Sandbox Code Playgroud) 我正在使用 Quart,我真的很想将 Socket.IO 与它一起使用,但我找不到 Quart 的 Socket.IO 集成,仅适用于 Flask。我应该尝试烧瓶版本还是没有办法?
你好,我对Python相当陌生,我正在尝试将Flask上的现有应用程序转换为Quart(https://gitlab.com/pgjones/quart),它应该构建在asyncio之上,所以我可以使用Goblin OGM 与 JanusGraph 或 TinkerPop 交互。根据我在 Goblin 上找到的示例,我需要获取一个事件循环来异步运行命令。
>>> import asyncio
>>> from goblin import Goblin
>>> loop = asyncio.get_event_loop()
>>> app = loop.run_until_complete(
... Goblin.open(loop))
>>> app.register(Person, Knows)
Run Code Online (Sandbox Code Playgroud)
然而,我找不到从 Quart 获取事件循环的方法,即使它是构建在 asyncio 之上的。
有谁知道我怎样才能得到它?任何帮助将不胜感激。
我试图将 pyppeteer 和 quart 结合起来,但由于启动浏览器需要花费很多时间,我宁愿全局处理它(使用异步锁),这似乎意味着我需要手动处理清理。这是我的最小代码示例:
\n\n#!/usr/bin/env python3\n\nimport asyncio\nimport atexit\nimport pyppeteer\n\nfrom quart import Quart, Response, request\n\napp = Quart(__name__)\nbrowser = asyncio.get_event_loop().run_until_complete(pyppeteer.launch())\n\nasync def cleanup_async():\n await browser.quit()\n\n@atexit.register\ndef cleanup():\n asyncio.get_event_loop().run_until_complete(cleanup_async())\nRun Code Online (Sandbox Code Playgroud)\n\n问题如下:
\n\n[22:26:53] \xe2\x9e\x9c strokes git:(async_browser) \xe2\x9c\x97 % QUART_APP=/tmp/quart_cleanup.py timeout 10s quart run -h 0.0.0.0\nRunning on http://0.0.0.0:5000 (CTRL + C to quit)\nTraceback (most recent call last):\n File "/home/d33tah/virtualenv-py3/bin/quart", line 11, in <module>\n sys.exit(main())\n File "/home/d33tah/virtualenv-py3/lib/python3.6/site-packages/quart/cli.py", line 208, in main\n cli.main(args=args, prog_name=name)\n File "/home/d33tah/virtualenv-py3/lib/python3.6/site-packages/quart/cli.py", line 152, in main\n return super().main(*args, **kwargs)\n File "/home/d33tah/virtualenv-py3/lib/python3.6/site-packages/click/core.py", line …Run Code Online (Sandbox Code Playgroud) 按照Izmailoff 博客文章中设置的示例,我能够从 Flask 向用户发送远程文件,但是当我切换到Quart时,我开始收到TypeError: 'function' object is not iterable错误。
该代码几乎与博客上的完全相同,我尝试使用await但无济于事,因为它出错了object Response can't be used in 'await' expression。
我的代码如下,raw_url直接访问URL:
req = requests.get(raw_url, stream=True)
return Response(stream_with_context(req.iter_content()), content_type=req.headers['content-type'])
Run Code Online (Sandbox Code Playgroud) 我正在 Python 3.8 中尝试 Quart 和 Hypercorn。据我了解,Quart 通常用于单线程应用程序。但我看到 Hypercorn 有一个--workers运行该应用程序的选项。
workers w, --workers The number of workers to spawn and use.
Run Code Online (Sandbox Code Playgroud)
单线程应用程序如何从使用多个工作线程中受益?
我有一个Python3.9 / Quart / Hypercorn 微服务,它在配置有environment.yml 文件的conda 环境中运行。基础镜像是 Continumio/miniconda3。
由于 conda init 问题等,花了很多功夫才启动这个项目。
是否有一种更干净的方法可以在 Docker 中安装并激活 conda 环境,而不必求助于 conda run 命令并覆盖默认的 SHELL 命令?
FROM continuumio/miniconda3
COPY . /api/
WORKDIR /api/src
# See this tutorial for details https://pythonspeed.com/articles/activate-conda-dockerfile/
RUN conda env create -f /api/conda_environment_production.yml
SHELL ["conda", "run", "-n", "ms-amazing-environment", "/bin/bash", "-c"]
ENTRYPOINT ["conda", "run", "--no-capture-output", "-n", "ms-amazing-environment", "hypercorn", "--bind", "0.0.0.0:5000", "QuartAPI:app"]
EXPOSE 5000
Run Code Online (Sandbox Code Playgroud)