0

I am working with flask and redis. I've decided to try the rom redis orm (http://pythonhosted.org/rom/) to manage some mildly complex data structures. I have a list of objects, lets say:

urls = ['www.google.com', 'www.example.com', 'www.python.org']

I also have the rom model:

class Stored_url(rom.Model):
    url = rom.String(required=True, unique=True, suffix=True)
    salt = rom.String()
    hash = rom.String()
    created_at = rom.Float(default=time.time)

What is the best way to cycle through my urls, turning each into a Stored_url object?

For example the first object would look like:

url = "google.com"
salt = ""
hash = ""
created_at = "the current time"

Edit: the example in the docs has:

user = User(email='[email protected]')
user.salt, user.hash = gen_hash(password)
user.save()

# session.commit() or session.flush() works too

1 Answer 1

1

You can do this using list comprehensions, something like:

objects = [Stored_url(url=u) for u in urls]

This will create a new list with one Stored_url object for each url in the original urls list.

To then save these objects, you need to loop through the object list and call save() on each of them:

for o in objects:
    o.save()
Sign up to request clarification or add additional context in comments.

5 Comments

Matt, thank you. One question in your approach: I will need to save each object (please see my edit above). Can this be incorporated into your method or do I need to iterate through the objects list and save each one?
Do you need to have access to the objects after you save them or can you discard them? If you need to have access you just need to loop over the objects list and save them, but if you can discard the created objects you can just change that comprehension to [Stored_url(url=u).save() for u in urls]
I need to save them, for later use.
Then the best way to go about it is to use the method in the original post and then afterwards, loop through the objects list and call save on each object. I'll edit my post
Ok, that helps. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.