如何使Django识别另一个目录中的JSON文件

问题描述 投票:0回答:1

我正在使用JSON文件存储一些凭据。我有一个具有打开该JSON文件并使用凭据使用Tweepy调用Twitter API的功能的文件。文件结构如下所示:

[search]/
├── [tweepi_api]/
│   ├── __init__.py
│   ├── get_tweets.py
│   ├── credentials.json
└── views.py

init。py看起来像:

from .get_tweets import ApiAuth

Views.py看起来像:

from django.shortcuts import render
import json
from .tweepy_api import ApiAuth 

# Create your views here.
def search_bar(request):
    tweetObj = ApiAuth('IBM')
    tweet_text = tweetObj.get_tweets()

    return render(request, 'tweets.html', {'public_tweets': tweet_text})

问题是我收到此错误:

Exception Value: [Errno 2] No such file or directory: 'credentials.json'

我不确定如何以其他方式将此文件包含在我的项目中。希望这足以回答我的问题。如果需要,我可以共享更多代码,但是当我将凭据上传到Github并将其作为json文件保存在我的计算机上时,我的目标并没有使凭据可见。

提前谢谢您

python django tweepy
1个回答
0
投票

您能否显示您的ApiAuth代码?

我认为,tweetObj = ApiAuth('IBM')发生了错误在此代码中,我们应该了解如何导入凭据。

仅供参考,要导入json文件,您可以按如下方式使用'with statement`。


In [8]: with open("credentials.json", "r") as credentials_json:
   ...:     credentials = json.loads(credentials_json.read())
   ...:     for key, value in credentials.items():
   ...:         print(key, value)
   ...:

id example_id
password example_password

© www.soinside.com 2019 - 2024. All rights reserved.