zoukankan      html  css  js  c++  java
  • [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']

     

  • 相关阅读:
    使用 Docker 安装 Jenkins 的最佳方式
    使用 Docker 在 Linux 上托管 ASP.NET Core 应用程序
    分布式缓存 Redis 集群搭建
    [译]RabbitMQ教程C#版
    如何解决 React 官方脚手架不支持 Less 的问题
    [译]RabbitMQ教程C#版
    [译]RabbitMQ教程C#版
    快速签发 Let's Encrypt 证书指南
    [译]RabbitMQ教程C#版
    [译]RabbitMQ教程C#版
  • 原文地址:https://www.cnblogs.com/bluefrog/p/2219739.html
Copyright © 2011-2022 走看看