使用django从外部数据库将数据拉到模板

时间:2021-10-13 00:16:12

I'm going to attempting to build a web app where users can visit a url, login and view reports and other information. However the data for the reports are stored in an external database. It's a MySQL database which I'm going to have access to.

我将尝试构建一个web应用程序,用户可以访问url、登录和查看报告以及其他信息。但是,报表的数据存储在外部数据库中。这是一个MySQL数据库,我可以访问它。

I've done a little research on google and not have much luck finding any examples. I've done a little reading into connecting to multiple databases - https://docs.djangoproject.com/en/dev/topics/db/multi-db/ So it looks i can connect to the database ok.

我在谷歌做了一些研究,没有找到任何例子。我对连接多个数据库做了一些阅读——https://docs.djangoproject.com/en/dev/topics/db/multidb/,这样看起来我可以连接到数据库。

The next part is where I'm stuck. The data in the database is going to be updated all the time. I don't want to be able to edit the information neither do i want to be able to overwrite anything. I just want to be able to connect to the DB pull the information required and then view it through the template for user to be able to see. First of all because the data is being updated all the time, is this going to be a problem? (I hope not!)

下一部分是我被困住的地方。数据库中的数据将一直更新。我不想编辑信息,我也不想覆盖任何东西。我只是想能够连接到DB拉出所需的信息,然后通过模板查看,以便用户能够看到。首先,因为数据一直在更新,这会是一个问题吗?(我希望不是这样!)

Once I've connected to the database, what is the best to be able to pull out the data and then put it into a format that i can output to the template? Would i need to import the data in to models, then control with the view. Or would i need to convert the data with JSON or XML?

一旦我连接到数据库,什么是最好的,能够提取数据,然后将它放入一个我可以输出到模板的格式?是否需要将数据导入模型,然后使用视图进行控制。还是需要用JSON或XML转换数据?

I'm fairly new to python / django, so any help would be much appreciated. If you need anymore info please ask and thanks in advance. :)

我对python / django非常熟悉,所以任何帮助都非常感谢。如果您需要更多的信息,请提前询问和感谢。:)

3 个解决方案

#1


13  

No problem! I do this all the time.

没问题!我一直这么做。

As far as the "don't edit or update the data", just don't add anything to your app that would update the data. Salem's suggestion about using permissions on the MySQL side is a good idea as well.

至于“不要编辑或更新数据”,只是不要在你的应用中添加任何会更新数据的东西。Salem关于在MySQL端使用权限的建议也是一个好主意。

For retrieving the data, you have two options:

为了获取数据,您有两个选项:

1) You can create Django models that correspond to your tables in the MySQL database. You can do this manually, or you can use the "inspectdb" command with manage.py to give yourself a good starting point. Then do something like this:

1)可以创建与MySQL数据库中的表对应的Django模型。您可以手动执行此操作,或者使用“inspectdb”命令进行管理。给自己一个好的起点。然后做这样的事情:

def myview(request):
  rows = MyModel.objects.using('mysql').all()
  return render_to_response("mytemplate.html", {"rows" : rows })

2) You can manage the connections and queries manually within your app. This is perfectly valid within a view:

2)你可以在你的app中手动管理连接和查询,这在视图中是完全有效的:

def myview(request):
  conn = MySQLdb.connect("connection info here")
  try:
    cursor = conn.cursor()
    cursor.execute("select * from mytable")
    rows = cursor.fetchall()
  finally:
    conn.close()

  return render_to_response("mytemplate.html", {"rows" : rows})

finally -- Django is perfectly happy to use MySQL as a database. It might simplify things if your DBA will let Django create its tables right in the same database.

最后——Django非常乐意使用MySQL作为数据库。如果DBA允许Django在同一个数据库中创建表,那么它可能会简化一些事情。

#2


1  

There is going to be no problem if the data is being updated.

如果数据正在更新,就不会有问题。

Now for retrieving the data from database you first have to import the concerned model in your views

现在,要从数据库中检索数据,首先需要在视图中导入相关模型

from app_name.models import model_name
def view_report(request):
    r_name=request.POST.get('r_name','default_value')
    r=model_name.objects.get(report_name=r_name)
    return render_to_response('url',{'r':r})

In your template

在你的模板

{{r.report_desc}}

#3


1  

To make your access to the database "read only", I guess the best option is to create a limited used in the MySQL side with only SELECT:

为了使你对数据库的访问“只读”,我认为最好的选择是创建一个在MySQL端使用的有限的只读选项:

GRANT SELECT ON target_database.* TO your_user@'your_host' IDENTIFIED BY 'your_password';

This will make sure that in any case an update/alter will succeed.

这将确保在任何情况下更新/修改都会成功。

Usually you model your database tables as objects because this makes it easier to work with database records from Python and gives you some abstraction, but you can execute raw SQL queries if you feel this is the right thing to do.

通常,您将数据库表建模为对象,因为这样可以更容易地处理来自Python的数据库记录,并提供一些抽象,但是如果您认为这是正确的,您可以执行原始SQL查询。

Depending on how you want to present your data, you may need to convert it to something.

根据您希望如何显示数据,您可能需要将其转换为某些内容。

If your want to make your application more dynamic (for example, retrieving new data in 10 seconds intervals and presenting it to the user without refresh) you probably will need to convert it to some format more suitable to be used with AJAX, like JSON or XML (Django has some serialization tools ready to be used). If you just want a "static" application( ie: user clicks in a link/button and goes to a page where data is presented, and to be refreshed user has to refresh the page) you can use the objects as retrieved from the database in your view.

如果你想让你的应用程序更加动态的(例如,获取新的数据在10秒的间隔和呈现给用户没有刷新)你可能需要将它转换成一些格式更适合使用AJAX,像JSON或XML(Django一些序列化工具可以使用)。如果您只是想要一个“静态”应用程序(例如:用户单击一个链接/按钮,然后切换到显示数据的页面,并且刷新用户必须刷新页面),您可以在视图中使用从数据库检索到的对象。

#1


13  

No problem! I do this all the time.

没问题!我一直这么做。

As far as the "don't edit or update the data", just don't add anything to your app that would update the data. Salem's suggestion about using permissions on the MySQL side is a good idea as well.

至于“不要编辑或更新数据”,只是不要在你的应用中添加任何会更新数据的东西。Salem关于在MySQL端使用权限的建议也是一个好主意。

For retrieving the data, you have two options:

为了获取数据,您有两个选项:

1) You can create Django models that correspond to your tables in the MySQL database. You can do this manually, or you can use the "inspectdb" command with manage.py to give yourself a good starting point. Then do something like this:

1)可以创建与MySQL数据库中的表对应的Django模型。您可以手动执行此操作,或者使用“inspectdb”命令进行管理。给自己一个好的起点。然后做这样的事情:

def myview(request):
  rows = MyModel.objects.using('mysql').all()
  return render_to_response("mytemplate.html", {"rows" : rows })

2) You can manage the connections and queries manually within your app. This is perfectly valid within a view:

2)你可以在你的app中手动管理连接和查询,这在视图中是完全有效的:

def myview(request):
  conn = MySQLdb.connect("connection info here")
  try:
    cursor = conn.cursor()
    cursor.execute("select * from mytable")
    rows = cursor.fetchall()
  finally:
    conn.close()

  return render_to_response("mytemplate.html", {"rows" : rows})

finally -- Django is perfectly happy to use MySQL as a database. It might simplify things if your DBA will let Django create its tables right in the same database.

最后——Django非常乐意使用MySQL作为数据库。如果DBA允许Django在同一个数据库中创建表,那么它可能会简化一些事情。

#2


1  

There is going to be no problem if the data is being updated.

如果数据正在更新,就不会有问题。

Now for retrieving the data from database you first have to import the concerned model in your views

现在,要从数据库中检索数据,首先需要在视图中导入相关模型

from app_name.models import model_name
def view_report(request):
    r_name=request.POST.get('r_name','default_value')
    r=model_name.objects.get(report_name=r_name)
    return render_to_response('url',{'r':r})

In your template

在你的模板

{{r.report_desc}}

#3


1  

To make your access to the database "read only", I guess the best option is to create a limited used in the MySQL side with only SELECT:

为了使你对数据库的访问“只读”,我认为最好的选择是创建一个在MySQL端使用的有限的只读选项:

GRANT SELECT ON target_database.* TO your_user@'your_host' IDENTIFIED BY 'your_password';

This will make sure that in any case an update/alter will succeed.

这将确保在任何情况下更新/修改都会成功。

Usually you model your database tables as objects because this makes it easier to work with database records from Python and gives you some abstraction, but you can execute raw SQL queries if you feel this is the right thing to do.

通常,您将数据库表建模为对象,因为这样可以更容易地处理来自Python的数据库记录,并提供一些抽象,但是如果您认为这是正确的,您可以执行原始SQL查询。

Depending on how you want to present your data, you may need to convert it to something.

根据您希望如何显示数据,您可能需要将其转换为某些内容。

If your want to make your application more dynamic (for example, retrieving new data in 10 seconds intervals and presenting it to the user without refresh) you probably will need to convert it to some format more suitable to be used with AJAX, like JSON or XML (Django has some serialization tools ready to be used). If you just want a "static" application( ie: user clicks in a link/button and goes to a page where data is presented, and to be refreshed user has to refresh the page) you can use the objects as retrieved from the database in your view.

如果你想让你的应用程序更加动态的(例如,获取新的数据在10秒的间隔和呈现给用户没有刷新)你可能需要将它转换成一些格式更适合使用AJAX,像JSON或XML(Django一些序列化工具可以使用)。如果您只是想要一个“静态”应用程序(例如:用户单击一个链接/按钮,然后切换到显示数据的页面,并且刷新用户必须刷新页面),您可以在视图中使用从数据库检索到的对象。