- Python Pyramid 教程
- Python Pyramid - 首页
- Python Pyramid - 概述
- Pyramid - 环境设置
- Python Pyramid - Hello World
- Pyramid - 应用配置
- Python Pyramid - URL 路由
- Python Pyramid - 视图配置
- Python Pyramid - 路由前缀
- Python Pyramid - 模板
- Pyramid - HTML 表单模板
- Python Pyramid - 静态资源
- Python Pyramid - 请求对象
- Python Pyramid - 响应对象
- Python Pyramid - 会话
- Python Pyramid - 事件
- Python Pyramid - 消息闪现
- Pyramid - 使用 SQLAlchemy
- Python Pyramid - Cookiecutter
- Python Pyramid - 创建项目
- Python Pyramid - 项目结构
- Python Pyramid - 包结构
- 手动创建项目
- 命令行 Pyramid
- Python Pyramid - 测试
- Python Pyramid - 日志记录
- Python Pyramid - 安全性
- Python Pyramid - 部署
- Python Pyramid 有用资源
- Python Pyramid - 快速指南
- Python Pyramid - 有用资源
- Python Pyramid - 讨论
Python Pyramid - Hello World
示例
要检查 Pyramid 及其依赖项是否已正确安装,请输入以下代码并将其保存为 hello.py,使用任何支持 Python 的编辑器。
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
def hello_world(request):
return Response('Hello World!')
if __name__ == '__main__':
with Configurator() as config:
config.add_route('hello', '/')
config.add_view(hello_world, route_name='hello')
app = config.make_wsgi_app()
server = make_server('0.0.0.0', 6543, app)
server.serve_forever()
Configurator 对象用于定义 URL 路由并将视图函数绑定到它。从该配置对象获得的 WSGI 应用对象是 make_server() 函数的参数,以及 localhost 的 IP 地址和端口。当调用 serve_forever() 方法时,服务器对象进入监听循环。
从命令终端运行此程序,如下所示:
Python hello.py
输出
WSGI 服务器开始运行。打开浏览器并在地址栏中输入 http://loccalhost:6543/。当请求被接受时,hello_world() 视图函数将被执行。它返回 Hello world 消息。Hello world 消息将显示在浏览器窗口中。
如前所述,wsgiref 模块中 make_server() 函数创建的开发服务器不适合生产环境。相反,我们将使用 Waitress 服务器。根据以下代码修改 hello.py:
from pyramid.config import Configurator
from pyramid.response import Response
from waitress import serve
def hello_world(request):
return Response('Hello World!')
if __name__ == '__main__':
with Configurator() as config:
config.add_route('hello', '/')
config.add_view(hello_world, route_name='hello')
app = config.make_wsgi_app()
serve(app, host='0.0.0.0', port=6543)
所有其他功能都相同,除了我们使用 waitress 模块的 serve() 函数启动 WSGI 服务器。在运行程序后访问浏览器中的 '/' 路由,将像以前一样显示 Hello world 消息。
除了函数之外,可调用类也可以用作视图。可调用类是重写了 __call__() 方法的类。
from pyramid.response import Response
class MyView(object):
def __init__(self, request):
self.request = request
def __call__(self):
return Response('hello world')
广告