I am trying to Upload the image using Django 1.8 and tastypie - tastypie

I am using Django 1.8 ,tastypie 0.13.0 versions,
while make the POST request it gives an error. UnsupportedFormat: The format indicated 'application/form-data' had no available deserialization method. Please check your formats and content_types on your Serializer.
class MultiPartResource(object):
def deserialize(self, request, data, format=None):
if not format:
format = request.Meta.get('CONTENT_TYPE', 'application/json')
if format == 'application/x-www-form-urlencoded':
return request.POST
if format.startswith('multipart/form-data'):
data = request.POST.copy()
data.update(request.FILES)
return data
return super(MultiPartResource, self).deserialize(request, data, format)
def patch_detail(self, request, **kwargs):
if request.META.get('CONTENT_TYPE', '').startswith('multipart/form- data') and not hasattr(request, '_body'):
request._body = ''
return super(MultipartResource, self).patch_detail(request, **kwargs)

Take a look at this issue: https://github.com/django-tastypie/django-tastypie/issues/42#issuecomment-5485666
It is about file upload support and how to deal with multipart/form-data.
Also, I suggest that you implement this tastypie field https://gist.github.com/klipstein/709890 to solve this.
Hope this work for you.

Use tastypie-extras MultipartResourceMixin
from tastypie_extras import MultipartResourceMixin
class MyResource(MultipartResourceMixin, ModelResource):
....
Tested on Django 1.4 and 1.8 and Tastypie 0.9.12 and 0.13.0

Related

mocking a request with a payload using wiremock

I'm currently trying to mock external server using Wiremock.
One of my external server endpoint takes a payload.
This endpoint is defined as follow :
def sendRequestToMockServer(payload: String) = {
for {
request_entity <- Marshal(payload).to[RequestEntity]
response <- Http().singleRequest(
HttpRequest(
method = HttpMethods.GET,
uri = "http://localhost:9090/login",
entity = request_entity
)
)
} yield {
response
}
}
To mock this endpoint using Wiremock, I have written the following code :
stubFor(
get(urlEqualTo("/login"))
.willReturn(
aResponse()
.withHeader("Content-Type","application/json")
.withBodyFile("wireMockResponse.json")
.withStatus(200)
)
.withRequestBody(matchingJsonPath("requestBody.json"))
)
where I Have defined the request body in the requestBody.json file.
But when I run tests , I keep getting an error indicating that the requested Url is not found.
I'm thinking that the error is related to this line withRequestBody(matchingJsonPath("requestBody.json")), because when I comment it the error disappear.
Any suggestions on how to work around this?
matchingJsonPath does not populate a file at a provided filepath, but instead evaluates the JsonPath provided. See documentation.
I'm not entirely sure there is a way to provide the request body as a .json file. If you copy the contents of the file into the withRequest(equalToJson(_yourJsonHere_)), does it work? If it does, you could get the file contents as a JSON string above the definition and provide it to the function (or I guess, make a function to return a JSON string from a .json file).
Additionally, you could make a custom request matcher that does the parsing for you. I think I'd recommend this only if the above does not work.

XPages REST and date format

I have an XPages page which contains the REST service component. I'm using the "documentJsonService".
Awesome component and everything else is working fine, but I'm having issues with the date formats and don't know what to do.
The Notes Document where I'm reading the data from, contains a DateTime item having a proper date e.g. 01.09.2014 (finnish format: dd.MM.yyyy). The REST component returns the date in "2014-09-01" (string). This is fine. However when I do a HTTP POST to the server with the same exact data, Domino changes the "2014-09-01" string date into 09.01.2014 Notes Date time item.
Don't know any more what to do. Why Domino gives date in format A and when I give it back in same format, something strange happens.
This same happens on Linux and Windows environments.
Domino version is 9.0.1.
Thanks already. I'm more or less lost with this "feature" :)
I would say: broken as designed. To my knowledge the JSON format returned is always in the form yyyy-mm-dd, while the format expected when posting depends on the browser locale. You would need to "hack around it".
I'm not a big fan of the ready baked JSON services, I'd rather roll my own, where I can be very specific with the formats and (more importantly) add validation before I write data back. You can find a sample on my blog
Basically you implement a bean like this:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ibm.domino.services.ServiceException;
import com.ibm.domino.services.rest.RestServiceEngine;
import com.ibm.xsp.extlib.component.rest.CustomService;
import com.ibm.xsp.extlib.component.rest.CustomServiceBean;
public class CustomSearchHelper extends CustomServiceBean {
#Override
public void renderService(CustomService service, RestServiceEngine engine) throws ServiceException {
HttpServletRequest request = engine.getHttpRequest();
HttpServletResponse response = engine.getHttpResponse();
response.setHeader("Content-Type", "application/json; charset=UTF-8");
// Your code goes here!
}
}
you need to check in the request what method GET or POST was used, but then it is easy to continue. While you are on it: the OpenNTF Domino API makes your life much easier.

Box API 2.0: Unable to Download

I'm testing out the new API, but having no luck downloading a test image file. The file exists, is accessible through the web UI, and is retrievable using the v1.0 API.
I'm able to access the metadata ("https://api.box.com/2.0/files/{fileid}") using both commandline curl and pycurl. However, calls to "https://api.box.com/2.0/files/{fileid}/data" bring back nothing. An earlier post (5/1) received the answer that the download feature had a bug and that "https://www.box.com" should be used as the base URL in the interim. That, however, just provokes a 404.
Please advise.
You should be able to download via http://api.box.com/2.0/files/<fildID>/content ... Looks like we have a bug somewhere in the backend. Hope to have it fixed soon.
Update 11/13/2012 -- This got fixed at least a month ago. Just updated the URL to our newer format
For me it works when its /content instead of /data... python code below
import requests
fileid = str(get_file_id(filenumber))
url = https://api.box.com/2.0/files/1790744170/content
r = requests.get(url=url, headers=<HEADERS>, proxies=<PROXIES>)
infoprint("Downloading...")
filerecieved = r.content
filename = uni_get_id(fileid, "name", "file")
f = open(filename, 'w+')
infoprint("Writing...")
f.write(filerecieved)
f.close()

SoundCloud parsing basic search results, is there api support?

...just wanted to confirm that since the latest soundcloud api does not provide a data interface, we are left with parsing the results from an http request.
my concern is that the resulting structure could change at anytime and thus render my parsing schema invalid. is anyone else doing something similar? or better?
This is correct. All SoundCloud API responses will be serialized as JSON or XML. We take backwards compatibility pretty seriously, so you can rely on the format and data returned.
Most languages have at least one library capable of automatically parsing JSON into an appropriate data type (i.e. an array of hashes). You can always check to ensure a key exists before you try to access it, for example in Python:
import json
import urllib
url = 'https://api.soundcloud.com/tracks.json'
fp = urllib.urlopen('%s?%s' % (url, urllib.urlencode({
'client_id': 'YOUR_CLIENT_ID',
'limit': 2
})))
data = fp.read()
tracks = json.loads(data)
for track in tracks:
print track.get('title', 'No title available')
Does that help answer your question?

How to post a file in grails

I am trying to use HTTP to POST a file to an outside API from within a grails service. I've installed the rest plugin and I'm using code like the following:
def theFile = new File("/tmp/blah.txt")
def postBody = [myFile: theFile, foo:'bar']
withHttp(uri: "http://picard:8080/breeze/project/acceptFile") {
def html = post(body: postBody, requestContentType: URLENC)
}
The post works, however, the 'myFile' param appears to be a string rather than an actual file. I have not had any success trying to google for things like "how to post a file in grails" since most of the results end up dealing with handling an uploaded file from a form.
I think I'm using the right requestContentType, but I might have missed something in the documentation.
POSTing a file is not as simple as what you have included in your question (sadly). Also, it depends on what the API you are calling is expecting, e.g. some API expect files as base64 encoded text, while others accept them as mime-multipart.
Since you are using the rest plugin, as far as I can recall it uses the Apache HttpClient, I think this link should provide enough info to get you started (assuming you are dealing with mime-multipart). It shouldn't be too hard to change it around to work with your API and perhaps make it a bit 'groovy-ier'