基于Flask的最简Web请求

引言: Python功能强大,可以用来进行Web服务的开发,这里将给出一个最简单的示例,仅做参考。

Flask

这里使用了Flask作为Web服务的框架,其简单精悍,非常易学易用。

示例代码

代码如下:

import logging.config
import json
from flask import Flask
from flask import make_response, request

logging.config.fileConfig("logging.conf")
logger = logging.getLogger("filelogger")

app = Flask(__name__)

print("hello world")

@app.route("/test/info", methods=['GET'])
def testinfo():
    logger.info("test information in test block")

    keyword = request.args.get('key', '')

    resultJson = {}
    resultJson['msg'] = 'it is a great world'
    resultJson['status'] = 0
    resultJson['code'] = keyword

    jsonstr = json.dumps(resultJson)
    response = make_response(jsonstr)

    return response

if __name__ == "__main__":
    print("main...")
    app.run()

代码中的logging.conf是配置日志的路径、格式以及文件大小的,大家也可以直接去掉,将日志输出到控制台。

这里定义了一个Get请求,并以json的方式,返回结果信息。

main‘是在Python程序定义程序主入口的方法。

总结

这里的实例非常简单,复杂的例子大家可以自行上网参照其他内容。

猜你喜欢

转载自blog.csdn.net/blueheart20/article/details/81566120
今日推荐