我刚刚开始学习Django / Python。我创建了一个名为reddit_project的项目,其中包含一个名为scraper的应用程序。我试图使用我的models.py中的模型链接,以便我可以根据我在web_crawler.py中搜索的JSON创建记录。但是,当我尝试在终端中运行web_crawler.py时,Django一直告诉我模块刮刀不存在。如何正确导入Link类,以便可以在web_crawler.py中使用?
刮刀/ models.py:
from django.db import models
# Create your models here.
class Link(models.Model):
title = models.CharField(max_length=50)
author = models.CharField(max_length=50)
url = models.CharField(max_length=200)
subreddit = models.CharField(max_length=200)
upvotes = models.IntegerField()
downvotes = models.IntegerField()
posted_date = models.DateTimeField()
web_crawler.py
import requests
from bs4 import BeautifulSoup
from scraper.models import Link
website_url = 'http://reddit.com/.json'
response = requests.get(website_url)
reddit_json = response.json()
print(reddit_json)
树:
.
|______init__.py
|______pycache__
| |______init__.cpython-34.pyc
| |____admin.cpython-34.pyc
| |____models.cpython-34.pyc
|____admin.py
|____models.py
|____models.pyc
|____tests.py
|____views.py
|____web_crawler.py
答案 0 :(得分:1)
您应该使用Django shell在Django项目中运行脚本。您可以输入以下命令启动shell:
python manage.py shell
当您在项目根目录中时,在OS命令提示符处。您可以导入web_crawler.py,因为您没有main方法:
>>> from scraper import web_crawler.py
话虽这么说,运行应该访问Django环境的脚本的更好方法是将其写为管理命令。这样,您可以使用
运行它python manage.py <mycommand>
有关详细信息,请参阅https://docs.djangoproject.com/en/1.7/howto/custom-management-commands/。