How to pass a parameter from client side to server in python

385 Views Asked by At

I am using flask and flask-restx try to create a protocol to get a specific string from another service. I am wonder if there is a way I can pass the parameter from another function to server side. For example, here's my server side:

from flask_restx import Api,fields,Resource
from flask import Flask
app = Flask(__name__)
api = Api(app)

parent = api.model('Parent', {
    'name': fields.String(get_answer(a,b)),
    'class': fields.String(discriminator=True)
})
@api.route('/language')
class Language(Resource):
    # @api.marshal_with(data_stream_request)
    @api.marshal_with(parent)
    @api.response(403, "Unauthorized")
    def get(self):

        return {"happy": "good"}

get_answer function in a different file:

get_answer(a,b):
  return a + b

What I expect is to get the result of get_answer from a file, and then my API is generated so that the GET request can get it. I know that if there is a web page, we can use render_template( or form to get it. But what if I want to get the value from another function? I know we only run the server with app.run(), but are we able to pass any value into the server? Guessing app.run(a,b) should not work in this case. We definite need to pass two parameter into the server. Or we can store the answer of get_answer(a,b) in main with specific value of a and b, then pass the number into the server side. But it will need the parameter either way.


One thing I've tested is wrapping up the server into a function. But in our case, is it a good idea to wrap a class inside a function as we have class Language(Resource):?

1

There are 1 best solutions below

2
OneCricketeer On BEST ANSWER

get_answer function in a different file

Then import and call it

from other_file import get_answer

... 
def get(self):
    return {"answer": get_answer(2,2)}

As the other answer shows, if you want to use custom arguments, parse them from the request object