我在用于UX设计的金字塔教程中看到了它.我无法理解这个装饰者的全部内容.
我看到它的用法的示例代码.
def __init__(self, request):
self.request = request
renderer = get_renderer("templates/global_layout.pt")
self.global_template = renderer.implementation().macros['layout']
@reify
def company_name(self):
return COMPANY
@reify
def site_menu(self):
new_menu = SITE_MENU[:]
url = self.request.url
for menu in new_menu:
if menu['title'] == 'Home':
menu['current'] = url.endswith('/')
else:
menu['current'] = url.endswith(menu['href'])
return new_menu
@view_config(renderer="templates/index.pt")
def index_view(self):
return {"page_title": "Home"}
@view_config(renderer="templates/about.pt", name="about.html")
def about_view(self):
return {"page_title": "About"}
Run Code Online (Sandbox Code Playgroud) 我得到了这个奇怪的错误,我说的很奇怪,因为我改变了一个不相关的表.
我试图查询我的tDevice表,看起来像这样:
class TDevice(Base):
__tablename__ = 'tDevice'
ixDevice = Column(Integer, primary_key=True)
ixDeviceType = Column(Integer, ForeignKey('tDeviceType.ixDeviceType'), nullable=False)
ixSubStation = Column(Integer, ForeignKey('tSubStation.ixSubStation'), nullable=False)
ixModel = Column(Integer, ForeignKey('tModel.ixModel'), nullable=True)
ixParentDevice = Column(Integer, ForeignKey('tDevice.ixDevice'), nullable=True)
sDeviceName = Column(Unicode(255), nullable=False)#added
children = relationship('TDevice',
backref=backref('parent', remote_side=[ixDevice]))
device_type = relationship('TDeviceType',
backref=backref('devices'))
model = relationship('TModel',
backref=backref('devices'))
sub_station = relationship('TSubStation',
backref=backref('devices'))
Run Code Online (Sandbox Code Playgroud)
这就是我查询它的方式:
Device = DBSession.query(TDevice).filter(TDevice.ixDevice == device_id).one()
Run Code Online (Sandbox Code Playgroud)
一旦执行此行,我就会收到错误:
ArgumentError: relationship 'report_type' expects a class or a mapper argument (received: <class 'sqlalchemy.sql.schema.Table'>)
Run Code Online (Sandbox Code Playgroud)
我所做的唯一更改是在my中添加一个report_type关系tReportTable
,现在看起来像这样:
class TReport(Base):
__tablename__ …Run Code Online (Sandbox Code Playgroud) 我习惯在Django和gunicorn上开发Web应用程序.
对于Django,Django应用程序中的任何应用程序模块都可以通过django.conf.settings获取部署设置."settings.py"是用Python编写的,因此可以动态定义任意设置和预处理.
在gunicorn的情况下,它按优先顺序有三个配置位置,并且一个设置注册表类实例组合这些.(但通常这些设置仅用于gunicorn而不是应用程序.)
对于Pyramid,根据Pyramid文档,部署设置通常可以放入pyramid.registry.Registry().settings中.但它似乎仅在存在pyramid.router.Router()实例时才被访问.那就是pyramid.threadlocal.get_current_registry().settings在应用程序"main.py"的启动过程中返回None.
例如,我通常在SQLAlchemy模型模块中定义一些业务逻辑,这需要部署设置如下.
myapp/models.py
from sqlalchemy import Table, Column, Types
from sqlalchemy.orm import mapper
from pyramid.threadlocal import get_current_registry
from myapp.db import session, metadata
settings = get_current_registry().settings
mytable = Table('mytable', metadata,
Column('id', Types.INTEGER, primary_key=True,)
(other columns)...
)
class MyModel(object):
query = session.query_property()
external_api_endpoint = settings['external_api_uri']
timezone = settings['timezone']
def get_api_result(self):
(interact with external api ...)
mapper(MyModel, mytable)
Run Code Online (Sandbox Code Playgroud)
但是,"settings ['external_api_endpoint']"会引发TypeError异常,因为"settings"为None.
我想了两个解决方案.
定义一个callable,它接受"models.py"中的"config"参数,"main.py"使用Configurator()实例调用它.
myapp/models.py
from sqlalchemy import Table, …Run Code Online (Sandbox Code Playgroud)# /test{.format} no longer seems to work...
config.add_route('test', '/test.{ext}', view='ms.views.test')
Run Code Online (Sandbox Code Playgroud)
views.py:
from pyramid.response import Response
from pyramid.renderers import render
import json
def test(request):
extension = request.matchdict['ext']
variables = {'name' : 'blah', 'asd' : 'sdf'}
if extension == 'html':
output = render('mypackage:templates/blah.pt', variables, request=request)
if extension == 'json':
output = json.dumps(variables)
return Response(output)
Run Code Online (Sandbox Code Playgroud)
有更简单的方法吗?有了Pylons,它很简单:
def test(self, format='html'):
c.variables = {'a' : '1', 'b' : '2'}
if format == 'json':
return json.dumps(c.variables)
return render('/templates/blah.html')
Run Code Online (Sandbox Code Playgroud)
我怀疑我接近这个错误的方式......?
我正在尝试让我的表单提交到一条路线,该路线将验证数据然后重定向回原始路线.
例如:
金字塔给我带来了一些麻烦.
这是我瘦弱的views.py
def _get_link_form(post_data):
""" Returns the initialised form object """
return LinkForm(post_data)
def home_page(request):
form = _get_link_form(request.POST)
return {'form' : form}
def save_post(request):
""" form data is submitted here """"
form = _get_link_form(request.POST)
if not form.validate():
return home_page(request, form)
Run Code Online (Sandbox Code Playgroud)
这是我一直在玩的代码.它不仅不起作用,而且感觉很乱并且被黑了.肯定有一种更简单的方法可以在金字塔中"重定向POST后"?
我正在尝试创建一个将"项目"所有权考虑在内的授权策略.例如,一些用户X"拥有"项目A,B,C.这些是通过URL访问的/item/{item}/some_options.
如何获取有关{item}授权策略对象的信息(permit()调用)?将附加信息放入上下文中是一个好主意(我只做基于路由的路由).我该怎么办?
我无法弄清楚如何使用Jinja2修改包含模板中的块.这是我使用三个文件的示例.
base.html文件:
<html>{% include "content.html" %}</html>
Run Code Online (Sandbox Code Playgroud)
content.html:
<h1>{% block title %}Title{% endblock title%}</h1>
<div>{% block content_body %}Content Body{% endblock content_body%}</div>
Run Code Online (Sandbox Code Playgroud)
story.html
{% extends "base.html" %}
{% block title %}story.title{% endblock title %}
{% block content_body %}story.description{% endblock content_body %}
Run Code Online (Sandbox Code Playgroud)
渲染story.html时,我会得到:
<html>
<h1>Title</h1>
<div>Content Body</div>
</html>
Run Code Online (Sandbox Code Playgroud)
如何使用预期值进行渲染?
我在Pyramid应用程序中定义了自定义404视图:
@view_config(context=HTTPNotFound, renderer='404.pt')
def not_found(self, request):
return {}
Run Code Online (Sandbox Code Playgroud)
它工作正常,除了与内容一起发送的HTTP状态代码是200 OK,这无论如何都不行.403 Forbidden我遇到了同样的问题.如何让Pyramid发送正确的状态代码?
我是SQLAlchemy的新手,并且在没有访问原始作者的情况下继承了一些有点混乱的代码库.
代码是通过调用来编写的DBSession.flush(),似乎是作者想要确保数据被保存的任何时候.起初我只是遵循我在这段代码中看到的模式,但是当我正在阅读文档时,似乎这是不必要的 - 自动清理应该到位.另外,我遇到了一些AJAX调用的情况,这些调用会产生错误"InvalidRequestError:Session已经刷新".
在什么情况下,我合法地想要保持对flush()的调用?
这是一个Pyramid应用程序,SQLAlchemy正在设置:
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension(), expire_on_commit=False))
Base = declarative_base()
Run Code Online (Sandbox Code Playgroud) 我试图用金字塔设置uWSGI,但是在尝试时我收到了这个错误 uwsgi --ini-paste development.ini
Python version: 3.2.3
错误信息:
uwsgi socket 0 bound to UNIX address /tmp/uwsgi.sock fd 3
Python version: 3.2.3 (default, Oct 19 2012, 20:08:46) [GCC 4.6.3]
Set PythonHome to /root/path/to/virtualenv
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named encodings
Run Code Online (Sandbox Code Playgroud)
这是我在development.ini中的内容
[uwsgi]
socket = /tmp/uwsgi.sock
master = true
processes = 4
harakiri = 60
harakiri-verbose = true
limit-post = 65536
post-buffering = 8192
daemonize = ./uwsgi.log
pidfile = ./pid_5000.pid
listen = 256
max-requests …Run Code Online (Sandbox Code Playgroud)