小编amo*_*ian的帖子

使用aiohttp和asyncio时编写单元测试

我正在更新我的一个Python包,所以它是异步的(使用aiohttp而不是requests).我也在更新我的单元测试,所以他们使用新的异步版本,但我遇到了一些问题.

这是我的包中的一个片段:

async def fetch(session, url):
    while True:
        try:
            async with session.get(url) as response:
                assert response.status == 200
                return await response.json()
        except Exception as error:
            pass


class FPL():
    def __init__(self, session):
        self.session = session

    async def get_user(self, user_id, return_json=False):
        url = API_URLS["user"].format(user_id)
        user = await fetch(self.session, url)

        if return_json:
            return user
        return User(user, session=self.session)
Run Code Online (Sandbox Code Playgroud)

所有这些似乎都在使用时如此:

async def main():
    async with aiohttp.ClientSession() as session:
         fpl = FPL(session)
         user = await fpl.get_user(3808385)
         print(user)

loop = asynio.get_event_loop()
loop.run_until_complete(main())

>>> …
Run Code Online (Sandbox Code Playgroud)

python python-asyncio aiohttp

7
推荐指数
1
解决办法
1454
查看次数

如何从 PRAW 中的提交对象获取 url?

我正在使用 PRAW 创建一个每天提交一次内容的 Reddit 机器人。提交后我想保存提交的 url 并将其写入文本文件。

url = r.submit(subreddit, submission_title, text=submission_text)
Run Code Online (Sandbox Code Playgroud)

以上返回一个提交对象,但我想要实际的网址。有没有办法从提交对象中获取 url,或者我是否需要做其他事情来获取 url?

python praw

5
推荐指数
2
解决办法
3500
查看次数

使用 pytest 在 Flask 中测试服务器发送的事件

我有一个 Flask 应用程序,我使用服务器发送的事件将数据发送到我的前端。

@bp.route("/stream", methods=("GET",))
def stream_translations():
    translation_schema = TranslationSchema()

    def event_stream():
        while True:
            recently_updated = [
                translation_schema.dump(translation)
                for translation in recently_updated_translations()]
            if recently_updated:
                yield f"data: {json.dumps(recently_updated)}\n\n"

    return Response(event_stream(), mimetype="text/event-stream")
Run Code Online (Sandbox Code Playgroud)

它工作得很好,但我也想为其编写一个测试来确定。我以前从未为生成器编写过测试,并且绝对不是服务器发送的事件。目前,这就是我所拥有的:

def test_stream(client):
    response = client.get("/translations/stream")

    assert response.status_code == 200
    assert response.mimetype == "text/event-stream"
Run Code Online (Sandbox Code Playgroud)

当然这只是测试响应,但我还想测试event_stream()生成器。我该怎么做呢?

python pytest flask flask-sqlalchemy

5
推荐指数
1
解决办法
1175
查看次数

Next.js 具有 i18n 和共享组件的多区域

我将 Next.js 的多区域功能与博客和 Web 应用程序一起使用,这样我就可以独立开发和部署这两个应用程序。通过遵循他们的区域示例很容易设置,我已经在 port 处设置了一个博客应用程序,4200并在 port 处设置了一个网络应用程序3000,运行良好。不幸的是,我遇到了一些在其文档中没有描述的问题(据我所知)。

首先,我还使用他们的国际化路由,该路由工作正常,但是当访问我的博客应用程序时,它将区域设置附加到 URL 的末尾。想象一下,我正在打开localhost:3000/en并导航到博客应用程序,然后它将显示localhost:4200/blog/en而不是localhost:4200/en/blog. 有什么办法可以解决这个问题(例如通过使用重写)吗?

其次,我正在 monorepo 中工作,并且在两个应用程序之间共享组件,例如页眉和页脚,其中显然包括导航。当我在博客上并想要导航到例如页面时/about,它显然会导航到localhost:4200/blog/about而不是localhost:3000/about。一种解决方案是检查导航组件中的基本路径,然后localhost:3000href基本路径等于之前添加blog,但这会刷新整个应用程序并且不会导致流畅的导航,因此它并不理想。对此我还能做些什么吗?

看来多区域功能实际上只适合非常小的应用程序,或者我错过了一些东西。似乎其他人也有同样的问题,如果我遗漏了什么,那么文档至少肯定是这样。

javascript internationalization reactjs monorepo next.js

5
推荐指数
0
解决办法
1564
查看次数

使用matplotlib.pyplot.imshow()时如何确定颜色?

我正在使用imshow()来绘制2D numpy数组,例如:

my_array = [[ 2.  0.  5.  2.  5.]
            [ 3.  2.  0.  1.  4.]
            [ 5.  0.  5.  4.  4.]
            [ 0.  5.  2.  3.  4.]
            [ 0.  0.  3.  5.  2.]]

plt.imshow(my_array, interpolation='none', vmin=0, vmax=5)
Run Code Online (Sandbox Code Playgroud)

绘制此图像:

在此输入图像描述

然而,我想要做的是改变颜色,例如0是RED,1是GREEN,2是ORANGE,你明白我的意思.有没有办法做到这一点,如果是这样,怎么样?

我试过通过更改colourmap中的条目来尝试这样做,如下所示:

    cmap = plt.cm.jet
    cmaplist = [cmap(i) for i in range(cmap.N)]
    cmaplist[0] = (1,1,1,1.0)
    cmaplist[1] = (.1,.1,.1,1.0)
    cmaplist[2] = (.2,.2,.2,1.0)
    cmaplist[3] = (.3,.3,.3,1.0)
    cmaplist[4] = (.4,.4,.4,1.0)
    cmap = cmap.from_list('Custom cmap', cmaplist, cmap.N)
Run Code Online (Sandbox Code Playgroud)

但它没有像我预期的那样工作,因为0 =颜色映射中的第一个条目,但是例如1!!=颜色映射中的第二个条目,因此只有0被不同地绘制:

在此输入图像描述

python colors matplotlib draw

3
推荐指数
1
解决办法
1387
查看次数

将子流程与traceroute一起使用时没有错误输出

我正在尝试获取traceroute失败时返回的错误消息。例如:

from subprocess import CalledProcessError, check_output

try: 
    output = check_output(["traceroute", "error"])
except CalledProcessError as error:
    output = error.output

print "error: {}".format(output)
Run Code Online (Sandbox Code Playgroud)

输出:

error:
Run Code Online (Sandbox Code Playgroud)

我尝试使用,output = str(error.output)但输出保持为空。执行上述代码时,将在终端上显示一条错误消息,因此应该可以将其分配给变量,对吗?

python error-handling subprocess traceroute

3
推荐指数
1
解决办法
711
查看次数

Next.js 中使用 TypeScript 和 HOC 的持久布局

我想向 Next.js 应用程序的某些页面添加持久布局。我发现这篇文章解释了人们如何做到这一点的几种方法。看起来很简单,但是在使用推荐的方法时我遇到了以下两个问题:

  1. 我正在使用 TypeScript,但不确定如何输入。例如,我有以下工作,但我显然不喜欢使用as any
const getLayout =
    (Component as any).getLayout ||
    ((page: NextPage) => <SiteLayout children={page} />);
Run Code Online (Sandbox Code Playgroud)
  1. 我正在使用 Apollo,因此我正在为某些页面使用withApolloHOC(来自此处)。使用这个会导致Component.getLayout总是undefined。我对正在发生的事情没有足够的了解来知道为什么会发生这种情况(我可以猜到),所以我自己很难解决这个问题。

typescript reactjs higher-order-components next.js

3
推荐指数
2
解决办法
3024
查看次数

在类中使用时关闭 aiohttp ClientSession

我有以下代码

session = aiohttp.ClientSession()


async def fetch(session, url):
    while True:
        try:
            async with session.get(url) as response:
                assert response.status == 200
                return await response.json()
        except Exception as error:
            print(error)



class FPL():
    async def get_player_summaries(self, player_ids=[], return_json=False):
        tasks = [asyncio.ensure_future(
                fetch(session, API_URLS["player"].format(player_id)))
                for player_id in player_ids]

        player_summaries = await asyncio.gather(*tasks)

        if return_json:
            return player_summaries

        return [PlayerSummary(player_summary)
                for player_summary in player_summaries]

    async def get_points_against(self):
        players = await self.get_players(return_json=True)
        player_ids = [player["id"] for player in players]
        player_summaries = await self.get_player_summaries(
            player_ids, return_json=True)
        points_against = …
Run Code Online (Sandbox Code Playgroud)

python python-asyncio aiohttp

1
推荐指数
1
解决办法
4225
查看次数