Python Web框架Pylons中使用MongoDB的例子
Pylons 经过漫长的开发,终于放出了 1.0 版本。对于正规的产品开发来说,1.0 版本的意义很大,这表明 Pylons 的 API 终于稳定下来了。
Pylons 虽是山寨 Rails 而生,但作为一个纯 Python 的 Web 框架,它有一个鲜明的特点:可定制性强。框架每一层都没重新发明轮子,而是尽量整合现有的 Python 库。在 MVC 的 Model 层,Pylons 默认支持 SQLAlchemy。现在 NoSQL 很火 MongoDB 很热。在 Pylons 中应用 MongoDB 也很简单。下面是一个简单的示例。
在 PROJECT/model/__init__.py 中定义 MongoDB 初始化函数和映射对象:
from ming import Session
from ming import schema
from ming.orm import MappedClass
from ming.orm import FieldProperty, ForeignIdProperty, RelationProperty
from ming.orm import ThreadLocalORMSession
session = None
def init_single_model(model_class):
model_class.__mongometa__.session = session
class Page(MappedClass):
class __mongometa__:
session = session
name = 'pages'
_id = FieldProperty(schema.ObjectId)
title = FieldProperty(str)
content = FieldProperty(str)
def init_model(engine):
global session
session = ThreadLocalORMSession(doc_session=Session(engine))
init_single_model(Page)
MappedClass.compile_all()
在 PROJECT/config/environment.py 中进行初始化:
from ..model import init_model
from ming.datastore import DataStore
def load_environment(global_conf, app_conf):
...
# Create the Mako TemplateLookup, with the default auto-escaping
config['pylons.app_globals'].mako_lookup = TemplateLookup(
directories=paths['templates'],
error_handler=handle_mako_error,
module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
input_encoding='utf-8', default_filters=['escape'],
imports=['from webhelpers.html import escape'])
# Setup the mongodb database engine
init_model(DataStore(config['database.uri']))
# CONFIGURATION OPTIONS HERE (note: all config options will override
# any Pylons config options)
return config
最后在 development.ini 中加入 MongoDB 的配置项:
[app:main]
database.uri = mongodb://localhost:27017/test
如果需要在程序安装时初始化一些数据, 可以在 PROJECT/websetup.py 中加入
"""Setup the wukong application"""
import logging
import pylons.test
from .config.environment import load_environment
from . import model
log = logging.getLogger(__name__)
def setup_app(command, conf, vars):
"""Place any commands to setup wukong here"""
# Don't reload the app if it was loaded under the testing environment
if not pylons.test.pylonsapp:
load_environment(conf.global_conf, conf.local_conf)
log.info("Adding demo data.")
page = model.Page(title='demo', content='This is for demo.')
model.session.flush()
log.info("Successfully set up.")
这里使用了 Ming 库来连接 MongoDB 并做简单的 ORM。Ming 库是对 PyMongo 的 ORM 包装库。它是 SourceForge 用 TurboGears 和 MongoDB 对网站进行重构的副产物。使用起来有点象 SQLAlchemy ORM 。在上面的示例中,也可以把 Ming 替换成 MongoKit 或其它 MongoDB 的 ORM 库,甚至直接用 PyMongo 也无不可。
有种感觉,MongoDB 会火。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











When developing an e-commerce website, I encountered a difficult problem: how to provide users with personalized product recommendations. Initially, I tried some simple recommendation algorithms, but the results were not ideal, and user satisfaction was also affected. In order to improve the accuracy and efficiency of the recommendation system, I decided to adopt a more professional solution. Finally, I installed andres-montanez/recommendations-bundle through Composer, which not only solved my problem, but also greatly improved the performance of the recommendation system. You can learn composer through the following address:

This article introduces how to configure MongoDB on Debian system to achieve automatic expansion. The main steps include setting up the MongoDB replica set and disk space monitoring. 1. MongoDB installation First, make sure that MongoDB is installed on the Debian system. Install using the following command: sudoaptupdatesudoaptinstall-ymongodb-org 2. Configuring MongoDB replica set MongoDB replica set ensures high availability and data redundancy, which is the basis for achieving automatic capacity expansion. Start MongoDB service: sudosystemctlstartmongodsudosys

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

Detailed explanation of MongoDB efficient backup strategy under CentOS system This article will introduce in detail the various strategies for implementing MongoDB backup on CentOS system to ensure data security and business continuity. We will cover manual backups, timed backups, automated script backups, and backup methods in Docker container environments, and provide best practices for backup file management. Manual backup: Use the mongodump command to perform manual full backup, for example: mongodump-hlocalhost:27017-u username-p password-d database name-o/backup directory This command will export the data and metadata of the specified database to the specified backup directory.

GitLab Database Deployment Guide on CentOS System Selecting the right database is a key step in successfully deploying GitLab. GitLab is compatible with a variety of databases, including MySQL, PostgreSQL, and MongoDB. This article will explain in detail how to select and configure these databases. Database selection recommendation MySQL: a widely used relational database management system (RDBMS), with stable performance and suitable for most GitLab deployment scenarios. PostgreSQL: Powerful open source RDBMS, supports complex queries and advanced features, suitable for handling large data sets. MongoDB: Popular NoSQL database, good at handling sea

Encrypting MongoDB database on a Debian system requires following the following steps: Step 1: Install MongoDB First, make sure your Debian system has MongoDB installed. If not, please refer to the official MongoDB document for installation: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-debian/Step 2: Generate the encryption key file Create a file containing the encryption key and set the correct permissions: ddif=/dev/urandomof=/etc/mongodb-keyfilebs=512

To set up a MongoDB user, follow these steps: 1. Connect to the server and create an administrator user. 2. Create a database to grant users access. 3. Use the createUser command to create a user and specify their role and database access rights. 4. Use the getUsers command to check the created user. 5. Optionally set other permissions or grant users permissions to a specific collection.

The main tools for connecting to MongoDB are: 1. MongoDB Shell, suitable for quickly viewing data and performing simple operations; 2. Programming language drivers (such as PyMongo, MongoDB Java Driver, MongoDB Node.js Driver), suitable for application development, but you need to master the usage methods; 3. GUI tools (such as Robo 3T, Compass) provide a graphical interface for beginners and quick data viewing. When selecting tools, you need to consider application scenarios and technology stacks, and pay attention to connection string configuration, permission management and performance optimization, such as using connection pools and indexes.
