在django中读取本地文件 [英] Read a local file in django

查看:3156
本文介绍了在django中读取本地文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很坚持这个!
我正在编写一个从外部数据库读取数据的Django视图。为此,我正在使用标准的MySQLdb库。
现在,要加载数据,我必须做一个非常长而复杂的查询。我可以在我的视图中对该查询进行硬编码,并且工作正常。
但我认为这不实际;我希望将来能够更改查询,所以我尝试从文本文件中加载语句。
我的问题是,我不知道在哪里存储和如何打开该文件。无论我做什么,我得到一个没有这样的文件或目录的错误。甚至将它保存在与视图代码相同的目录中。



请注意,这不是上传的文件;它只是一个完成我的代码的外部文件。
任何想法?
提前感谢!

解决方案

将文件保存在django项目根目录中,并在settings.py文件中添加以下内容。

  PROJECT_ROOT = os.path.abspath(os.path.dirname(__ file__))

然后在视图中执行此操作。

  import os 
from django.conf.settings import PROJECT_ROOT

file_ = open(os.path.join(PROJECT_ROOT,'filename'))


I'm quite stuck on this one! I am writing a Django view that reads data from an external database. To do this, I am using the standard MySQLdb library. Now, to load the data, I must do a very long and complex query. I can hard code that query in my view and that works just fine. But I think that is not practical; I want to be able to change the query in the future, so I try to load the statement from a text file. My problem is that I don't know where to store and how to open that file. Wherever I do, I get a "No such file or directory" error. Even saving it in the same directory than the code of the view fails.

Note that this is not an uploaded file; it's just an external file that completes my code. Any ideas? Thanks in advance!

解决方案

Keep the file in django project root and add the following in the settings.py file.

PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))

Then in the view do this.

import os
from django.conf.settings import PROJECT_ROOT

file_ = open(os.path.join(PROJECT_ROOT, 'filename'))

这篇关于在django中读取本地文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆