[英]How to pass a parameter from client side to server in python
I am using flask
and flask-restx
try to create a protocol to get a specific string from another service.我正在使用flask
并且flask-restx
尝试创建一个协议以从另一个服务获取特定的字符串。 I am wonder if there is a way I can pass the parameter from another function to server side.我想知道是否有一种方法可以将参数从另一个 function 传递到服务器端。 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 function 在不同的文件中:
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.我期望的是从一个文件中得到get_answer
的结果,然后生成我的API,这样GET请求就可以拿到了。 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.我知道如果有一个 web 页面,我们可以使用render_template(
或form
来获取它。但是如果我想从另一个 function 获取值怎么办?我知道我们只使用app.run()
运行服务器,但是我们可以将任何值传递到服务器吗?猜测app.run(a,b)
在这种情况下不应该起作用。我们肯定需要将两个参数传递到服务器。或者我们可以存储get_answer(a,b)
的答案在 main 中使用a
和b
的特定值,然后将数字传递到服务器端。但无论哪种方式都需要参数。
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):
?我测试过的一件事是将服务器包装成 function。但在我们的例子中,将 class 包装在 function 中是个好主意,因为我们有class Language(Resource):
get_answer function in a different file get_answer function 在不同的文件中
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正如另一个答案所示,如果您想使用自定义 arguments,请从请求 object 中解析它们
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.