python实现Restful服务(基于flask)(2)
参考:https://blog.csdn.net/yelena_11/article/details/53404892
最简单的post例子:
- from flask import Flask, request
- app = Flask(__name__)
- @app.route('/')
- def hello_world():
- return 'hello world'
- if __name__ == '__main__':
- app.run()
然后在客户端client.py运行如下内容:
- import requests
- r = requests.post("http://127.0.0.1:5000")
- print (r.text)
- #返回welcome
简单的post例子:
以用户注册为例,向服务器/register传送用户名name和密码password,编写如下HelloWorld/index.py。
- from flask import Flask, request
- app = Flask(__name__)
- @app.route('/')
- def hello_world():
- return 'hello world'
- @app.route('/register', methods=['POST'])
- def register():
- print (request.headers)
- print (request.form)
- print (request.form['name'])
- print (request.form.get('name'))
- print (request.form.getlist('name'))
- print (request.form.get('nickname', default='little apple'))
- return 'welcome'
- if __name__ == '__main__':
- app.run()
- @app.route('/register', methods=['POST'])
- #表示url /register只接受POST方法,也可以修改method参数如下:
- @app.route('/register', methods=['GET', 'POST'])
客户端client.py内容如下:
- import requests
- user_info = {'name': 'letian', 'password': ''}
- r = requests.post("http://127.0.0.1:5000/register", data=user_info)
- print (r.text)
先运行HelloWorld/index.py,然后运行client.py,得到如下结果:
- welcome
运行完client.py之后相应的在编译器终端出现如下信息:
- 127.0.0.1 - - [23/Mar/2018 17:44:24] "POST /register HTTP/1.1" 200 -
- Host: 127.0.0.1:5000
- User-Agent: python-requests/2.18.4
- Accept-Encoding: gzip, deflate
- Accept: */*
- Connection: keep-alive
- Content-Length: 24
- Content-Type: application/x-www-form-urlencoded
- ImmutableMultiDict([('name', 'letian'), ('password', '')])
- letian
- letian
- ['letian']
- little apple
以上部分的前6行是client.py生成的HTTP请求头,由 print (request.headers) 输出
相对应的,print (request.form) 的输出结果是:
- ImmutableMultiDict([('name', 'letian'), ('name', 'letian2'), ('password', '')])
这是一个 ImmutableMultiDict 对象。
其中,request.form['name'] 和 request.form.get['name'] 都可以获得name对应的值,对 request.form.get() 通过为参数default指定值作为默认值,上述程序中:
- print (request.form.get('nickname', default='little apple'))
输出:little apple
若name存在多个值,则通过 request.form.getlist('name') 返回一个列表,对client.py作相应的修改:
- import requests
- user_info = {'name': ['letian', 'letian2'], 'password': ''}
- r = requests.post("http://127.0.0.1:5000/register", data=user_info)
- print (r.text)
运行client.py,print (request.form.getlist('name'))则会对应的输出:
- ['letian', 'letian2']
上传文件:
假设上传的文件只允许'png, jpg, jpeg, git' 四种格式,使用/upload格式上传,上传的结果放在服务器端的目录下。
首先在项目HelloWorld中创建目录。
werkzeug可以用来判断文件名是否安全,修改后的HelloWorld/index.py文件如下所示:
- from flask import Flask, request
- from werkzeug.utils import secure_filename
- import os
- app = Flask(__name__)
- app.config['UPLOAD_FOLDER'] = 'C:/Users/1/Desktop/3/' #设置需要放置的目录
- app.config['ALLOWED_EXTENSIONS'] = set(['png', 'jpg', 'jpeg', 'gif'])
- # For a given file, return whether it's an allowed type or not
- def allowed_file(filename):
- return '.' in filename and \
- filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
- @app.route('/')
- def hello_world():
- return 'hello world'
- @app.route('/upload', methods=['POST'])
- def upload():
- upload_file = request.files['image01']
- if upload_file and allowed_file(upload_file.filename):
- filename = secure_filename(upload_file.filename)
- upload_file.save(os.path.join(app.root_path, app.config['UPLOAD_FOLDER'], filename))
- return 'hello, '+request.form.get('name', 'little apple')+'. success'
- else:
- return 'hello, '+request.form.get('name', 'little apple')+'. failed'
- if __name__ == '__main__':
- app.run()
app.config中的config是字典的子类,可以用来设置自有的配置信息,也可以用来设置自己的配置信息。函数allowed_file(filename)用来判断filename是否有后缀以及后缀是否在app.config['ALLOWED_EXTENSIONS']中。
客户端上传的图片必须以image01标识,upload_file是上传文件对应的对象,app.root_path获取index.py所在目录在文件系统的绝对路径,upload_file.save(path)用来将upload_file保存在服务器的文件系统中,参数最好是绝对路径。os.path.join()用于将使用合适的分隔符将路径组合起来。然后定制客户端client.py:
- import requests
- files = {'image01': open('01.jpg', 'rb')}
- user_info = {'name': 'letian'}
- r = requests.post("http://127.0.0.1:5000/upload", data=user_info, files=files)
- print (r.text)
将当前目录下的01.jpg上传到服务器中,运行client.py,结果如下所示:
- hello, letian. success
处理JSON:
处理JSON文件的时候,需要把请求头和响应头的Content-Type设置为:application/json
修改HelloWorld/index.py:
- from flask import Flask, request, Response
- import json
- app = Flask(__name__)
- @app.route('/')
- def hello_world():
- return 'hello world'
- @app.route('/json', methods=['POST'])
- def my_json():
- print (request.headers)
- print (request.json)
- rt = {'info':'hello '+request.json['name']}
- return Response(json.dumps(rt), mimetype='application/json')
- if __name__ == '__main__':
- app.run()
修改client.py,并运行:
- import requests, json
- user_info = {'name': 'letian'}
- headers = {'content-type': 'application/json'}
- r = requests.post("http://127.0.0.1:5000/json", data=json.dumps(user_info), headers=headers)
- print (r.headers)
- print (r.json())
然后得到如下显示结果:
- {'Content-Type': 'application/json', 'Content-Length': '', 'Server': 'Werkzeug/0.12.2 Python/3.6.3', 'Date': 'Fri, 23 Mar 2018 16:13:29 GMT'}
- {'info': 'hello letian'}
相应在HelloWorld/index.py出现调试信息:
- Host: 127.0.0.1:5000
- User-Agent: python-requests/2.18.4
- Accept-Encoding: gzip, deflate
- Accept: */*
- Connection: keep-alive
- Content-Type: application/json
- Content-Length: 18
若需要响应头具有更好的可定制性,可以如下修改my_json()格式:
- @app.route('/json', methods=['POST'])
- def my_json():
- print (request.headers)
- print (request.json)
- rt = {'info':'hello '+request.json['name']}
- response = Response(json.dumps(rt), mimetype='application/json')
- response.headers.add('Server', 'python flask')
- return response
python实现Restful服务(基于flask)(2)的更多相关文章
- python实现Restful服务 (基于flask)(1)
参考:https://www.jianshu.com/p/6ac1cab17929 参考:https://www.cnblogs.com/alexyuyu/p/6243362.html 参考:http ...
- [转]python实现RESTful服务(基于flask)
python实现RESTful服务(基于flask) 原文: https://www.jianshu.com/p/6ac1cab17929 前言 上一篇文章讲到如何用java实现RESTful服务, ...
- python实现RESTful服务(基于flask)
https://www.jianshu.com/p/6ac1cab17929 http://www.pythondoc.com/flask/quickstart.html 在java中调用python ...
- python之restful api(flask)获取数据
需要用到谷歌浏览器的扩展程序 Advanced Rest Client进行模拟请求 1.直接上代码 from flask import Flask from flask import request ...
- 实战SpringCloud响应式微服务系列教程(第九章)使用Spring WebFlux构建响应式RESTful服务
本文为实战SpringCloud响应式微服务系列教程第九章,讲解使用Spring WebFlux构建响应式RESTful服务.建议没有之前基础的童鞋,先看之前的章节,章节目录放在文末. 从本节开始我们 ...
- Python flask 基于 Flask 提供 RESTful Web 服务
转载自 http://python.jobbole.com/87118/ 什么是 REST REST 全称是 Representational State Transfer,翻译成中文是『表现层状态转 ...
- XData -–无需开发、基于配置的数据库RESTful服务,可作为移动App和ExtJS、WPF/Silverlight、Ajax等应用的服务端
XData -–无需开发.基于配置的数据库RESTful服务,可作为移动App和ExtJS.WPF/Silverlight.Ajax等应用的服务端 源起一个App项目,Web服务器就一台,已经装了 ...
- 基于SpringBoot开发一个Restful服务,实现增删改查功能
前言 在去年的时候,在各种渠道中略微的了解了SpringBoot,在开发web项目的时候是如何的方便.快捷.但是当时并没有认真的去学习下,毕竟感觉自己在Struts和SpringMVC都用得不太熟练. ...
- 基于TypeScript装饰器定义Express RESTful 服务
前言 本文主要讲解如何使用TypeScript装饰器定义Express路由.文中出现的代码经过简化不能直接运行,完整代码的请戳:https://github.com/WinfredWang/expre ...
随机推荐
- 通用 C# DLL 注入器injector(注入dll不限)
为了方便那些不懂或者不想用C++的同志,我把C++的dll注入器源码转换成了C#的,这是一个很简单实用的注入器,用到了CreateRemoteThread,WriteProcessMemory ,Vi ...
- linux基本目录
/ 根目录: dev : 存放抽象硬件 ib : 存放系统库文件 sbin : 存放特权级二进制文件 var : 存放经常变化的文件 home : 普通用户目录 etc : 存放配置文件目录 /etc ...
- javascript处理json字符串
字符串转JSON格式 var obj = JSON.parse(json字符串); 判断字段值是否存在,返回true或false obj.hasOwnProperty("error" ...
- Delphi XE2 之 FireMonkey 入门(23) - 数据绑定: TBindingsList: TBindExpression
准备用 TBindingsList 重做上一个例子. 可以先把 TBindingsList 理解为是一组绑定表达式(TBindExpression)的集合;官方应该是提倡在设计时完成 TBindExp ...
- Delphi XE2 之 FireMonkey 入门(14) - 滤镜: 概览
相关单元: FMX.Filter FMX.FilterCatBlur FMX.FilterCatGeometry FMX.FilterCatTransition FMX_FilterCatColor ...
- 2019了,给自己立一个flag吧
新年伊始,元旦已过,虽然有迟了,但是,相对于整年来说,还是比较早.年度总结,年度规划,除过上交的报告以外,还得自己给自己立个flag,一次来督促自己,而不是为了别的.做这些事,不仅仅是为了能更好的工作 ...
- B-/B+树 MySQL索引结构
索引 索引的简介 简单来说,索引是一种数据结构 其目的在于提高查询效率 可以简单理解为“排好序的快速查找结构” 一般来说,索引本身也很大,不可能全部存储在内存中,因此索引往往以索引文件的形式存储在中磁 ...
- Sentinel分布式系统的流量防卫兵
Sentinel 是什么?官网:https://github.com/alibaba/Sentinel/wiki/介绍 随着微服务的流行,服务和服务之间的稳定性变得越来越重要.Sentinel 以流量 ...
- 大牛总结的 Git 使用技巧,写得太好了!
作者:你喜欢吃青椒么 juejin.im/post/5d157bf3f265da1bcc1954e6 前言 本文是参考廖雪峰老师的Git资料再加上我自己对Git的理解,记录我的Git学习历程,作下此文 ...
- 洛谷 P2672 推销员(贪心,模拟)
传送门 解题思路 第一种: 对于选i家,很显然,a值前i-1家的一定会选,所以只需要考虑最后一家的选法.要么是选择a值第i大的(就不管s了),要么选择剩下的中s最大的. 我们把每一家的情况(s和a)存 ...