Quickbase module add_record() function—file upload parameters? - python

The code below is part of the Python Quickbase module which has not been updated in quite a while. The help text for one of the function shown below is not clear on how to pass the parameters to upload a file (the value of which is actually base64 encoded).
def add_record(self, fields, named=False, database=None, ignore_error=True, uploads=None):
"""Add new record. "fields" is a dict of name:value pairs
(if named is True) or fid:value pairs (if named is False). Return the new records RID
"""
request = {}
if ignore_error:
request['ignoreError'] = '1'
attr = 'name' if named else 'fid'
request['field'] = []
for field, value in fields.iteritems():
request_field = ({attr: to_xml_name(field) if named else field}, value)
request['field'].append(request_field)
if uploads:
for upload in uploads:
request_field = (
{attr: (to_xml_name(upload['field']) if named else upload['field']),
'filename': upload['filename']}, upload['value'])
request['field'].append(request_field)
response = self.request('AddRecord', database or self.database, request, required=['rid'])
return int(response['rid'])
Can someone help me in how I should pass the parameters to add a record.

Based on the definition you provided, it appears that you you need to pass an array of dictionaries that each provide the field name/id, filename, and the base64 encoding of the file for the uploads parameter. So, if I had a table where I record the name of a color to the field named "color" with the field id of 19 and a sample image to the field named "sample image" with the field id of 21, I believe my method call would be something like:
my_color_file = #base64 encoding of your file
my_fields = {'19': 'Seafoam Green'}
my_uploads = [{'field': 21, 'filename':'seafoam_green.png', 'value': my_color_file}]
client.add_record(fields=my_fields, uploads=my_uploads)
Or, if you're using field names:
my_color_file = #base64 encoding of your file
my_fields = {'color': 'Seafoam Green'}
my_uploads = [{'field': 'sample_image', 'filename':'seafoam_green.png', 'value': my_color_file}]
client.add_record(fields=my_fields, named=True, uploads=my_uploads)
client is just the object you instantiated earlier using whatever constructor this module has.

Related

passing parameter in Rest API request from other file or list variable- using

new to python and API.
i have list of values like below
typeid=['1','12','32','1000','9']
I have to pass this value as parameter in API request, so that it would take one typeid at a time and append the json. code i have following but not sure how it will move from one value to other?
# activity type id store as following in other .py file typeid=['1','12','32','1000','9']
#importing the file in main program file.
From typeid list import activitytypeids
act1 = requests.get(host + '/rest/v1/activities.json',
params={
'activityTypeIds': activitytypeids[0]
}).text
json_obj = json.loads(act1)
results.append(json_obj)
more_result = json_obj['moreResult']
while True:
act1 = requests.get(host + '/rest/v1/activities.json',
params={
'activityTypeIds': activitytypeids[0]
}).text
json_obj = json.loads(act1)
results.append(json_obj)
more_result =json(results['moreResult'])
if not more_result:
break
How do I pass the activity's in request param one by one, so that get the result of all type ids.
take your code to get one id and put it in a function that accepts an activity_id, and change all activitytypeids[0] to just be activity_id
From typeid list import activitytypeids
def get_activity_id(activity_id):
act1 = requests.get(host + '/rest/v1/activities.json',
params={
'activityTypeIds': activity_id
}).text
return act1.json()
then you can just iterate over your list
results = [get_activity_id(id) for id in activitytypeids]
that said it seems very surprising that a variable named activityTypeIds only accepts one id ... i would very much expect this to be able to accept a list based on nothing more than the variable name

Python, django, edit table with string

I don't know how set name for this question.. sorry.
I have function:
myFunction(request, {'Username': 'MyNewUsername', 'Sex': 'Woman', 'SexWant': 'Man'})
def myFunction(self, data):
dataquery = UserData.objects.get(Username = "Patrycja")
for name, key in data.items():
dataquery.name = key
dataquery.save()
Generally speaking this line: dataquery.name
name is 'Username', if I set dataquery.Username = good. But I have to do it as above
From what I understand, your query should be
dataquery = UserData.objects.get(username="Patrycja")
then be aware that the line
dataquery.name = key
sets the attribute name of the object.
In order to set the attributes whose name is specified in data you need to use setattr
for name, value in data.items():
setattr(dataquery, name, value)
and since you seem to want to update only such fields, call save specifing which fields should be updated
dataquery.save(update_fields=data.keys())
Note: please refer to #Sayse's answer in case you need to update more than one record at a time

Extract OFS Image Pdata object and save it as Namedfile on Dexterity

I have an Archetype content that has field called file and it is MultiFileField (from archetypes.multifile.MultiFileField). The schema is something like:
MultiFileField('file',
primary=True,
languageIndependent=True,
widget = MultiFileWidget(
label= "File Uploads",
show_content_type = False,))
And I have a Dexterity content type that has the same field name which is file and I want to create a script that extract the stored uploaded object from the Archetype content and pass it on the Dexterity custom content type. The schema for Dexterity custom content type is:
form.widget(file=MultiFileFieldWidget)
file = schema.List(
title=_(u"File Attachment"),
required=False,
value_type=NamedFile(),
)
I observed that Archetype's MultiFileField stores the uploaded object as OFS Image Pdata, and for the latter part, it stores as plone.namedfile.file.NamedFile object. Is there a way to convert the OFS object into Namedfile object?
Update:
I have found a solution but I am not sure if it's the right thing.
for field in prev_obj.Schema().fields():
key = field.getName()
objects_list = []
value = field.getRaw(prev_obj)
for f in value:
data = str(f['file'].data)
filename = unicode(f['filename'])
contentType = f['content_type']
fileData = NamedFile(data=data, contentType=contentType, filename=filename)
objects_list.append(fileData)
new_obj.file = copy.copy(objects_list)
First off, you may want to use NamedBlobFile instead.
Then, have you tried something like this to convert the data?
from plone.namedfile.file import NamedBlobFile
new_obj.file = [NamedBlobFile(str(fdata), contentType=fdata.content_type, filename=fdata.filename) for fdata in previous_obj.getFile()]
Assuming you have both previous_obj and new_obj available.

How to take a dictionary and send a JSON Response

I have the following function,
def facebooktest(request):
fb_value = ast.literal_eval(request.body)
fb_foodies = Foodie.objects.filter(facebook_id__in = fb_value.values())
for fb_foodie in fb_foodies:
state = request.user.relationships.following().filter(username = fb_foodie.user.username).exists()
userData = {
'fbid': fb_foodie.facebook_id,
'followState': int(state),
}
Basically I am checking to see which of the user's facebook friends are on my django app. If they are, return the followState. The followState basically returns a 1 or a 0. 1 if the user is already following them on my Django app and 0 if they are not following their facebook friend on my Django app.
I would like to return back a json type dictionary to that user that looks like this:
[{fbid:222222222222, followState: 0}, {fbid:111111111111, followState: 1}, {fbid:435433434534, followState:1}]
EDIT
I have the dictionary structure but I just want to return it like the structure above.
def facebooktest(request):
fb_value = ast.literal_eval(request.body)
fb_foodies = Foodie.objects.filter(facebook_id__in = fb_value.values())
response = []
for fb_foodie in fb_foodies:
state = request.user.relationships.following().filter(username = fb_foodie.user.username).exists()
userData = {
'fbid': fb_foodie.facebook_id,
'followState': int(state),
}
response.append(userData)
return json.dumps(response)
There is a function in the django.forms.models package for that: model_to_dict
from django.forms.models import model_to_dict
model_to_dict(your_model, fields=[], exclude=[])
From the help:
model_to_dict(instance, fields=None, exclude=None)
Returns a dict containing the data in ``instance`` suitable for passing as
a Form's ``initial`` keyword argument.
``fields`` is an optional list of field names. If provided, only the named
fields will be included in the returned dict.
``exclude`` is an optional list of field names. If provided, the named
fields will be excluded from the returned dict, even if they are listed in
the ``fields`` argument.
I think you're looking for this:
return HttpResponse(simplejson.dumps(response_dict), mimetype='application/json')
where 'response_dict' would be your dictionary.

Get All Field Values on Row

I am using the code below to get all values from a row.
from google.appengine.ext import db
from python_lib.models import Field
field = Field.all()[0]
names = Field.properties()
for key in names:
print field.get(key)
But it giving the following error,
BadKeyError: Invalid string key name.
You are confusing too different api's in this code.
for key in names:
print field.get(key)
Your get() call is invalid, as your are actually trying to call a class method to fetch an entity from the datastore - see the docs for this method https://developers.google.com/appengine/docs/python/datastore/modelclass#Model_get .
To get a property by name from an instance of field (your object) you should be using getattr
as in
for key in names:
print getattr(field,key)
or all alternately use get_value_for_datastore(model_instance) of the property object, which is returned from properties() call along with the name of the property.
Is this what you want?
Code:
from google.appengine.ext import db
class Field(db.Model):
author = db.StringProperty()
content = db.StringProperty(multiline=True)
date = db.DateTimeProperty(auto_now_add=True)
a = Field(author="me")
a.put()
EDIT:
field = Field.all()
for f in field:
print f.author
print f.content
props = Field.properties()
print props
for vals in props:
print vals
output:
<__main__.Field object at 0xb8c9e4c>
{'content': <google.appengine.ext.db.StringProperty object at 0xb7c0aec>, 'date': <google.appengine.ext.db.DateTimeProperty object at 0xb7c06cc>, 'author': <google.appengine.ext.db.StringProperty object at 0xb7c0f6c>}
content
date
author

Categories

Resources