-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.py
47 lines (36 loc) · 1.4 KB
/
database.py
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
41
42
43
44
45
46
47
from model import User
from pymongo import MongoClient
from dotenv import load_dotenv
import os
load_dotenv()
CONNECTION_STRING = os.getenv("DB")
def get_database():
# Provide the mongodb atlas url to connect python to mongodb using pymongo
# CONNECTION_STRING = "mongodb+srv://andresdgarcia96:[email protected]/test"
# Create a connection using MongoClient. You can import MongoClient or use pymongo.MongoClient
client = MongoClient(CONNECTION_STRING)
# Create the database for our example (we will use the same database throughout the tutorial
return client['MusicApp']
# This is added so that many files can reuse the function get_database()
# Get the database
database = get_database()
collection = database['track']
async def fetch_user(user):
document = collection.find_one({"user":user})
return document
async def fetch_all_users():
users = []
cursor = collection.find({})
for document in cursor:
users.append(User(**document))
return users
async def create_user(document):
collection.insert_one(document)
return document
async def update_user(document):
collection.update_one({"user":document["user"]},{"$set":{
"period": document["period"],
"length": document["length"],
"infolist": document["infolist"]}})
document = collection.find_one({"user":document["user"]})
return document