.. _aiohttp-web:
.. highlight:: python
High-level HTTP Server
======================
.. module:: aiohttp.web
.. versionadded:: 0.10
Run a simple web server
-----------------------
For implementing a web server, first create a :ref:`request
handler<aiohttp-web-handler>`.
Handler is a :ref:`coroutine<coroutine>` or a regular function that
accepts only *request* parameter of type :class:`Request`
and returns :class:`Response` instance::
import asyncio
from aiohttp import web
@asyncio.coroutine
def hello(request):
return web.Response(request, b"Hello, world")
Next, you have to create a :class:`Application` instance and register
:ref:`handler<aiohttp-web-handler>` in the application's router pointing *HTTP
method*, *path* and *handler*::
app = web.Application()
app.router.add_route('GET', '/', hello)
After that, create a server and run the *asyncio loop* as usual::
loop = asyncio.get_event_loop()
f = loop.create_server(app.make_handler, '0.0.0.0', 8080)
srv = loop.run_until_complete(f)
print('serving on', srv.sockets[0].getsockname())
try:
loop.run_forever()
except KeyboardInterrupt:
pass
That's it.
.. _aiohttp-web-handler:
Handler
-------
Handler is an any *callable* that accepts a single :class:`Request`
argument and returns a :class:`StreamResponse` derived
(e.g. :class:`Response`) instance.
Handler **can** be a :ref:`coroutine<coroutine>`, :mod:`aiohttp.web` will
**unyield** returned result by applying ``yield from`` to the handler.
Handlers are connected to the :class:`Application` via routes::
handler = Handler()
app.router.add_route('GET', '/', handler)
.. _aiohttp-web-variable-handler:
You can also use *variable routes*. If route contains string like
``'/a/{name}/c'`` that means the route matches to the path like
``'/a/b/c'`` or ``'/a/1/c'``.
Parsed *path part* will be available in the *request handler* as
``request.match_info['name']``::
@asyncio.coroutine
def variable_handler(request):
return web.Response(
request,
"Hello, {}".format(request.match_info['name']).encode('utf8'))
app.router.add_route('GET', '/{name}', variable_handler)
Handlers can be first-class functions, e.g.::
@asyncio.coroutine
def hello(request):
return web.Response(request, b"Hello, world")
app.router.add_route('GET', '/', hello)
Sometimes you would like to group logically coupled handlers into a
python class.
:mod:`aiohttp.web` doesn't dictate any implementation details,
so application developer can use classes if he wants::
class Handler:
def __init__(self):
pass
def handle_intro(self, request):
return web.Response(request, b"Hello, world")
@asyncio.coroutine
def handle_greeting(self, request):
name = request.match_info.get('name')
txt = "Hello, {}".format(name)
return web.Response(request, txt.encode('utf-8')
handler = Handler()
app.router.add_route('GET', '/intro', handler.handle_intro)
app.router.add_route('GET', '/greet/{name}', handler.handle_greeting)
.. _aiohttp-web-file-upload:
File Uploads
------------
There are two steps necessary for handling file uploads. The first is
to make sure that you have a form that has been setup correctly to accept
files. This means adding enctype attribute to your form element with
the value of *multipart/form-data*. A very simple example would be a
form that accepts a mp3 file. Notice, we have set up the form as
previously explained and also added the *input* element of the *file*
type::
<form action="/store_mp3" method="post" accept-charset="utf-8"
enctype="multipart/form-data">
<label for="mp3">Mp3</label>
<input id="mp3" name="mp3" type="file" value="" />
<input type="submit" value="submit" />
</form>
The second step is handling the file upload in your :ref:`request
handler<aiohttp-web-handler>` (here assumed to answer on
*/store_mp3*). The uploaded file is added to the request object as
a :class:`FileField` object accessible through the :meth:`Request.POST`
coroutine. The two properties we are interested in are *file* and
*filename* and we will use those to read a file's name and a content::
import os
import uuid
from aiohttp.web import Response
def store_mp3_view(request):
data = yield from request.POST()
# ``filename`` contains the name of the file in string format.
filename = data['mp3'].filename
# ``input_file`` contains the actual file data which needs to be
# stored somewhere.
input_file = data['mp3'].file
content = input_file.read()
return Response(request, content,
headers=MultiDict([('CONTENT-DISPOSITION', input-file)])
.. _aiohttp-web-request:
Request
-------
The Request object contains all the information about an incoming HTTP request.
Every :ref:`handler<aiohttp-web-handler>` accepts a request instance as the
first positional parameter.
.. note::
You should never create the :class:`Request` instance manually --
:mod:`aiohttp.web` does it for you.
.. class:: Request
.. attribute:: method
*HTTP method*, Read-only property.
The value is upper-cased :class:`str` like ``"GET"``,
``"POST"``, ``"PUT"`` etc.
.. attribute:: version
*HTTP version* of request, Read-only property.
Returns :class:`aiohttp.protocol.HttpVersion` instance.
.. attribute:: host
*HOST* header of request, Read-only property.
Returns :class:`str` or ``None`` if HTTP request has no *HOST* header.
.. attribute:: path_qs
The URL including PATH_INFO and the query string. e.g, ``/app/blog?id=10``
Read-only :class:`str` property.
.. attribute:: path
The URL including *PATH INFO* without the host or scheme. e.g.,
``/app/blog``
Read-only :class:`str` property.
.. attribute:: query_string
The query string in the URL, e.g., ``id=10``
Read-only :class:`str` property.
.. attribute:: GET
A multidict with all the variables in the query string.
Read-only :class:`~aiohttp.multidict.MultiDict` lazy property.
.. attribute:: headers
A case-insensitive multidict with all headers.
Read-only :class:`~aiohttp.multidict.CaseInsensitiveMultiDict`
lazy property.
.. attribute:: keep_alive
``True`` if keep-alive connection enabled by HTTP client and
protocol version supports it, otherwise ``False``.
Read-only :class:`bool` property.
.. attribute:: match_info
Read-only property with :class:`~aiohttp.abc.AbstractMatchInfo`
instance for result of route resolving.
.. note::
Exact type of property depends on used router. If
``app.router`` is :class:`UrlDispatcher` the property contains
:class:`UrlMappingMatchInfo` instance.
.. attribute:: app
An :class:`Application` instance used to call :ref:`request handler
<aiohttp-web-handler>`, Read-only property.
.. attribute:: transport
An :ref:`transport<asyncio-transport>` used to process request,
Read-only property.
The property can be used, for example, for getting IP address of
client's peer::
peername = request.transport.get_extra('peername')
if peername is not None:
host, port = peername
.. attribute:: cookies
A multidict of all request's cookies.
Read-only :class:`~aiohttp.multidict.MultiDict` lazy property.
.. attribute:: payload
A :class:`~aiohttp.streams.FlowControlStreamReader` instance,
input stream for reading request's *BODY*.
Read-only property.
.. attribute:: content_type
Read-only property with *content* part of *Content-Type* header.
Returns :class:`str` like ``'text/html'``
.. note::
Returns value is ``'application/octet-stream'`` if no
没有合适的资源?快使用搜索试试~ 我知道了~
aiohttp-0.11.0.tar.gz
0 下载量 124 浏览量
2024-06-20
23:51:58
上传
评论
收藏 795KB GZ 举报
温馨提示
Python库是一组预先编写的代码模块,旨在帮助开发者实现特定的编程任务,无需从零开始编写代码。这些库可以包括各种功能,如数学运算、文件操作、数据分析和网络编程等。Python社区提供了大量的第三方库,如NumPy、Pandas和Requests,极大地丰富了Python的应用领域,从数据科学到Web开发。Python库的丰富性是Python成为最受欢迎的编程语言之一的关键原因之一。这些库不仅为初学者提供了快速入门的途径,而且为经验丰富的开发者提供了强大的工具,以高效率、高质量地完成复杂任务。例如,Matplotlib和Seaborn库在数据可视化领域内非常受欢迎,它们提供了广泛的工具和技术,可以创建高度定制化的图表和图形,帮助数据科学家和分析师在数据探索和结果展示中更有效地传达信息。
资源推荐
资源详情
资源评论
收起资源包目录
aiohttp-0.11.0.tar.gz (129个子文件)
make.bat 7KB
.buildinfo 230B
setup.cfg 157B
sample.crt 822B
basic.css 8KB
default.css 4KB
pygments.css 4KB
api.doctree 381KB
web.doctree 270KB
client.doctree 56KB
server.doctree 15KB
index.doctree 5KB
ajax-loader.gif 673B
web.html 149KB
client.html 137KB
api.html 126KB
protocol.html 114KB
web.html 109KB
connector.html 66KB
parsers.html 60KB
streams.html 55KB
client.html 55KB
server.html 49KB
helpers.html 44KB
genindex.html 43KB
websocket.html 40KB
wsgi.html 34KB
server.html 18KB
errors.html 17KB
index.html 10KB
py-modindex.html 6KB
index.html 4KB
search.html 4KB
websocket.html 2KB
aiohttp-icon.ico 4KB
aiohttp-icon.ico 4KB
MANIFEST.in 174B
objects.inv 2KB
jquery.js 247KB
underscore.js 40KB
searchindex.js 26KB
websupport.js 25KB
searchtools.js 17KB
doctools.js 7KB
sidebar.js 5KB
sample.key 887B
Makefile 7KB
Makefile 927B
environment.pickle 1.42MB
PKG-INFO 11KB
PKG-INFO 11KB
aiohttp-icon.png 19KB
comment-close.png 3KB
comment-bright.png 3KB
comment.png 3KB
file.png 392B
up-pressed.png 372B
down-pressed.png 368B
down.png 363B
up.png 363B
plus.png 199B
minus.png 199B
test_client_functional.py 47KB
test_client.py 34KB
web.py 32KB
client.py 31KB
protocol.py 27KB
test_connector.py 24KB
test_streams.py 22KB
test_http_parser.py 19KB
test_http_server.py 18KB
test_parsers.py 17KB
test_websocket.py 17KB
test_http_protocol.py 16KB
connector.py 14KB
test_web_response.py 13KB
parsers.py 13KB
server.py 12KB
test_multidict.py 11KB
streams.py 11KB
test_wsgi.py 10KB
test_web_functional.py 10KB
test_urldispatch.py 10KB
wssrv.py 10KB
test_utils.py 9KB
conf.py 9KB
mpsrv.py 9KB
websocket.py 8KB
helpers.py 8KB
multidict.py 8KB
test_worker.py 7KB
wsgi.py 7KB
test_web_request.py 5KB
srv.py 5KB
tcp_protocol_parser.py 5KB
worker.py 4KB
test_web_exceptions.py 4KB
crawl.py 3KB
wsclient.py 3KB
errors.py 3KB
共 129 条
- 1
- 2
资源评论
程序员Chino的日记
- 粉丝: 3667
- 资源: 5万+
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- C语言-leetcode题解之83-remove-duplicates-from-sorted-list.c
- C语言-leetcode题解之79-word-search.c
- C语言-leetcode题解之78-subsets.c
- C语言-leetcode题解之75-sort-colors.c
- C语言-leetcode题解之74-search-a-2d-matrix.c
- C语言-leetcode题解之73-set-matrix-zeroes.c
- 树莓派物联网智能家居基础教程
- YOLOv5深度学习目标检测基础教程
- (源码)基于Arduino和Nextion的HMI人机界面系统.zip
- (源码)基于 JavaFX 和 MySQL 的影院管理系统.zip
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功