[英]I need help to add a Conditional to Python Rock Paper Scissor game to catch wrong inputs and throw an error(sample code below)
[英]How do I turn the sample code below into accepting multiple inputs?
我想从我写的一个简单的发票应用程序创建一个Web服务。 我希望它能从jache fop返回json和希望的pdf文件。 我不想要一个html网页,我将从python桌面应用程序访问该服务。
我可以忽略文档的模板部分吗?
我遇到的最大问题是接受函数的多个参数。
如何将下面的示例代码转换为接受多个输入?
@app.route('/post/<int:post_id>')
def show_post(post_id):
# show the post with the given id, the id is an integer
return 'Post %d' % post_id
我是编程新手,对Web服务更是如此,如果我以错误的方式解决这个问题,请告诉我。
你肯定可以忽略html部分。 Flask是一种很好的轻量级创建Web应用程序的方法。 如果需要,您可以将json(或其他数据)作为对所有网址的响应返回,并完全忽略html模板。
您可以在路径定义中包含所需数量的params / regex每个都将为该函数创建一个新参数。
@app.route('/post/<int:post_id>/<int:user_id>/')
def show_post(post_id, user_id):
# show the post with the given id, the id is an integer
return 'Post %d' % post_id
烧瓶是适合这项工作的合适工具吗?
Flask是一个微型python web框架,如Bottle或webpy。 在我看来,简约的Web框架对您的工作很有帮助。
不要将作为可变部分的“变量规则”混淆为URL和函数的“经典”参数。
from flask import Flask
app = Flask(__name__)
@app.route('/post/<int:post_id>', defaults={'action': 1})
def show_post(post_id, action):
# show the post with the given id, the id is an integer
# show the defauls argument: action.
response = 'Post %d\nyour argument: %s' % (post_id, action)
return response
if __name__ == '__main__':
app.run()
感谢大家的所有答案,他们帮了很多忙。 下面是一些工作示例代码,从没有参数升级到参数,然后是json响应的参数。
希望下面的代码可以帮助某人。
from flask import Flask
from flask import jsonify
app = Flask(__name__)
@app.route('/')
def helloworld():
response = 'HelloWorld'
return response
@app.route('/mathapi/<int:x>/<int:y>/', methods = ['GET'])
def math(x, y):
result = x + y # Sum x,t -> result
response = '%d + %d = %d' %(x, y, result) #Buld response
return response #Return response
@app.route('/mathapijson/<int:x>/<int:y>/', methods = ['GET'])
def mathjs(x, y):
result = x + y #Sum x,t -> result
data = {'x' : x, 'y' : y, 'result' : result} #Buld arrary
response = jsonify(data) #Convert to json
response.status_code = 200 #Set status code to 200=ok
response.headers['Link'] = 'http://localhost'
return response #return json response
if __name__ == '__main__':
app.run(debug=True)
用法:
localhost:port / - 输出 - HelloWorld
localhost:port / mathapi / 3/4 / - output = 3 + 4 = 7
localhost:port / mathapi / mathapijson / 3/4 / - output = {“y”:4,“x”:3,“result”:7}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.