首页 > 编程语言 > 详细

Python-基于flask的接口框架

时间:2021-07-05 15:36:43      阅读:22      评论:0      收藏:0      [点我收藏+]

Python-基于flask的接口框架

?Flask是一个Python编写的Web 微框架,让我们可以使用Python语言快速实现一个网站或Web服务。本文参考自Flask官方文档,大部分代码引用自官方文档。

安装flask

首先我们来安装Flask。最简单的办法就是使用pip。

pip install flask

然后打开一个Python文件,输入下面的内容并运行该文件。然后访问localhost:5000,我们应当可以看到浏览器上输出了hello world。

from flask import Flaskapp = Flask(__name__)?@app.route(‘/‘)def hello_world():    return ‘hello world‘?if __name__ == ‘__main__‘:    app.run(host=‘127.0.0.1‘,port=5000)

调试模式

我们修改代码中的输出,然后查看浏览器上是否有变化。如果你照做的话,可以看到什么变化都没有。其实Flask内置了调试模式,可以自动重载代码并显示调试信息。这需要我们开启调试模式,方法很简单,设置FLASK_DEBUG环境变量,并将值设置为1。或者设置app.debug=True

?

from flask import Flask?app = Flask(__name__)app.debug=True?@app.route(‘/‘)def hello_world():    return ‘Hello World!‘?@app.route(‘/login‘)def login():    return ‘Login‘??if __name__ == ‘__main__‘:    app.run()

?

然后再次运行程序,会看到有这样的输出。这时候如果再次修改代码,会发现这次Flask会自动重启。

* Restarting with stat
* Debugger is active!
* Debugger PIN: 157-063-180
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

路由

在上面的例子里可以看到路由的使用。如果了解Spring Web MVC的话,应该对路由很熟悉。路由通过使用Flask的app.route装饰器来设置,这类似Java的注解。

@app.route(‘/‘)def index():    return ‘Index Page‘?@app.route(‘/hello‘)def hello():    return ‘Hello, World‘

?

路径变量

如果希望获取/article/1这样的路径参数,就需要使用路径变量。路径变量的语法是/path/<converter:varname>。在路径变量前还可以使用可选的转换器,有以下几种转换器。

转换器 作用
string 默认选项,接受除了斜杠之外的字符串
int 接受整数
float 接受浮点数
path 和string类似,不过可以接受带斜杠的字符串
any 匹配任何一种转换器
uuid 接受UUID字符串

下面是Flask官方的例子。

?

@app.route(‘/user/<username>‘)def show_user_profile(username):    # show the user profile for that user    return ‘User %s‘ % username?@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

?

构造URL

在Web程序中常常需要获取某个页面的URL,在Flask中需要使用url_for(‘方法名‘)来构造对应方法的URL。下面是Flask官方的例子。

>>> from flask import Flask, url_for>>> app = Flask(__name__)>>> @app.route(‘/‘)... def index(): pass...>>> @app.route(‘/login‘)... def login(): pass...>>> @app.route(‘/user/<username>‘)... def profile(username): pass...>>> with app.test_request_context():...  print url_for(‘index‘)...  print url_for(‘login‘)...  print url_for(‘login‘, next=‘/‘)...  print url_for(‘profile‘, username=‘John Doe‘)...//login/login?next=//user/John%20Doe

HTTP方法

如果需要处理具体的HTTP方法,在Flask中也很容易,使用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()

日志输出

Flask 为我们预配置了一个 Logger,我们可以直接在程序中使用。这个Logger是一个标准的Python Logger,所以我们可以向标准Logger那样配置它,详情可以参考官方文档。

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

?

处理请求

在 Flask 中获取请求参数需要使用request等几个全局对象,但是这几个全局对象比较特殊,它们是?Context Locals?,其实就是 Web 上下文中局部变量的代理。虽然我们在程序中使用的是全局变量,但是对于每个请求作用域,它们都是互不相同的变量。理解了这一点,后面就非常简单了。

?

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)

?

如果数据是由GET方法传送过来的,可以使用args属性获取,这个属性也是一个字典。

searchword = request.args.get(‘key‘, ‘‘)

?

文件上传

利用Flask也可以方便的获取表单中上传的文件,只需要利用 request 的files属性即可,这也是一个字典,包含了被上传的文件。如果想获取上传的文件名,可以使用filename属性,不过需要注意这个属性可以被客户端更改,所以并不可靠。更好的办法是利用werkzeug提供的secure_filename方法来获取安全的文件名。

?

from flask import requestfrom werkzeug.utils import secure_filename?@app.route(‘/upload‘, methods=[‘GET‘, ‘POST‘])def upload_file():    if request.method == ‘POST‘:        f = request.files[‘the_file‘]        f.save(‘/var/www/uploads/‘ + secure_filename(f.filename))

写在最后

这篇文章主要参考了Flask的官方文档,但是只介绍了 Flask的最基本的一部分。了解了这部分,我们可以用Python 搭一个小服务器做点事情。如果希望详细了解 Flask的使用用法,请关注更详细的资料。

Python-基于flask的接口框架

原文:https://blog.51cto.com/u_15284226/2977877

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!