python——Web服务开发(一)Flask模块

flask的诞生于2010年的愚人节,本来它只是作者无意间写的一个小玩具,没想到它却悄悄流行起来了。漫长的8年时间,flask一直没有发布一个严肃的正式版本,但是却不能阻挡它成为即将被微软收购的亚洲最大同性交友网站github上最受好评的Python Web框架。

https://github.com/pallets/flask

现在flask终于发布了1.0正式版本,虽然也没什么卵用,不过还是可以赞一波的。


flask内核内置了两个最重要的组件,所有其它的组件都是通过易扩展的插件系统集成进来的。这两个内置的组件分别是werkzeug和jinja2。werkzeug是一个用于编写Python WSGI程序的工具包,它的结构设计和代码质量在开源社区广受褒扬,其源码被尊为Python技术领域最值得阅读的开源库之一。而jinja2是一个功能极为强大的模板系统,它完美支持unicode中文,每个模板都运行在安全的沙箱环境中,使用jinja2编写的模板代码非常优美。

安装flask就不多说了,pip了解一下。



路由:

路由通过使用Flask的app.route装饰器来设置。

@app.route('/')
def index():
    return 'Index Page'

@app.route('/hello')
def hello():
    return 'Hello, World'
HTTP方法:

使用route装饰器的methods参数设置。

from flask import request

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        do_the_login()
    else:
        show_the_login_form()

静态文件:

url_for('static', filename='style.css')

日志模块:

 app.Logger

app.logger.debug('A value for debugging')
app.logger.warning('A warning occurred (%d apples)', 42)
app.logger.error('An error occurred')

request对象:

Request 对象是一个全局对象,利用它的属性和方法,我们可以方便的获取从页面传递过来的参数。
method属性会返回HTTP方法的类似,例如post和get。form属性是一个字典,如果数据是POST类型的表单,就可以从form属性中获取。下面是 Flask 官方的例子,演示了 Request 对象的method和form属性。

from flask import request

@app.route('/login', methods=['POST', 'GET'])
def login():
    error = None
    if request.method == 'POST':
        if valid_login(request.form['username'],
                       request.form['password']):
            return log_the_user_in(request.form['username'])
        else:
            error = 'Invalid username/password'
    # the code below is executed if the request method
    # was GET or the credentials were invalid
    return render_template('login.html', error=error)
更多接口可以参考API文档 http://flask.pocoo.org/


我们先简单起一个小服务,返回输入的2倍:

import math
from flask import Flask, request

app = Flask(__name__)

@app.route("/double")
def double():
    # 默认参数
    a = int(request.args.get('a', '100'))
    return str(a*2)
    
if __name__ == '__main__':
    app.run()

web缓存:可以通过键值作为索引,下次可以直接从缓存中获取结果。

import math
import threading
from flask import Flask, request
from flask.json import jsonify

app = Flask(__name__)


class Cache(object):

    def __init__(self):
        self.pis = {}
        self.lock = threading.RLock()

    def set(self, input, output):
        with self.lock:
            self.pis[input] = output

    def get(self, input):
        with self.lock:
            return self.pis.get(input)

cache = Cache()

@app.route("/double")
def double():
    # 默认参数
    a = int(request.args.get('a', '100'))
    result = cache.get(a)
    if result:
        return jsonify({"cached": True, "result": result})
    result=a*2
    cache.set(a, result)
    return jsonify({"cached": False, "result": result})
    
if __name__ == '__main__':
    app.run()

第一次:


第二次:



猜你喜欢

转载自blog.csdn.net/sm9sun/article/details/80620251