脚本\loadDateData.py
import csv
import urllib.request
from database.models import locationData, dateData
def run():
target = locationData.objects.get (pk = 1)
url = target.resourceURL
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'} #from blog.csdn.net
req = urllib.request.Request(url = url, headers = headers) #from blog.csdn.net
response = urllib.request.urlopen(req) #from stackoverflow
lines = [l.decode('utf-8') for l in response.readlines()] #from stackoverflow
reader = csv.DictReader(response) #from stackoverflow
dateData.objects.all().delete()
for row in reader:
print (row)
temp = dateData()
temp.date = row ['As of date']
temp.confirmedCase = int (row ['Number of confirmed cases'])
temp.deathCase = int (row ['Number of death cases'])
temp.name = target.name
temp.save()
模型.py
from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator
#from django.contrib.postgres.fields import ArrayField
# Create your models here.
class locationData (models.Model):
locationID = models.AutoField (primary_key = True)
name = models.CharField (max_length = 64)
population = models.IntegerField (default = 0, validators = [MinValueValidator(0)])
apiEndpoint = models.URLField (max_length = 256)
resourceURL = models.URLField (max_length = 256)
class dateData (models.Model):
entryID = models.AutoField (primary_key = True)
name = models.CharField (max_length = 64)
date = models.DateField (auto_now = False, auto_now_add = False)
confirmedCase = models.IntegerField (default = 0, validators = [MinValueValidator(0)])
deathCase = models.IntegerField (default = 0, validators = [MinValueValidator(0)])
我是一名初学者,我正在开展一个关于基于 Web 的应用程序的项目,以显示特定位置的更新的 covid 案例数据。为此,我需要从公开发布的 CSV 文件中获取数据。所以我遵循了一个在线教程,到目前为止我已经做了什么。
- 在项目目录中创建了一个脚本目录
- 创建了一个 init 文件,该文件在该目录中为空
- 在 setting.py 中将 django_extensions 添加到已注册的应用程序中
- 并创建了上面显示的 loadDateData.py
现在,处理前面提到的错误。还有一个新问题是我运行服务器后数据库仍然是空的。由于没有弹出错误消息,而且我对 Django 不太熟悉。我不确定哪个部分出了问题。有什么我仍然想念的吗?