python - 使用 Pyramid 在 View 和应用程序之间共享对象

标签 python pyramid deform colander

我正在尝试使用 Pyramid 为数据分析管道创建网络界面。我正在使用变形和漏勺来制作表格。我一直在改编这个例子:

http://pyramid-tutorials.readthedocs.org/en/latest/humans/security/step02/

大部分工作在提交表单时完成,但有几个通用步骤只需要运行一次。我可以在服务器启动时将一些东西加载到内存中,以便可以从 View 中访问它们吗?

最佳答案

您可以在应用程序的主文件(或其他地方)中定义一些模块级变量,然后根据您的要求导入它们来使用它们。

我使用这种方法从环境变量中为 SQLAlchemy 创建数据库连接字符串等设置。

默认情况下,一个模块在 Python 中只会被解析一次,因此您的模块级代码只会运行一次。

更新1

假设 Pyramid 项目的目录结构如下所示:

.
├── __init__.py
├── models
│   ├── __init__.py
│   ├── meta
│   │   ├── base.py
│   │   ├── __init__.py
│   │   ├── orm.py
│   │   ├── schema.py
│   │   ├── types.py
│   ├── users.py
├── security.py
├── settings
│   ├── database.py
│   ├── email.py
│   ├── __init__.py
│   ├── redis.py
│   ├── security.py
├── static
│   ├── css
│   │   └── main.css
│   └── js
│       ├── app.js
│       ├── app-services.js
│       ├── controllers
│       │   └── excel_preview.js
├── templates
│   ├── auth
│   │   └── login.html
│   ├── base.html
│   ├── home.html
├── views
│   ├── auth.py
│   ├── home.py
│   ├── __init__.py

假设我们在 settings/redis.py 中有以下代码:

import os
import redis


def get_redis_client():
    # Read settings from environment variables
    redis_db_name = os.environ.get('REDIS_NAME')
    redis_host = os.environ.get('REDIS_HOST')
    redis_port = os.environ['REDIS_PORT']

    # create a redis connection
    redis_client = redis.StrictRedis(
        host=redis_host,
        port=redis_port,
        db=redis_db_name,
    )

    # return newly created redis connection
    return redis_client


redis_client = get_redis_client()

SOME_SETTING_STORED_IN_REDIS = redis_client.get('some_setting_stored_in_redis')

您可以从任何地方使用这个 SOME_SETTING_STORED_IN_REDIS 变量。如果您的应用名称是 example_app,那么在 example_app/views/home.py 中,您可以像这样使用它:

from pyramid.view import view_config

from example_app.settings.redis import SOME_SETTING_STORED_IN_REDIS


def includeme(config):
    config.add_route('home', '/')


@view_config(
    route_name='home',
    renderer='home.html',
    permission='authenticated'
)
def home_view(request):

    return {
        "some_setting": SOME_SETTING_STORED_IN_REDIS,
    }

我认为您正试图实现类似的目标。

关于python - 使用 Pyramid 在 View 和应用程序之间共享对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30746123/

相关文章:

python - 属性(property)没有按预期工作

python - Pyramid :ACL 中的 ACE 顺序

python - Pyramid - 动态分配模板以查看

python - 存储上传的图像?

python - 在 Deform/Colander HTML 选择字段中处理多对多关系

Python MySQL 连接器 fetchone 不返回 dict

python - eclipse-python IDE if else 匹配行/指示器

python - 有没有一种方法可以将数据从表单映射到插入数据库而无需显式定义每个变量?

python - 在Python中的pandas数据框中使用lambda函数使用多种文本格式?

forms - 哪一种是表单验证的正确方法? Colander 的模式验证还是 Deform 的表单验证?