Following http://mongoengine.org/docs/v0.4/guide/gridfs.html documentation about mongoengine FileField I did the following:
In my model
files = ListField(FileField())
In my test code
# Create an entry
photo = FileField()
f = open('/home/foo/marmot.jpg', 'r')
photo.put(f, content_type='image/jpeg')
entry.files = [photo,]
Trying to follow the doc, however i get an error:
Traceback (most recent call last):
File "/home/bar/tests.py", line 76, in test_MongoDGACLogook_creation
photo.put(f, content_type='image/jpeg')
AttributeError: 'FileField' object has no attribute 'put'
Am I missing something obvious ?
Thanks
This isn't obvious at all IMO, but if you look at the Mongoengine code you'll see that the put method is defined in the GridFSProxy class, which is accessed via a descriptor in FileField (the __get__ and __set__ methods).
Looking at the code and the examples in the docs, it appears the only way to access or use a FileField is through the descriptor....so, collection.file_field.
Given all this, I don't think it's possible to have a list of file fields using the Mongoengine API as it exists now.
f = mongoengine.fields.GridFSProxy()
to_read = open('/home/.../marmot.jpg', 'r')
f.put(to_read, filename=os.path.basename(to_read.name))
to_read.close()
If you are uploading multiples files and trying to save it a ListField(FileField())
<input type='file' name='myfiles' multiple="">
files = []
for f in request.FILES.getlist('myfiles'):
mf = mongoengine.fields.GridFSProxy()
mf.put(f, filename=f.name)
files.append(mf)
entry.files = files
entry.save()
I had exactly the same problem. As suggested by #KoppeKTop on GitHub in this post, I finally extended my model (Pet) using an EmbeddedDocument like this:
class OneImage(mongoengine.EmbeddedDocument):
element = ImageField()
class Pet(mongoengine.Document):
photos = EmbeddedDocumentListField(OneImage)
# ...more fields... #
I can then add a new image using
i = OneImage()
i.element.put(form.photo.data.stream)
entry.photos.append(i)
entry.save()
This may not always be the best option, but personally I prefer it because I can work with models as usual without having to work with proxies. And I can also save other photo metadata in the future, if I need to.
Related
I'm trying to setup stream-framework the one here not the newer getstream. I've setup the Redis server and the environment properly, the issue I'm facing is in creating the activities for a user.
I've been trying to create activities, following the documentation to add an activity but it gives me an error message as follows:
...
File "/Users/.../stream_framework/activity.py", line 110, in serialization_id
if self.object_id >= 10 ** 10 or self.verb.id >= 10 ** 3:
AttributeError: 'int' object has no attribute 'id'
Here is the code
from stream_framework.activity import Activity
from stream_framework.feeds.redis import RedisFeed
class PinFeed(RedisFeed):
key_format = 'feed:normal:%(user_id)s'
class UserPinFeed(PinFeed):
key_format = 'feed:user:%(user_id)s'
feed = UserPinFeed(13)
print(feed)
activity = Activity(
actor=13, # Thierry's user id
verb=1, # The id associated with the Pin verb
object=1, # The id of the newly created Pin object
)
feed.add(activity) # Error at this line
I think there is something missing in the documentation or maybe I'm doing something wrong. I'll be very grateful if anyone helps me get the stream framework working properly.
The documentation is inconsistent. The verb you pass to the activity should be (an instance of?*) a subclass of stream_framework.verbs.base.Verb. Check out this documentation page on custom verbs and the tests for this class.
The following should fix the error you posted:
from stream_framework.activity import Activity
from stream_framework.feeds.redis import RedisFeed
from stream_framework.verbs import register
from stream_framework.verbs.base import Verb
class PinFeed(RedisFeed):
key_format = 'feed:normal:%(user_id)s'
class UserPinFeed(PinFeed):
key_format = 'feed:user:%(user_id)s'
class Pin(Verb):
id = 5
infinitive = 'pin'
past_tense = 'pinned'
register(Pin)
feed = UserPinFeed(13)
activity = Activity(
actor=13,
verb=Pin,
object=1,
)
feed.add(activity)
I quickly looked over the code for Activity and it looks like passing ints for actor and object should work. However, it is possible that these parameters are also outdated in the documentation.
* The tests pass in classes as verb. However, the Verb base class has the methods serialize and __str__ that can only be meaningfully invoked if you have an object of this class. So I'm still unsure which is required here. It seems like in the current state, the framework never calls these methods, so classes still work, but I feel like the author originally intended to pass instances.
With the help of great answer by #He3lixxx, I was able to solve it partially. As the package is no more maintained, the package installs the latest Redis client for python which was creating too many issues so by installation redis-2.10.5 if using stream-framework-1.3.7, should fix the issue.
I would also like to add a complete guide to properly add activity to a user feed.
Key points:
If you are not using feed manager, then make sure to first insert the activity before you add it to the user with feed.insert_activity(activity) method.
In case of getting feeds with feed[:] throws an error something like below:
File "/Users/.../stream_framework/activity.py", line 44, in get_hydrated
activity = activities[int(self.serialization_id)]
KeyError: 16223026351730000000001005L
then you need to clear data for that user using the key format for it in my case the key is feed:user:13 for user 13, delete it with DEL feed:user:13, In case if that doesn't fix the issue then you can FLUSHALL which will delete everything from Redis.
Sample code:
from stream_framework.activity import Activity
from stream_framework.feeds.redis import RedisFeed
from stream_framework.verbs import register
from stream_framework.verbs.base import Verb
class PinFeed(RedisFeed):
key_format = 'feed:normal:%(user_id)s'
class UserPinFeed(PinFeed):
key_format = 'feed:user:%(user_id)s'
class Pin(Verb):
id = 5
infinitive = 'pin'
past_tense = 'pinned'
register(Pin)
feed = UserPinFeed(13)
print(feed[:])
activity = Activity(
actor=13,
verb=Pin,
object=1)
feed.insert_activity(activity)
activity_id = feed.add(activity)
print(activity_id)
print(feed[:])
I'm trying to update a user attribute in Active Directory using pyad. This is my code
from pyad import *
pyad.set_defaults(ldap_server="server.domain.local",
username="admin", password="password")
pyad.adobject.ADObject.update_attribute(self='testuser1', attribute='mail',
newvalue='my#email.com')
and this is the error i recieve.
Traceback (most recent call last):
File "c:\Users\Administrator\Desktop\scripts\AD-Edit-user.py", line 12, in
<module>
pyad.adobject.ADObject.update_attribute(self='testuser1', attribute='mail',
newvalue='my#email.com')
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-
32\lib\site-packages\pyad-0.5.20-py3.6.egg\pyad\adobject.py", line 318, in
update_attribute
elif pyadutils.generate_list(newvalue) != self.get_attribute(attribute):
AttributeError: 'str' object has no attribute 'get_attribute'
This makes me assume that I need to change the attribute type from str to something else. I have verified that mail is the correct attribute name.
I know ldap connection is working because i can create a user using a similar script.
Your problem is how you use pyad.
Specifically in this line:
pyad.adobject.ADObject.update_attribute(self='testuser1', attribute='mail',
newvalue='my#email.com')
if we look at the source of pyad.adobject.ADObject, we can see the following:
def update_attribute(self, attribute, newvalue, no_flush=False):
"""Updates any mutable LDAP attribute for the object. If you are adding or removing
values from a multi-valued attribute, see append_to_attribute and remove_from_attribute."""
if newvalue in ((),[],None,''):
return self.clear_attribute(attribute)
elif pyadutils.generate_list(newvalue) != self.get_attribute(attribute):
self._set_attribute(attribute, 2, pyadutils.generate_list(newvalue))
if not no_flush:
self._flush()
self here is not a parameter of the function, it is a reference to the class instance. Your call includes self='testuser1' which is str.
Please lookup the documentation on how to use this function / functionality / module, here. You will notice that there is no "self"... other than looking into the source code I am not sure how you got to the conclusion you needed self.
I have no way of testing the following, but this is roughly how it should work:
# first you create an instance of the object, based on
# the distinguished name of the user object which you
# want to change
my_ad_object = pyad.adobject.ADObject.from_dn('the_distinguished_name')
# then you call the update_attribute() method on the instance
my_ad_object.update_attribute(attribute='mail', newvalue='my#email.com')
I'm currently editing existing documents in my ravenDB instance.
The main issue i'm facing is that i get no errors but no changes are saved.
I'm using the following code :
#in init method
self.store = document_store.documentstore(url=self.dbURL, database=self.dbInUse)
self.store.initialize()
def someMethodToSaveData(self, id, newTextField="")
with self.store.open_session() as session:
doc = session.load(id)
doc.newTextField=newTextField
session.store(doc,id)
session.save_changes()
thanks
edit: added session.save_changes() in this code. testing, but i have that line in another project and I'm facing the same issue with it.
I think you will have to call the method session.save_changes() so that the the database transaction completes:
#in init method
self.store = document_store.documentstore(url=self.dbURL, database=self.dbInUse)
self.store.initialize()
def someMethodToSaveData(self, id, newTextField="")
with self.store.open_session() as session:
doc = session.load(id)
doc.newTextField=newTextField
session.store(doc,id)
session.save_changes() # this call is important
I found this information in the offical RavenDB documentation:
I have been using django imagekit without any problems in the templates but now I need to get the url in the view not the template, following this example in the imagekit docs:
source_file = open('/path/to/myimage.jpg')
image_generator = Thumbnail(source=source_file)
result = image_generator.generate()
So I did this:
course_img = open(settings.MEDIA_ROOT+str(course.image), 'rb+')
image_generator = myapp_images.Thumbnail100x100(source=course_img)
result = image_generator.generate()
And then, I try to get the url from the "result" variable, but I don't know how:
details_html += "<img class='img-rounded' src='"+ str(result) +"'/>
I have been trying with str(result), result.url, result.name, etc... with no luck, any idea how to get it?
Thx
I got the solution from the imagekit author in the google imagekit group:
In my case I wanted to interact with the Cache File, in order to do that we have to wrap my generator with an ImageCacheFile, like this:
from imagekit.cachefiles import ImageCacheFile
image_generator = myapp_images.Thumbnail00x100(source=course.image)
result = ImageCacheFile(image_generator)
so the result object it is what I was expecting, now I can read the url just using result.url.
Generator itself doesn't allow you to do that on the fly, it generates file-like object, which means it doesn't save the file on disk, which means no filename and so, no URL name..
Either you save the object and generate url manually or you can use ImageCacheFile like this:
from imagekit.cachefiles import ImageCacheFile
file = ImageCacheFile(image_generator, name='my_image.thumb.jpg')
file.generate()
print file.url
Code:
for k in dir(parse_rest.User):
print parse_rest.User[k]
Error:
Traceback (most recent call last):
File "/home/ntresch/Development/webapp/appcode.py", line 53, in <module>
for k in dir(parse_rest.User):
AttributeError: 'module' object has no attribute 'User'
The docs show the following:
#Users
#You can sign up, log in, modify or delete users as well, using the User object. You sign a user up as follows:
u = parse_rest.User.signup("dhelmet", "12345", phone="555-555-5555")
#or log in an existing user with
u = parse_rest.User.login("dhelmet", "12345")
# Once a User has been logged in, it saves its session so that it can be edited or deleted:
u.highscore = 300
u.save()
u.delete()
I really want to know what all I can do with the user object. This behavior seems wonky.
This was a case of (at the time) out-of-date documentation, fixed as of 3/11/2013. The way to access the User class is not parse_rest.User but:
from parse_rest.user import User
The answer is don't use that library. My colleague has one we home rolled checked into our source tree and we're planning on releasing one. When we do I will post a link here for completeness. :)