Request Post in GAE Method Request Post in GAE - forms

I wonder if there is a way to make a request for a form which was sent by post in a way more dynamic without having to be variable by setting the variable. I mean if I have a form with 10 fields instead of doing:
var1 = self.request ('text1')
[...]
var10 self.request = ('text10')
If there is any way that he has returned me a list where the list argument is the field name and the value of the argument is the field value, eg:
list = { 'text1': value_text1, [ ... ] }
Tanks.

I think you are talking about the get_all() function. For more details see this reference

Related

How to get the "body" and "subject" fields of a draft when extending compose UI?

We are developing a Gmail Addon in which we extend the compose UI.
This extends the compose window in which you can compose your e-mail.
We need the 'From', 'To', 'Subject' and 'Body' of the message that is being composed.
The 'From' can be read from the Session object like this
var mySelf = Session.getEffectiveUser().getEmail();
The 'To' can be read from the draftMetadata from the event object of the function being called.
function composeEmail(event) { console.log(event.draftMetadata.toRecipients); }
The 'Subject' and 'Body' can't be read from the event object of the function since it is a composeTrigger. The argument contains these objects:
{
formInput = {},
clientPlatform = web,
formInputs = {},
parameters = {},
draftMetadata = {
toRecipients = [test #test.com],
subject = ,
bccRecipients = [],
ccRecipients = []
}
}
Surprisingly to me, the subject key is there but not being filled in (yes I did type in a subject).
Question:
How can I get the 'Subject' and 'Body' of the E-mail being composed by the user in the extended composer UI?
Extra information:
The contextual trigger action contains the following object as event object:
{
clientPlatform = web,
messageMetadata = {
messageId = 16e agg7323451256989f68,
accessToken = AAGdOAawdaAOW8PWchmdawdk0N13STKnBPMAOXVjZVHyQMfAawdBtgEIrS6N8y5h2BOZnKFPlfsl5VBsyPiF7YiONOoP7XVjKZawdi - E6vI - jVU92dPmfj3RNmXfawdawdeaNMrXehAFLm
}
}
By reading an email through the contextual trigger a messageId is being added in which the getBody and getSubject methods can be used.
As of now, the Compose Trigger Event never returns the value of the subject field.
I have filled a bug for this here. Click the ★ icon to follow this Issue and get updates. This will also help prioritize this Issue.
As a workaround, you can use the contextual trigger to:
Get the messageId
Find drafts that have that messageId associated to them
Get the draft by their draftId
Fetch the subject line from the Headers object on the draft.
This only works on drafts that are replying to a specific message.
I've never done this before so this is a guess. I looked at the compose dialog html with the developer tools and this is what I noticed.
There seem to be a bunch of hidden inputs that are used to store values that are typed into the compose dialog. So I would try something like:
formInputs.body or perhaps formInput.body taking the name of the key from names of this hidden elements. This is just a guess.

Iterative Post request in Postman

I need help for doing Post request repeatedly in Postman with different bodies. Example given below, where company name must be changed. It would be better to read company names from a document or may be from an array in script. Please advice how can I do it?
{
"d": "{{company}}"
}
I found somethin like that, but I am getting error: (There was an error in evaluating the Pre-request Script: TypeError: Cannot read property 'get' of undefined)
Pre-request Script:
if(!companies){
companies = ["111",
"222",
"333"];
}
var currentCompany = companies.shift();
pm.enviroment.set("company",currentCompany);
pm.enviroment.set("companies", companies);
Tests:
var companies = pm.enviroment.get("companies");
if(companies && companies.length > 0){
postman.setNextRequest("my url");
} else {
postman.setNextRequest(null);
}
There are multiple but small mistakes:
the set environment function is misspelled: please use pm.environment.set(right) instead of pm.enviroment.set(false)
you have to load the companies var from the environments before. Add var companies = JSON.parse(pm.environment.get("companies")); to the first line of your pre rquest script.
Please make sure that you are saving string values to the environment vars. Use JSON.stringify(myObject) e.g. pm.environment.set("company", JSON.stringify(currentCompany)); and analogue JSON.parse(myStringVar) for loading variables in var companies = JSON.parse(pm.enviroment.get("companies"));
(Maye also a problem) Please make sure, there is a enviroment chosen in Postman, postman-runner and newman. If there is no environment set, you can get errors:

Posting multiple images to tumblr using tumblr.js api

I am trying to creating a app which can send posts to tumblr using tumblr.js api.
I could send single image using the createPhotoPost method, but I have to send multiple image in a single post via this method.
From the documentation it says that createPhotoPost method has a "data" parameter which can be an array with "URL-encoded binary contents"
When ever I try to send something in the data Array it returns "[Error: form-data: Arrays are not supported.]".
Can someone please help to solve this issue and please explain what should we pass in the array (Really I am not getting what is URL-encoded binary contents)?
Thanks in advance
There is an error in tumblr.js
https://tumblr.github.io/tumblr.js/tumblr.js.html#line504
The documentation at https://www.tumblr.com/docs/en/api/v2#posting is correct.
Basically the issue is that its not supposed to be
data = [ one , two ] its litterally params['data[0]'] = one ; params['data[1]'] = two; (?A PHP Convention)
var request = require('request')// already a tumblr.js dependency
var currentRequest = request({
url:'https://api.tumblr.com/v2/blog/someblog.tumblr.com/post',
oauth:keys,
},function(err,response,body){
currentRequest//
debugger
cb()
})
var params = {
'type' :'photo',
'caption':'Click To Verify You Are A Robot',
}
var params_images = [
fs.createReadStream('image'),
fs.createReadStream('image')
]
// Sign it with the non-data parameters
currentRequest.form(params)
currentRequest.oauth(keys);
// Clear the side effects from form(param)
delete currentRequest.headers['content-type'];
delete currentRequest.body;
// And then add the full body
var form = currentRequest.form();
//###add params_images to params keys 'data[0]' 'data[1]' 'data[2]' ....
params_images.forEach(function(image,index){
params['data['+index+']']
})
for (var key in params) {
form.append(key, params[key]);
}
// Add the form header back
var form_headers = form.getHeaders()
for(var key in form_headers){
currentRequest[key] = form_headers[key]
}

Play Framework 2.4 how to use return statement in Action controller

is there a way to return a value inside Action controller.
I have a method in my User model which returns the number of friends of a given user.
def nrOfFriends(current_user: Long): Int = {
DB.withConnection{ implicit connection =>
var nr: Int = SQL("select count(*) from friend where user_id_1=" + current_user + " or user_id_2=" + current_user).as(scalar[Int].single)
nr
}
}
In my controller, I just want to return the value from the model
def freunde() = IsAuthenticated { username => _ =>
User.findByUsername(username).map { user =>
var nr: Int = Friend.nrOfFriends(user.id.get)
Ok(""+nr)
}.getOrElse(Forbidden)
}
But in the way that is written, it will print "empty string " concatenated with the number
If I replace Ok(""+nr) with Ok(nr) I receive the following error:
"Cannot write an instance of Int to HTTP response. Try to define a Writeable[Int]"
I need for my action to return a value so that I can pass the value from the action to header.views.html inside the navbar something like that
#Freund.freunde Friends
if you want your response to just be the value of nr you can simply call nr.toString:
def freunde() = IsAuthenticated { username => _ =>
User.findByUsername(username).map { user =>
var nr: Int = Friend.nrOfFriends(user.id.get)
Ok(nr.toString)
}.getOrElse(Forbidden)
}
The error you're getting makes reference to the fact that Int doesn't have an implicit Writeable[Int] in scope. So play doesn't know how display an Int in an http response.
You can add make Int writeable by putting this in scope:
implicit val intWriteable = play.api.http.Writeable[Int](_.toString.getBytes, None)
Then you would be able to just say:
Ok(nr)
without error.
However, it sounds like you just want the result of nrOfFriends inside an unrelated template. If that's the case, you should be using an Action at all. Instead just call your model function inside the template where you need the data.
#User.nrOfFriends(user.id) Friends
Of course you would need to pass in the user to the template as well.
You didn't post a full sample of all the code involved in what you are trying to accomplish so I think this is the best I can do for now. Perhaps try posting the base template that your <a> is in.
An important point is that Actions are for production an HTTP response, and not just plain data internally to the application.
An action of a controller handles a request and generates a result to be sent to the client. In other words, an action returns a play.api.mvc.Result value, representing the HTTP response to send to the web client. In your example Ok constructs a 200 OK response. The body of the response must be one of the predefined types, including text/plain, json, and html. The number of a friends is an integer and is NOT an acceptable type of the body. Therefore, a simple way to address this problem is to convert it into a text/plain using .toString().
On the other hand, you can define a writer for Int that lets Play know how to convert an integer into a json format.
For more details, please take a look at this https://www.playframework.com/documentation/2.2.x/ScalaActions.

PUT Request not happening at all in Fantom

I am having some trouble with PUT requests to the google sheets api.
I have this code
spreadsheet_inputer := WebClient(`$google_sheet_URI_cells/R3C6?access_token=$accesstoken`)
xml_test := XDoc{
XElem("entry")
{
addAttr("xmlns","http://www.w3.org/2005/Atom")
addAttr("xmlns:gs","http://schemas.google.com/spreadsheets/2006")
XElem("id") { XText("https://spreadsheets.google.com/feeds/cells/$spreadsheet_id/1/private/full/R3C6?access_token=$accesstoken"), },
XElem("link") { addAttr("rel","edit");addAttr("type","application/atom+xml");addAttr("href","https://spreadsheets.google.com/feeds/cells/$spreadsheet_id/1/private/full/R3C6?access_token=$accesstoken"); },
XElem("gs:cell") { addAttr("row","3");addAttr("col","6");addAttr("inputValue","testing 123"); },
},
}
spreadsheet_inputer.reqHeaders["If-match"] = "*"
spreadsheet_inputer.reqHeaders["Content-Type"] = "application/atom+xml"
spreadsheet_inputer.reqMethod = "PUT"
spreadsheet_inputer.writeReq
spreadsheet_inputer.reqOut.writeXml(xml_test.writeToStr).close
echo(spreadsheet_inputer.resStr)
Right now it returns
sys::IOErr: No input stream for response 0
at the echo statement.
I have all the necessary data (at least i'm pretty sure) and it works here https://developers.google.com/oauthplayground/
Just to note, it does not accurately update the calendars.
EDIT: I had it return the response code and it was a 0, any pointers on what this means from the google sheets api? Or the fantom webclient?
WebClient.resCode is a non-nullable Int so it is 0 by default hence the problem would be either the request not being sent or the response not being read.
As you are obviously writing the request, the problem should the latter. Try calling WebClient.readRes() before resStr.
This readRes()
Read the response status line and response headers. This method may be called after the request has been written via writeReq and reqOut. Once this method completes the response status and headers are available. If there is a response body, it is available for reading via resIn. Throw IOErr if there is a network or protocol error. Return this.
Try this:
echo(spreadsheet_inputer.readRes.resStr)
I suspect the following line will also cause you problems:
spreadsheet_inputer.reqOut.writeXml(xml_test.writeToStr).close
becasue writeXml() escapes the string to be XML safe, whereas you'll want to just print the string. Try this:
spreadsheet_inputer.reqOut.writeChars(xml_test.writeToStr).close