3

我想从我写的一个简单的发票应用程序创建一个 Web 服务。我希望它从 apache 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

我是编程新手,对网络服务更是如此,如果我以错误的方式处理这个问题,请告诉我。

4

3 回答 3

4

你当然可以忽略 html 部分。Flask 是一种创建 Web 应用程序的轻量级方式。如果需要,您可以只返回 json(或其他数据)作为对所有 url 的响应,并完全忽略 html 模板。

您可以在路由定义中包含任意数量的参数/正则表达式,每个参数都会为函数创建一个新参数。

@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 在其 URL 路由中是否支持正则表达式?

于 2012-09-10T16:31:32.173 回答
2

烧瓶是适合这项工作的工具吗?

Flask 是一个微型 Python 网络框架,如 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()
于 2012-09-10T16:46:24.083 回答
0

感谢大家的所有回答,他们有很多帮助。下面是一些工作示例代码,从无参数到参数,然后是带有 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

本地主机:端口/mathapi/3/4/ - 输出= 3 + 4 = 7

本地主机:端口/mathapi/mathapijson/3/4/ - 输出= {“y”:4,“x”:3,“结果”:7}

于 2012-09-10T19:14:18.143 回答