[python]pyramid 学习4 (views)

Defining a View Callable as a Function

from pyramid.response import Response

def hello_world(request):
return Response('Hello world!')

 

Defining a View Callable as a Class

from pyramid.response import Response

class MyView(object):
def __init__(self, request):
self.request = request

def __call__(self):
return Response('hello')

 

HTTP异常 (pyramid.httpexceptions)

抛出401的第一种方法 

from pyramid.httpexceptions import HTTPUnauthorized

def aview(request):
raise HTTPUnauthorized()

抛出401的第二种方法

from pyramid.httpexceptions import exception_response

def aview(request):
raise exception_response(401)

 

403
pyramid.httpexceptions.HTTPForbidden.

404
pyramid.httpexceptions.HTTPNotFound

 

自定义异常

复制代码
class ValidationFailure(Exception):
def __init__(self, msg):
self.msg = msg

from pyramid.view import view_config
from helloworld.exceptions import ValidationFailure

@view_config(context=ValidationFailure)
def failed_validation(exc, request):
response = Response('Failed validation: %s' % exc.msg)
response.status_int = 500
return response
复制代码

 

header重定向

from pyramid.httpexceptions import HTTPFound

def myview(request):
return HTTPFound(location='http://example.com')

 

获取POST数据

复制代码
def myview(request):
firstname = request.params['firstname']
lastname = request.params['lastname']

def myview(request):
# the .decode('utf-8') will break below if there are any high-order
# characters in the firstname or lastname
firstname = request.params['firstname'].decode('utf-8')
lastname = request.params['lastname'].decode('utf-8')
复制代码

 

复习一下 route中获取数据(GET)

request.matchdict['xxxx']

 

posted on   bluefrog  阅读(2331)  评论(0编辑  收藏  举报

编辑推荐:
· 智能桌面机器人:用.NET IoT库控制舵机并多方法播放表情
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
阅读排行:
· 手把手教你在本地部署DeepSeek R1,搭建web-ui ,建议收藏!
· 新年开篇:在本地部署DeepSeek大模型实现联网增强的AI应用
· Janus Pro:DeepSeek 开源革新,多模态 AI 的未来
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(三):用.NET IoT库
· 【非技术】说说2024年我都干了些啥
< 2011年10月 >
25 26 27 28 29 30 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示