Ask coding questions

← Back to all posts
Help with Repl Database
h
MathBoy1 (0)

I've been using repl database with a recent project of mine (in Python Flask), how would I go about editing the contents of a database item?

For example, I wanted to do db[user][1] = myVar, however, this doesnt really seem to edit the user's database contents...

Would there be any way I could go about doing this without using shell, since most of the stuff is running automated on flask?

Answered by ruiwenge2 (1208) [earned 5 cycles]
View Answer
Comments
hotnewtop
MathBoy1 (0)

No, i mean, the user already exists with their db like this ["password", "xp"], and i want to change the xp from the already existing user @ruiwenge2

ruiwenge2 (1208)

@MathBoy1 then do this:

from replit import db
info = db[“USER”]
xp = info[1]
# change the value of xp
xp += 1
info = [“password”, xp]
db[“USER”] = info
MathBoy1 (0)

@ruiwenge2 Is do a package in replit, or is it a typo for db?

ruiwenge2 (1208)

@MathBoy1 oh sorry… it was the iPad autocorrecting lol

MathBoy1 (0)

@ruiwenge2 I'm getting an error called undefined name replit...

ruiwenge2 (1208)

@MathBoy1 right, I changed the code, change the replit to db. sorry about that

OldWizard209 (1638)

Replit's database is key-value storage.

So for that reason, if you need to set the key of user, to a value, you can pass in a dictionary, a list, or any other datatype as a value.

You want to do db[user][1] = myVar, this is like saying, get the value of the key with name of user, but then you are accessing the first index of it. That will not work, because the value is the one that contains a list, dict, etc., not the key. Thus what you have to do is this:

from replit import db # Import the DataBase.

db[user] = [name, age, username, email] # Set a key of "user" to a list for example, that contains the user's stats.

# This creates the db object in the background like:
db = {
       "user": [name, age, username, email]
}
# Get users' stats:
name = db[user][0]# This accesses the value of key-name "user", and returns the 0th index of the list associated to the value.
ruiwenge2 (1208)

like this:

from replit import db
user = “USERNAME”
myVar = “SOMETHING”
db[user] = {}
db[user][1] = myVar