![](/img/trans.png)
[英]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.