我正在寻找获取多部分表单数据并将其转换为字典。对于 json 来说很简单,但这似乎有点不同。
当前代码:
app = web.Application()
async def deploy(request):
# retrieve multipart form data or
# x-www-form-urlencoded data
# convert to a dictionary if not already
text = "Hello"
return web.Response(text=text)
app.router.add_post('/', deploy)
web.run_app(app)
Run Code Online (Sandbox Code Playgroud) 我对图书馆越来越熟悉,但我被以下情况难住了:
我希望不断处理来自两个不同网站的 websocket 的更新消息。
但是我无法使用单个会话变量实现这一点,因为 aiohttp.ClientSession() 对象应该存在于协程中。
import asyncio
import aiohttp
url1 = 'wss://example.com'
async def main():
session = aiohttp.ClientSession()
async with session.ws_connect(url1) as ws1:
async for msg in ws1:
# do some processing
loop = asyncio.get_event_loop()
loop.create_task(main())
loop.run_forever()
Run Code Online (Sandbox Code Playgroud)
以上将适用于单个 websocket 连接。但是因为ws:中的async for msg是一个无限循环,所以我看不到我可以把这个异步循环的 ws2 版本放在哪里。
浏览器使用 vue element-ui el-upload 组件上传文件,aiohttp 作为后端接收表单数据然后保存。但是 aiohttp request.multipart() 总是空白,但 request.post() 就可以了。
视图:
<el-upload class="image-uploader"
:data="dataObj"
drag
name="aaa"
:multiple="false"
:show-file-list="false"
:action="action" -> upload url,passed from outer component
:on-success="handleImageScucess">
<i class="el-icon-upload"></i>
</el-upload>
export default {
name: 'singleImageUpload3',
props: {
value: String,
action: String
},
methods: {
handleImageScucess(file) {
this.emitInput(file.files.file)
},
}
Run Code Online (Sandbox Code Playgroud)
aiohttp:不工作
async def post_image(self, request):
reader = await request.multipart()
image = await reader.next()
print (image.text())
filename = image.filename
print (filename)
size = 0
with open(os.path.join('', 'aaa.jpg'), 'wb') as f:
while True: …Run Code Online (Sandbox Code Playgroud) 我正在尝试将 Python HTTP 客户端转换requests为aiohttp. 逻辑是将 GET 调用发送到 REST 端点,该端点偶尔会传输数据并打印它返回的行。
我有一个使用带有选项和 的请求的代码,它工作得很好:stream=Trueiter_lines
import json
import requests
def main():
with requests.get('https://my-streaming-url.com', stream=True) as r:
if r.encoding is None:
r.encoding = 'utf-8'
for line in r.iter_lines(decode_unicode=True):
if line:
# Print each line emitted by the streaming api
print(json.loads(line))
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
现在,我想将此逻辑转换为aiohttp 流 api并尝试:
import asyncio
import aiohttp
import json
loop = asyncio.get_event_loop()
async def main():
r = aiohttp.request('get', 'https://my-streaming-url.com')
async …Run Code Online (Sandbox Code Playgroud) 我希望传递params和headers到aiohttp.ClientSession如图所示这里。
这是我尝试过的:
async def make_request(self, url, headers, params):
async with aiohttp.ClientSession(headers=headers, params=params) as session:
async with self.limit, session.get(url=url) as response:
await asyncio.sleep(self.rate)
resp = await response.read()
return resp
Run Code Online (Sandbox Code Playgroud)
async def process(url, url_id, update_id, rate, limit):
limit = asyncio.BoundedSemaphore(limit)
f = Fetch(
rate=rate,
limit=limit,
)
if "coinmarketcap" in url:
params = {
'start': '1',
'limit': '1',
'convert': 'USD,BTC'
}
headers = {
'Accepts': 'application/json',
'X-CMC_PRO_API_KEY': API_KEY,
}
else:
params = {}
headers = …Run Code Online (Sandbox Code Playgroud) 我打算在 PyQt 应用程序中嵌入 aiohttp 服务器,但是当我运行下面的代码时,Qt 窗口无法显示,我知道这是由 引起的web.run_app(app),我尝试将其移动到线程中,但是然后我明白了RuntimeError: There is no current event loop in thread \'Dummy-1\',那我该怎么办?我发现asyncqt可能会有所帮助,但我不知道如何使用它来处理 aiohttp 服务器。
from PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\nfrom aiohttp import web\n\n\nclass ThreadGo(QThread): # threading.Thread\n # implementing new slots in a QThread subclass is error-prone and discouraged.\n\n def __init__(self, parent, func, *args, **kwargs):\n super().__init__(parent)\n self.func = func\n self.args = args\n self.kwargs = kwargs\n self.result = 0\n\n onFinished = self.kwargs.get(\'onFinished\')\n self.finished.connect(onFinished) if onFinished else None …Run Code Online (Sandbox Code Playgroud) 我正在使用httpx库,但我认为aiohttp的原理是相同的。如果我在应用程序的整个生命周期中为多个请求创建并重用 AsyncClient,我是否需要在应用程序关闭事件时调用aclose()(或者如果使用 Client)?close或者这些联系会自行消失。
如果我在 Docker 容器中运行应用程序会怎样?这也会是一个因素吗?
我不明白 AsyncClient 或 Client (或 aoihttp 中的 ClientSession)对象下面发生了什么。
感谢帮助。
以前,我用于asyncio.wait_for超时控制,效果很好。最近,我学习了aiohttp软件包,发现它用于asyncio_timeout.timeout超时控制。然后我阅读了asyncio_timeout 的github页面(https://github.com/aio-libs/async-timeout)。作者声称它运行的速度比快asyncio.wait_for。所以我有两个问题:
asyncio_timeout.timeout完全取代asyncio.wait_for吗?我是否应该全部更换asyncio.wait_for以提高速度?我正在编写一个websocket客户端,asyncio.wait_for当前控制websocket.recv它被频繁调用。asyncio_timeout.timeout应该将其与一起使用async with。但是,在aiohttp帮助页面中,它们with代替async with(http://aiohttp.readthedocs.io/en/stable/)使用。那么哪一个是正确的呢?我的程序执行以下操作:
我担心程序的同步版本的性能,所以试图aiohttp使其异步(这是我在Python中除了Scrapy之外的第一次异步编程尝试).原来,异步代码花了2倍的时间,我不明白为什么.
同步代码(152秒)
url = "http://localhost:6090/api/analyzexml"
package = #name of the package I send in each requests
with open("template.txt", "r", encoding="utf-8") as f:
template = f.read()
articles_path = #location of my text files
def fetch(session, url, article_text):
data = {"package": package, "data": template.format(article_text)}
response = session.post(url, data=json.dumps(data))
print(response.text)
files = glob(os.path.join(articles_path, "*.txt"))
with requests.Session() as s:
for file in files:
with open(file, "r", encoding="utf-8") as f:
article_text = f.read()
fetch(s, url, article_text)
Run Code Online (Sandbox Code Playgroud)
分析结果: …
我想知道是否有任何方法可以使此脚本更快,例如立即创建1000个帐户,或者至少在几秒钟内创建一个帐户。我已经尝试过自己做一些异步的事情,但这是我所能做到的,我只是异步编程的初学者,所以可以提供任何帮助。
import asyncio
import aiohttp
async def make_numbers(numbers, _numbers):
for i in range(numbers, _numbers):
yield i
async def make_account():
url = "https://example.com/sign_up.php"
async with aiohttp.ClientSession() as session:
async for x in make_numbers(35691, 5000000):
async with session.post(url, data ={
"terms": 1,
"captcha": 1,
"email": "user%s@hotmail.com" % str(x),
"full_name": "user%s" % str(x),
"password": "123456",
"username": "auser%s" % str(x)
}) as response:
data = await response.text()
print("-> Creating account number %d" % x)
print (data)
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(make_account())
finally:
loop.close()
Run Code Online (Sandbox Code Playgroud) aiohttp ×10
python ×8
python-3.x ×3
fastapi ×1
httprequest ×1
httpx ×1
pyqt ×1
pyqt5 ×1
python-3.5 ×1
streaming ×1
vue.js ×1