簡體   English   中英

django模型的遠程訪問

[英]Remote access of django models

我有一個django 1.5項目,在apache服務器上運行的mysql上使用django模型。

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)

我的問題是,如果沒有本地數據庫,遠程應用程序將無法反序列化。

不要以為您需要通過http傳輸模型。 只需要連接到服務器數據庫。 在遠程應用程序設置中,選擇數據庫引擎(在您的情況下為mysql),名稱。 指定適當的用戶和密碼。 並輸入有效的主機和代理(如果需要)。 您的數據庫服務器正在運行的一台

至於用戶。 在服務器上創建一個對數據庫具有只讀權限的mysql用戶。

這將使您能夠對服務器和遠程應用程序使用相同的數據庫。

最后,我通過在客戶端的ram上運行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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM