apitools.py 文件源码

python
阅读 25 收藏 0 点赞 0 评论 0

项目:ORELS-Cogs 作者: orels1 项目源码 文件源码
def _post(self, ctx, *, url):
        """Performs POST or PUT request to selected URL"""

        await self.bot.say('Set headers by typing them in a `name=value` format, one on each line, or `pass`')

        answer = await self.bot.wait_for_message(timeout=50, author=ctx.message.author)

        parsed = self._parse_headers(answer)
        headers = parsed['headers']
        public_headers = parsed['public_headers']

        await self.bot.say('Headers are set to:\n```json\n{}```\nSet body typing in in a `name=value` one on each line or `pass`\nNested objects are not supported'
                           .format(json.dumps(public_headers, indent=4, sort_keys=True)))

        answer = await self.bot.wait_for_message(timeout=50, author=ctx.message.author)

        body = self._parse_body(answer)

        await self.bot.say('Body is set to:\n```json\n{}```'.format(json.dumps(body, indent=4, sort_keys=True)))

        url = url.strip()
        method = ctx.invoked_with

        if method == 'post':
            t1 = time.perf_counter()
            async with aiohttp.post(url, headers=headers, data=json.dumps(body)) as r:
                t2 = time.perf_counter()
                data = await r.text()
                status = r.status

        if method == 'put':
            if 'Content-Type' not in headers:
                headers['Content-Type'] = 'application/json'

            t1 = time.perf_counter()
            async with aiohttp.put(url, headers=headers, data=json.dumps(body)) as r:
                t2 = time.perf_counter()
                data = await r.text()
                status = r.status

        try:
            parsed = json.loads(data)
        except:
            parsed = json.loads('{}')

        color = status == 200 and 0x2ecc71 or status >= 400 and 0xe74c3c
        embed = discord.Embed(title='Results for **{}** {}'.format(method.upper(), url),
                              color=color,
                              description='```json\n{}```'.format(len(data) < 700
                                                                  and
                                                                  json.dumps(parsed, indent=4, sort_keys=True)
                                                                  or
                                                                  json.dumps(parsed, indent=4, sort_keys=True)[:700]
                                                                  + '\n\n...\n\n'))
        embed.add_field(name='Status',
                        value=status)
        embed.add_field(name='Time',
                        value='{}ms'.format(str((t2-t1) * 1000)[:3]))
        await self.bot.say(embed=embed)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号