-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimporta_db.py
More file actions
40 lines (32 loc) · 1.12 KB
/
importa_db.py
File metadata and controls
40 lines (32 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import os
import urllib.request
import json
from pymongo import MongoClient
# url
db = "https://raw.githubusercontent.com/adrianosferreira/afrodite.json/master/afrodite.json"
# Nome do arquivo de backup
name_file = "afrodite.json"
# Diretório do projeto
project_dir = os.path.dirname(os.path.abspath(__file__))
backup_dir = os.path.join(project_dir, "database")
# Se nao existir, cria
if not os.path.exists(backup_dir):
os.makedirs(backup_dir)
# Baixando arquivo json
urllib.request.urlretrieve(db, os.path.join(backup_dir, name_file))
# Endereco e porta padrao do mongodb
client = MongoClient('localhost', 27017)
db = client['afrodite']
collection = db['receitas']
# Abre o arquivo JSON e insere os documentos na collection
with open(os.path.join(backup_dir, name_file), 'r', encoding='utf-8') as f:
data = json.load(f)
# Remover o campo '_id' para gerar um novo
for document in data:
if '_id' in document:
del document['_id']
print("Importando...")
# Inserir na collection
collection.insert_many(data)
print("Importação Concluìda")
client.close()