Passing data to Rest API - python-3.x

i'm a newbie to Rest API's. i have been trying to create a api which takes input from users process it and send the output. basically, i have a file grades.py which predicts the grades of students using ML. and i have another file server.py with flask . and api code in server.py is '
#app.route('/Api/score/id',methods=['GET','POST'])
def getscore(score_id):
score_id=request.args['score_id']
return grades.predictor(score_id)
'
and i'm invoking the api with
'http://localhost:5000/Api/score/id?/score_id=1'
in postman.
I'm getting the error
'TypeError: getscore() missing 1 required positional argument: 'score_id' '
can anyone tell me what am i doing wrong?

Try removing the paramater score_id from the function
#app.route('/Api/score/id',methods=['GET','POST'])
def getscore():
score_id=request.args['score_id']
return grades.predictor(score_id)

Use this:
#app.route('/Api/score/id/<score_id>', methods=['GET','POST'])
def getscore(score_id):
return grades.predictor(score_id)
Try to call your route with http://localhost:5000/Api/score/id/1. This should work.

Related

Batch file creation to execute POST method in Flask API (windows)

I've to create a batch file so that it calls the following API POST method and executes it seamlessly on Windows. There is no input that is required to be provided to the POST method here
this is for a ML module which is being called by the API. I've tried calling the mentioned module directly through batch file and anaconda prompt but that doesn't work fine.
import CLassName1
from flask import Flask
app=Flask(__name__)
#app.route('/api/model/testing', methods=['POST'])
def test_model():
response=ClassName1.method_name1()
return response
#app.route('/test')
def post_health():
return "health"
if __name__ == '__main__':
app.run(host='127.0.0.1',port=15010, debug=True)
expected to run method_name1 and subsequent methods and then populate another file- 'Output' created in the parent folder.
actually- when method_name1 is executed directly from anaconda prompt throws an Import error after some time and keeps looping over
Can you please share the exact error stack trace that you are getting when you calls method_name1() because as long as method_name1() returns string or there is no error in method_name1(), this code should run.

How to implement multiple POST methods in CherryPy

I am new to cherryPy and I am working on communicating the GUI with Python functions, for it I am using CherryPy. I have followed this cherryPy tutorial. In that the POST method don't do much just return some string, but in my case there can be many functions which will communicate with GUI using the POST. I tried this:
#cherrypy.expose
class StringGeneratorWebService(object):
#cherrypy.tools.accept(media='text/plain')
def GET(self):
return cherrypy.session['mystring']
def POST(self, counter,param):
if counter == 1:
function1(param) # call a python function
elif counter == 2:
function2(param)
elif counter == 3:
function3(param)
def PUT(self, another_string):
cherrypy.session['mystring'] = another_string
def DELETE(self):
cherrypy.session.pop('mystring', None)
In above code in POST method, the counter and Param are parameters from the AJAX request. According to the counter value I am calling the respective function. The Param can be a big JSON document. The above code works but this is very crude way to do this, so is there other way which is a good coding practice?
The documentation is a little confusing, but you only need to implement the GET/POST Python methods if you want CherryPy to call different functions for you based on the HTTP method. If you don't care about GET requests on your POST URLs you can just use the #cherrypy.expose pattern.
If you look at the tutorial source for forms there's this helpful bit about exposing POST methods:
[Using HTTP POST method] would not change your application’s exposed method because CherryPy handles both the same way and uses the exposed’s handler parameters to deal with the query-string (key, value) pairs.
Modifying the handler to include the method makes this clear:
class StringGenerator(object):
#cherrypy.expose
def generate(self, length=8):
return cherrypy.request.method + ' ' + ''.join(random.sample(string.hexdigits, int(length)))
Now I can use curl make a GET then a POST request:
$ curl "http://example.com:8888/generate?length=8" # does a GET
GET 78A35e4f
$ curl "http://example.com:8888/generate" --data "length=8" # does a POST
POST 14d0D92c

Return from before_request() in flask

I'm new to flask and currently converting an existing WSGI application to run through flask as long term it'll make life easier.
All requests are POST to specific routes however the current application inspects the post data prior to executing the route to see if the request needs to be run at all or not (i.e. if an identifier supplied in the post data already exists in our database or not).
If it does exist a 200 code and json is returned "early" and no other action is taken; if not the application continues to route as normal.
I think I can replicate the activity at the right point by calling before_request() but I'm not sure if returning a flask Response object from before_request() would terminate the request adequately at that point? Or if there's a better way of doing this?
NB: I must return this as a 200 - other examples I've seen result in a redirect or 4xx error handling (as a close parallel to this activity is authentication) so ultimately I'm doing this at the end of before_request():
if check_request_in_progress(post_data) is True:
response = jsonify({'request_status': 'already_running'})
response.status_code = 200
return response
else:
add_to_requests_in_progress(post_data)
Should this work (return and prevent further routing)?
If not how can I prevent further routing after calling before_request()?
Is there a better way?
Based on what they have said in the documents, it should do what you want it to do.
The function will be called without any arguments. If the function returns a non-None value, it’s handled as if it was the return value from the view and further request handling is stopped.
(source)
#app.route("/<name>")
def index(name):
return f"hello {name}"
#app.before_request
def thing():
if "john" in request.path:
return "before ran"
with the above code, if there is a "john" in the url_path, we will see the before ran in the output, not the actual intended view. you will see hello X for other string.
so yes, using before_request and returning something, anything other than None will stop flask from serving your actual view. you can redirect the user or send them a proper response.

Reading POST data - CherryPy web-framework

I'm new with CherryPy web-framework. I would like to know how can
I read POST data that was delivered via HTTP request's body .
Thanks,
Gabriel.
You can either read the body of the request with cherrypy.request.body, cherrypy.request.params or if you use the default handler then, the distinction between GET and POST values is abstracted by cherrypy and you can get the values directly from the arguments:
#cherrypy.expose
def index(self, name, age):
return "My name is %s and age is %s" % (name, age)
Your POST request must have to provide the values for name and age on the traditional forms submission.
If you are planning on using json, then use the cherrypy.tools.json_in decorator and read the cherrypy.request.json property. http://docs.cherrypy.org/en/latest/basics.html#dealing-with-json
If you are using the MethodDispatcher, then there is another way to do it: http://docs.cherrypy.org/en/latest/tutorials.html#tutorial-7-give-us-a-rest
Maybe these posts might help you:
http://blog.joel.mx/posts/cherrypy-101
http://blog.joel.mx/posts/cherrypy-101-method-dispatcher
Cherrypy handles both get and post in a similar way by passing them into the function or method that is handling the request. A good example is located at tut03_get_and_post.py in the tutorial folder within the cherrypy package.
Here is a small portion that specifically speaks to your question...
#cherrypy.expose
def greetUser(self, name=None):
# CherryPy passes all GET and POST variables as method parameters.
# It doesn't make a difference where the variables come from, how
# large their contents are, and so on.

Print the request step response in groovy script step using variable

I have a requirement in which I need to print XML response in Groovy Script test step
Name of SOAP Request test step is Licensed
When I write
log.info context.expand('${Licensed#Response}')
I get right response
But I have a requirement where user is not aware of the code
def requestname=Licensed //user will enter request name here
log.info context.expand($'{requestname"#Response}')
I don't get valid response
I want to declare a variable and use and print xml response
Here is what you need in order use the step name as parameter / variable. You have a trivial error in your code snippet.
//You missed quotes
def requestname='Licensed'
//Your were using quotes incorrectly
log.info context.expand('${'+requestname+'#Response}')
Hope this resolves your issue.

Resources