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 ...
随机推荐
- 永久关闭Linux的防火墙
重启网络服务,加载网卡配置文件systemctl restart network 清空防火墙规则iptables -F 关闭selinux防火墙vi /etc/selinux/config修改如下配置 ...
- 阶段1 语言基础+高级_1-3-Java语言高级_06-File类与IO流_05 IO字符流_7_字符输出流的续写和换行
追加写就是后面参数设置为true 加入换行符
- python修改文件
文档username.txt 将文件中密码123456改成67890: 方法一:(简单粗暴) 1.打开文件 2.读出数据 3.修改数据 4.清空原来文件,将新的内容写进去 f = open('user ...
- 打印流PrintWriter
* 打印流 * 字节流打印流 PrintStream * 字符流打印流PrintWriter * * 打印流的特点: * A:只有写数据的,没有读取数据,只能操作目的地,不能操作数据源 * * B:可 ...
- 【MM系列】SAP MM模块-移动类型全部列表
公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[MM系列]SAP MM模块-移动类型全部列表 ...
- LeetCode 94. Binary Tree Inorder Traversal 动态演示
非递归的中序遍历,要用到一个stack class Solution { public: vector<int> inorderTraversal(TreeNode* root) { ve ...
- mooc-IDEA 收藏位置和文件--003
六.IntelliJ IDEA -收藏位置和文件(类/函数) 1.收藏自己喜欢的文件---代码 添加一个Favorites列表 定义名称 Help->Find Action... 选择Add t ...
- new Date() 对象及方法:
在别人的代码中见了两回 new Date().toLocaleString(),查了才知道,toLocaleString()是 根据本地时间格式,把 Date 对象转换为字符串.于是好奇new Dat ...
- 虚拟机 vs 容器
虚拟机 虚拟机本质上是模拟,模拟物理机上的硬件 虚拟机必须安装操作系统 一个虚拟机操作系统的崩溃不会影响到其他虚拟机 容器 容器的本质是经过隔离与限制的linux进程 容器使用的是物理机的资源 容器之 ...
- 极*Java速成教程 - (3)
Java语言基础 访问权限控制 Java是一个面向对象的语言,当你不是它所设计的要面向的对象时,它就不会给你看你不该看到的东西,也就是"访问权限控制". 亲疏有别,才能权限控制 包 ...