getting url parameters in tornado - rest

i've been facing some problems in getting url parameters using Tornado web framework.
these are my codes:
def main_app():
return tornado.web.Application([
(r"/reg", register),
(r"/account", account),
])
class account(tornado.web.RequestHandler):
def get(self):
name = self.get_argument('name')
depo = self.get_argument('depo')
respone = {'name':name ,'depo':depo}
self.write(respone)
i've tried to use some restful API to test this web service.
i curl a url like curl localhost:8000/account?name = "parsa" & depo = "10"
but always i get this error that says it doesn't recognize depo. actually i tested something and it showed that each time the second parameter doesn't work well or even the third one doesn't work.
i tried several ways but didn't work.

This is not a problem with your Tornado code. You are making the curl request incorrectly. You can verify that by visiting that url from your browser.
With, curl, you'll have to wrap the whole url in quotes:
curl "localhost:8000/account?name=para&depo=10"

Related

Groovy Rest/HTTP Request Native for use with Script Runner

I am trying to build a simple Http Get request that requires me to submit an api key as authentication (api key as unsername and blank password). I have seen some solutions using the groovyx.net.http.HTTPBuilder library. However, the piece of code will need to be deployed in an evironment that does not allow for libraries. So I tried the following where is the url of the website i am trying to reach:
// GET
def get = new URL("<url>").openConnection();
def getRC = get.getResponseCode();
println(getRC);
if(getRC.equals(200)) {
println(get.getInputStream().getText());
}
As expected this returns error 400 since I do not include any authentication with the api key, so I tried the following where is the api key:
def get = new URL("<url>");
def authString = "<api_key>:".getBytes().encodeBase64().toString();
def conn = get.openConnection();
conn.setRequestProperty("Authorization", "Basic ${authString}");
def getRC = conn.getResponseCode();
println(getRC);
println(conn.getInputStream().getText());
But I still get the 400 error. I tried picking up the request through Fiddler but it doesn't seem to be tracking it (executing Groovy code through GroovyConsole).
The second approach works. My mistake was to not substitute spaces in the URL with % signs.

Groovy REST URL mapping containing forward slashes

I have a REST service in Groovy on Grails; basic service that takes data and transforms it. It works fine except when the data being passed in has forward or back slashes. In those cases the browser tries to navigate to a directory based on the data:
localhost/traverse/map/321 64 fourth <<< this works fine
localhost/traverse/map/321/64/fourth <<< tries to find localhost/traverse/map/321/64/fourth and throws an http status 404
My urlmapping:
"map/$id" (controller: "map", action: "transform", formats=['text/plain'], method: "GET")
My controller. aside from the class declaration and class import nothing else going on:
def transform = {
//println params.id
if (param.id) {
DataMap dm = new DataMap();
render dm.hostNodeLookup(params.id)
}
}
Most of the data that will be passed to the REST service will have slashes and the number of slashes per "data being passed in" will vary from 1-N but I haven't been able to figure out how to escape/parse/other wise get around that issue. I've read up on this site but I didn't find it too helpful for this problem.
I do not have access to the web server to adjust encoding or how browsers render URL mappings and strings. The data doesn't get to the controller so I haven't been able to parse out the strings there. Anyone have ideas?
After reading this post I tried it and it worked like a charm.
In the urlmapping file I added this ** to the id variable:
"map/$id**" (controller: "map", action: "transform", formats=['text/plain'], method: "GET")

Rails 3.1 - Facebook Page API calls

I have the following working perfectly for calls to Facebook pages with simple URLS like: www.facebook.com/TurbonegroHQ
def get_facebook
#artist = Artist.accessible_by(current_ability).find(params[:id])
if #artist.facebook_url.present?
require 'open-uri'
require 'json'
result = JSON.parse(open("https://graph.facebook.com/"<<#artist.facebook_url).read)
#hometown = result["hometown"]
#band_members = result["band_members"]
#likes = result["likes"]
end
end
However, when a Facebook page URL isn't in this format, but something like https://www.facebook.com/pages/Clutch-The-Bakerton-Group-Weathermaker-Music/16637738637 it fails. Any ideas how I can get around this?
Thanks in advance?
TurbonegroHQ is the username of the page - this is interchangeable with the object ID in the Graph API.
If the page doesn't have a username you need to access it via the ID instead. In that case https://graph.facebook.com/16637738637 is the URL to access
Usually you'll have IDs rather than the URLs as the ID is returned in the API on all the endpoints I can think of

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'

Nothing except "None" returned for my Python web.py Facebook app when I turn on "OAuth 2.0 for Canvas"

I am a beginning Facebook app developer, but I'm an experienced developer. I'm using web.py as my web framework, and to make matters a bit worse, I'm new to Python.
I'm running into an issue, where when I try to switch over to using the newer "OAuth 2.0 for Canvas", I simply can't get anything to work. The only thing being returned in my Facebook app is "None".
My motivation for turning on OAuth 2.0 is because it sounds like Facebook is going to force it by July, and I might as well learn it now and now have to rewrite it in a few weeks.
I turned on "OAuth 2.0 for Canvas" in the Advanced Settings, and rewrote my code to look for "signed_request" that is POSTed to my server whenever my test user tries to access my app.
My code is the following (I've removed debugging statements and error checking for brevity):
#!/usr/bin/env python
import base64
import web
import minifb
import urllib
import json
FbApiKey = "AAAAAA"
FbActualSecret = "BBBBBB"
CanvasURL = "http://1.2.3.4/fb/"
RedirectURL="http://apps.facebook.com/CCCCCCCC/"
RegURL = 'https://graph.facebook.com/oauth/authorize?client_id=%s&redirect_uri=%s&type=user_agent&display=page' % (FbApiKey, RedirectURL)
urls = (
'/fb/', 'index',
)
app = web.application(urls, locals())
def authorize():
args = web.input()
signed_request = args['signed_request']
#split the signed_request via the .
strings = signed_request.split('.')
hmac = strings[0]
encoded = strings[1]
#since uslsafe_b64decode requires padding, add the proper padding
numPads = len(encoded) % 4
encoded = encoded + "=" * numPads
unencoded = base64.urlsafe_b64decode(str(encoded))
#convert signedRequest into a dictionary
signedRequest = json.loads(unencoded)
try:
#try to find the oauth_token, if it's not there, then
#redirect to the login page
access_token = signedRequest['oauth_token']
print(access_token)
except:
print("Access token not found, redirect user to login")
redirect = "<script type=\"text/javascript\">\ntop.location.href=\"" +_RegURL + "\";\n</script>"
print(redirect)
return redirect
# Do something on the canvas page
returnString = "<html><body>Hello</body></html>"
print(returnString)
class index:
def GET(self):
authorize()
def POST(self):
authorize()
if __name__ == "__main__":
app.run()
For the time being, I want to concentrate on the case where the user is already logged in, so assume that oauth_token is found.
My question is: Why is my "Hello" not being outputted, and instead all I see is "None"?
It appears that I'm missing something very fundamental, because I swear to you, I've scoured the Internet for solutions, and I've read the Facebook pages on this many times. Similarly, I've found many good blogs and stackoverflow questions that document precisely how to use OAuth 2.0 and signed_request. But the fact that I am getting a proper oauth_token, but my only output is "None" makes me think there is something fundamental that I'm doing incorrectly. I realize that "None" is a special word in python, so maybe that's the cause, but I can't pin down exactly what I'm doing wrong.
When I turn off OAuth 2.0, and revert my code to look for the older POST data, I'm able to easily print stuff to the screen.
Any help on this would be greatly appreciated!
How embarrassing!
In my authorize function, I return a string. But since class index is calling authorize, it needs to be returned from the class, not from authorize. If I return the return from authorize, it works.