远程访问Django模型
我有一个使用 Django 1.5 的项目,这个项目通过 MySQL 数据库在 Apache 服务器上运行。
class Person(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
birthdate = models.DateField()
class Book(models.Model):
name = models.CharField(max_length=100)
author = models.ForeignKey(Person)
我还有一个 Python/Django 应用程序(使用 Django 自定义命令),它运行在一台远程计算机上,需要使用这些模型。
- 远程应用程序和服务器共享相同的模型定义
- 远程应用程序只需要对模型的只读访问权限
- 远程应用程序不能获取服务器数据库的完整备份,因为服务器必须根据用户权限返回查询集
- 远程应用程序只能通过 HTTP 连接到服务器
- 服务器可以通过 REST API(返回 JSON 格式)来暴露模型
有没有什么自动化的方法可以通过 HTTP 传输模型?我尝试使用 django.core.serializers,但遇到了以下问题:
- 我无法序列化查询集中相关的对象
- 远程应用程序没有本地数据库就无法工作
- 远程应用程序在反序列化后会在本地数据库中查找相关对象(但本地数据库并不存在)
编辑:
我成功地序列化了模型,像这样:
books = Book.objects.prefetch_related('author').all()
authors = [book.author for book in books]
data = authors + list(books.all())
serialized_data = django.core.serializers.serialize("json", data)
我遇到的问题是,远程应用程序没有本地数据库就无法进行反序列化。
2 个回答
0
最后我通过在客户端使用运行在内存中的sqlite解决了这个问题。
在settings.py文件中,我使用了这样的配置:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
}
}
代码大概是这样的:
from django.db import connections
from django.core.management.color import no_style
from django.core import serializers
from apps.my_models import Book, Person
connection = connections['default']
cursor = connection.cursor()
sql, references = connection.creation.sql_create_model(Book, no_style(), set())
cursor.execute(sql[0])
sql, references = connection.creation.sql_create_model(Person, no_style(), set())
cursor.execute(sql[0])
serialized_data = get_serialized_data()
for obj in serializers.deserialize("json", serialized_data):
obj.save()
books = Book.objects.prefetch_related('author').all()
0
别以为你需要通过http来传输模型。其实只需要连接到服务器的数据库就可以了。
在远程应用的设置里,选择数据库引擎(在你的情况下是mysql),然后给它起个名字。
接着,填写合适的用户名和密码。如果需要的话,还要输入一个有效的主机和代理,也就是你的数据库服务器所在的地址。
关于用户方面,在服务器上创建一个mysql用户,并给它只读的权限,这样它就只能查看数据库里的数据,而不能修改。
这样,你就可以在服务器和远程应用之间使用同一个数据库了。