【小沐学Python】Python实现Web服务器(aiohttp)

文章目录

  • 1、简介
  • 2、下载和安装
  • 3、代码测试
    • 3.1 客户端
    • 3.2 服务端
  • 4、更多测试
    • 4.1 asyncio
    • 4.2 aiohttp+HTTP服务器
    • 4.3 aiohttp+爬虫实例
    • 4.4 aiohttp+requests比较
  • 结语

1、简介

https://github.com/aio-libs/aiohttp
https://docs.aiohttp.org/en/stable/index.html

Asynchronous HTTP client/server framework for asyncio and Python
异步 http 客户端/服务器框架

在这里插入图片描述

在这里插入图片描述
主要特点:

  • 支持 HTTP 协议的客户端和服务器端。
  • 支持开箱即用的客户端和服务器 Web 套接字,并避免 回调地狱。
  • 为 Web 服务器提供中间件和可插拔路由。

2、下载和安装

在这里插入图片描述
安装库:

pip3 install aiohttp
# pip install aiodns
# pip install aiohttp[speedups]

在这里插入图片描述

3、代码测试

3.1 客户端

  • 客户端:要从网络上获取某些内容。
import aiohttp
import asyncio

async def main():

    async with aiohttp.ClientSession() as session:
        async with session.get('https://www.baidu.com/') as response:

            print("Status:", response.status)
            print("Content-type:", response.headers['content-type'])

            html = await response.text()
            print("Body:", html[:15], "...")

asyncio.run(main())

运行之后:
在这里插入图片描述
报错了。
修改代码如下:

import aiohttp
import asyncio

async def main():

    async with aiohttp.ClientSession() as session:
        async with session.get('https://www.baidu.com/') as response:

            print("Status:", response.status)
            print("Content-type:", response.headers['content-type'])

            html = await response.text()
            print("Body:", html[:15], "...")

# asyncio.run(main())
loop = asyncio.get_event_loop()
loop.run_until_complete(main())

再次运行之后,没有报错。
在这里插入图片描述

3.2 服务端

  • 服务器:使用简单服务器的示例。
# examples/server_simple.py
from aiohttp import web

async def handle(request):
    name = request.match_info.get('name', "Anonymous")
    text = "Hello, " + name
    return web.Response(text=text)

async def wshandle(request):
    ws = web.WebSocketResponse()
    await ws.prepare(request)

    async for msg in ws:
        if msg.type == web.WSMsgType.text:
            await ws.send_str("Hello, {}".format(msg.data))
        elif msg.type == web.WSMsgType.binary:
            await ws.send_bytes(msg.data)
        elif msg.type == web.WSMsgType.close:
            break

    return ws


app = web.Application()
app.add_routes([web.get('/', handle),
                web.get('/echo', wshandle),
                web.get('/{name}', handle)])

if __name__ == '__main__':
    web.run_app(app)

运行之后:
在这里插入图片描述
浏览器访问网址:

http://127.0.0.1:8080/

在这里插入图片描述
在这里插入图片描述

4、更多测试

4.1 asyncio

asyncio是Python 3.4版本引入的标准库,直接内置了对异步IO的支持。

asyncio的编程模型就是一个消息循环。我们从asyncio模块中直接获取一个EventLoop的引用,然后把需要执行的协程扔到EventLoop中执行,就实现了异步IO。

import asyncio

@asyncio.coroutine
def hello():
    print("Hello world!111")
    print("Hello world!22")
    # 异步调用asyncio.sleep(1):
    r = yield from asyncio.sleep(1)
    print("Hello again!333")
    print("Hello again!444")

# 获取EventLoop:
loop = asyncio.get_event_loop()
# 执行coroutine
loop.run_until_complete(hello())
loop.close()

在这里插入图片描述

import threading
import asyncio

@asyncio.coroutine
def hello():
    print('Hello world! (%s)' % threading.currentThread())
    yield from asyncio.sleep(1)
    print('Hello again! (%s)' % threading.currentThread())

loop = asyncio.get_event_loop()
tasks = [hello(), hello()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()

在这里插入图片描述

import asyncio

@asyncio.coroutine
def wget(host):
    print('wget %s...' % host)
    connect = asyncio.open_connection(host, 80)
    reader, writer = yield from connect
    header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host
    writer.write(header.encode('utf-8'))
    yield from writer.drain()
    while True:
        line = yield from reader.readline()
        if line == b'\r\n':
            break
        print('%s header > %s' % (host, line.decode('utf-8').rstrip()))
    # Ignore the body, close the socket
    writer.close()

loop = asyncio.get_event_loop()
tasks = [wget(host) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()

在这里插入图片描述
asyncio提供了完善的异步IO支持;
异步操作需要在coroutine中通过yield from完成;

4.2 aiohttp+HTTP服务器

编写一个HTTP服务器:

import asyncio

from aiohttp import web

async def index(request):
    await asyncio.sleep(0.5)
    return web.Response(text='<h1>Index</h1>', content_type= 'text/html')

async def hello(request):
    await asyncio.sleep(0.5)
    text = '<h1>hello, %s!</h1>' % request.match_info['name']
    return web.Response(text=text, content_type= 'text/html')

async def init(loop):
    app = web.Application(loop=loop)
    app.router.add_route('GET', '/', index)
    app.router.add_route('GET', '/hello/{name}', hello)
    srv = await loop.create_server(app.make_handler(), '127.0.0.1', 8000)
    print('Server started at http://127.0.0.1:8000...')
    return srv

loop = asyncio.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()

在这里插入图片描述
在这里插入图片描述

4.3 aiohttp+爬虫实例

pip install bs4 

编写一个爬虫实例:

import asyncio
import aiohttp
from bs4 import BeautifulSoup
import logging

class AsnycSpider(object):

    def __init__(self, url_list, max_threads):

        self.urls = url_list
        self.results = {}
        self.max_threads = max_threads

    def __parse_results(self, url, html):
        try:
            soup = BeautifulSoup(html, 'html.parser')
            title = soup.find('title').get_text()
        except Exception as e:
            raise e

        if title:
            self.results[url] = title

    async def get_body(self, url):
        async with aiohttp.ClientSession() as session:
            async with session.get(url, timeout=30) as response:
                assert response.status == 200
                html = await response.read()
                return response.url, html

    async def get_results(self, url):
        url, html = await self.get_body(url)
        self.__parse_results(url, html)
        return 'Completed'

    async def handle_tasks(self, task_id, work_queue):
        while not work_queue.empty():
            current_url = await work_queue.get()
            try:
                task_status = await self.get_results(current_url)
            except Exception as e:
                logging.exception('Error for {}'.format(current_url), exc_info=True)

    def eventloop(self):
        q = asyncio.Queue()
        [q.put_nowait(url) for url in self.urls]
        loop = asyncio.get_event_loop()
        tasks = [self.handle_tasks(task_id, q, ) for task_id in range(self.max_threads)]
        loop.run_until_complete(asyncio.wait(tasks))
        # loop.close()

if __name__ == '__main__':
    async_example = AsnycSpider([
        'https://www.qq.com/',
        'https://www.163.com/',
        'https://news.baidu.com/',
        'https://blog.csdn.net/'], 5)
    async_example.eventloop()
    print(async_example.results)

在这里插入图片描述

4.4 aiohttp+requests比较

在 Python 众多的 HTTP 客户端中,有这几个:requests、aiohttp和httpx。在不借助其他第三方库的情况下,requests只能发送同步请求;aiohttp只能发送异步请求;httpx既能发送同步请求,又能发送异步请求。

pip install requests
  • test_requests.py
import random
import time
import datetime
import requests


def make_request(session):
    resp = session.get('http://httpbin.org/get')
    # result = resp.text
    # print(result)
    pass


def main():
    session = requests.Session()
    start = time.time()
    for _ in range(100):
        make_request(session)
    end = time.time()
    print(f'发送100次请求,耗时:{end - start}')


if __name__ == '__main__':
    main()

在这里插入图片描述

  • test_aiohttp.py
import aiohttp
import random
import datetime
import asyncio
import time

async def request(client):
    async with client.get('http://httpbin.org/get') as resp:
        # print(resp.status)
        # print(await resp.text())
        pass

async def main():
    async with aiohttp.ClientSession() as client:
        start = time.time()
        task_list = []
        for _ in range(100):
            req = request(client)
            task = asyncio.create_task(req)
            task_list.append(task)
        await asyncio.gather(*task_list)
        end = time.time()
    print(f'发送100次请求,耗时:{end - start}')

asyncio.run(main())

在这里插入图片描述

结语

如果您觉得该方法或代码有一点点用处,可以给作者点个赞,或打赏杯咖啡;╮( ̄▽ ̄)╭
如果您感觉方法或代码不咋地//(ㄒoㄒ)//,就在评论处留言,作者继续改进;o_O???
如果您需要相关功能的代码定制化开发,可以留言私信作者;(✿◡‿◡)
感谢各位大佬童鞋们的支持!( ´ ▽´ )ノ ( ´ ▽´)っ!!!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/267492.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

C/C++图型化编程

一、创建图形化窗口&#xff1a; 1.包含头文件&#xff1a; graphics.h:包含已经被淘汰的函数easyx.h:只包含最新的函数 2.两个函数就可以创建窗口&#xff1a; 打开&#xff1a;initgraph(int x,int y,int style);关闭&#xff1a;closegraph(); 3.窗口坐标的设置&#…

【眼镜】相关知识

眼镜相关 配眼镜可以事先了解的事情&#xff1a; 折射率&#xff1a;先说结论&#xff0c;高度数可以考虑选高折射率&#xff0c;低度数没必要。 折射率&#xff1a;1.50折射率 1.56折射率 1.60折射率 1.67折射率 1.71折射率 1.74折射率. 折射率越高&#xff0c;镜片越薄&a…

全面理解Stable Diffusion采样器

全面理解Stable Diffusion采样器 原文&#xff1a;Stable Diffusion Samplers: A Comprehensive Guide 在 AUTOMATIC1111 的 SD webui 中&#xff0c;有许多采样器&#xff08;sampler&#xff09;&#xff0c;如 Euler a&#xff0c;Heun&#xff0c;DDIM&#xff0c;… 什么是…

应急响应中的溯源方法

在发现有入侵者后&#xff0c;快速由守转攻&#xff0c;进行精准地溯源反制&#xff0c;收集攻击路径和攻击者身份信息&#xff0c;勾勒出完整的攻击者画像。 对内溯源与对内溯源 对内溯源&#xff1a;确认攻击者的行为 &#xff0c;分析日志 数据包等&#xff1b; 对外溯源&…

图像随机裁剪代码实现

原理 在计算机视觉领域&#xff0c;深度学习模型通常需要大量的训练数据才能获得良好的性能。然而&#xff0c;在实际应用中&#xff0c;我们可能面临训练数据不足的问题。为了解决这一问题&#xff0c;可以使用数据增强技术来扩充数据集。随机图像裁剪是其中一种简单而有效的…

系列十四、SpringBoot + JVM参数配置实战调优

一、SpringBoot JVM参数配置实战调优 1.1、概述 前面的系列文章大篇幅的讲述了JVM的内存结构以及各种参数&#xff0c;今天就使用SpringBoot项目实战演示一下&#xff0c;如何进行JVM参数调优&#xff0c;如果没有阅读过前面系列文章的朋友&#xff0c;建议先阅读后再看本篇文…

Windows系统安装 ffmpeg

下载及解压 ffmpeg官方下载地址&#xff1a;https://ffmpeg.org/download.html 下载好后将其解压至你想保存的位置中。 环境变量设置 打开Windows设置&#xff0c;在搜索框输入&#xff1a;系统高级设置。 新建环境变量&#xff0c;并输入bin目录具体位置。 安装检查 按住 w…

人工智能:从基础到前沿

人工智能&#xff1a;从基础到前沿 引言 当我们谈论“人工智能”&#xff08;AI&#xff09;时&#xff0c;我们其实是在谈论一个涵盖了众多学科、技术和应用的广阔领域。从计算机视觉到自然语言处理&#xff0c;从机器人学到深度学习&#xff0c;AI已经成为我们生活中不可或…

电脑上添加不了网络打印机的所有可能的原因,在这里差不多都能找到

在电脑上添加网络打印机通常很容易,但如果Windows无法很好识别或根本找不到它们呢?以下是一些快速解决方案。 无论你是升级到Windows 11还是仍在使用Windows 10,连接无线打印机都应该很容易。Windows应该能够自动连接到与你的电脑位于同一网络上的任何打印机。但有时,Windo…

大数据Doris(四十):聚合模型的局限性和ROLLUP的说明

文章目录 聚合模型的局限性和ROLLUP的说明 一、聚合模型的局限性

linux内存寻址原来那么简单

内存寻址 内存寻址听起来高大上&#xff0c;其实真实处理起来很简单&#xff0c;以常见的80x86架构为例&#xff0c;有三种不同的地址&#xff1a; 逻辑地址线性地址物理地址 内存控制单元(MMU)通过分段单元的硬件电路把一个逻辑地址转化为线性地址&#xff0c;通过分页单元的…

单例模式(C++实现)

RAII运用 只能在栈上创建对象 只能在堆上创建的对象 单例模式 设计模式 懒汉模式 解决线程安全 优化 饿汉模式 饿汉和懒汉的区别

Vue3学习(后端开发)

目录 一、安装Node.js 二、创建Vue3工程 三、用VSCode打开 四、源代码目录src 五、入门案例——手写src 六、测试案例 七、ref和reactive的区别 一、安装Node.js 下载20.10.0 LTS版本 https://nodejs.org/en 使用node命令检验安装是否成功 node 二、创建Vue3工程 在…

C语言--if...else语句【语法讲解】

一.if...else语句的介绍 if…else 语句是编程中常用的一种分支语句&#xff0c;用于根据条件执行不同的操作。 它的基本语法如下&#xff1a; if (条件表达式) {// 当条件表达式为真时执行的代码块 } else {// 当条件表达式为假时执行的代码块 } 当条件表达式为真时&#xff…

互联网上门洗衣洗鞋小程序优势有哪些?

互联网洗鞋店小程序相较于传统洗鞋方式&#xff0c;具有以下优势&#xff1b; 1. 便捷性&#xff1a;用户只需通过手机即可随时随地下单并查询&#xff0c;省去了许多不必要的时间和精力。学生们无需走出宿舍或校园&#xff0c;就能轻松预约洗鞋并取件。 2. 精准定位&#xff1…

前菜---二叉树+堆的小练习

目录 前言&#x1f3dc;️ 1. 二叉树性质总结⛱️ 1.2 性质3⏰ 2. 二叉树性质小练习&#x1f3d5;️ 3. 答案解析&#x1f4a1; 4. 堆概念结构小练习&#x1fa94; 5. 答案解析&#x1f9ff; 6. 前/中/后/层序遍历小练习&#x1f52b; 7. 答案解析&#x1f9fa; 后语…

祝大家圣诞节快乐

同时庆祝 JWFD 20周年

c++代码寻找USB00端口并添加打印机

USB00*端口的背景 插入USB端口的打印机&#xff0c;安装打印机驱动&#xff0c;在控制面板设备与打印机处的打印机对象上右击&#xff0c;可以看到打印机端口。对于不少型号&#xff0c;这个端口是USB001或USB002之类的。 经观察&#xff0c;这些USB00*端口并不是打印机驱动所…

Seata 序列化问题

异常&#xff1a; com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Type id handling not implemented for type java.lang.Object (by serializer of type com.fasterxml.jackson.databind.ser.impl.UnsupportedTypeSerializer) (through reference chain: i…

新建项目EasyUiAutotest,安装Appium-Python-Client

一、前置说明 Appium-Python-Client 是 Appium 的 Python 客户端库&#xff0c;它提供了一系列的类和方法&#xff0c;用于与 Appium 服务器进行通信&#xff0c;并执行各种移动应用测试操作&#xff0c;包括启动应用、模拟用户输入、点击等操作。 二、操作步骤 1. 启动Pych…
最新文章