参考:https://blog.csdn.net/yelena_11/article/details/53404892

最简单的post例子:

  1. from flask import Flask, request
  2. app = Flask(__name__)
  3. @app.route('/')
  4. def hello_world():
  5. return 'hello world'
  6. if __name__ == '__main__':
  7. app.run()

然后在客户端client.py运行如下内容:

  1. import requests
  2. r = requests.post("http://127.0.0.1:5000")
  3. print (r.text)
  4. #返回welcome

简单的post例子:

以用户注册为例,向服务器/register传送用户名name和密码password,编写如下HelloWorld/index.py。

  1. from flask import Flask, request
  2. app = Flask(__name__)
  3. @app.route('/')
  4. def hello_world():
  5. return 'hello world'
  6. @app.route('/register', methods=['POST'])
  7. def register():
  8. print (request.headers)
  9. print (request.form)
  10. print (request.form['name'])
  11. print (request.form.get('name'))
  12. print (request.form.getlist('name'))
  13. print (request.form.get('nickname', default='little apple'))
  14. return 'welcome'
  15. if __name__ == '__main__':
  16. app.run()
  1. @app.route('/register', methods=['POST'])
  2. #表示url /register只接受POST方法,也可以修改method参数如下:
  3. @app.route('/register', methods=['GET', 'POST'])

客户端client.py内容如下:

  1. import requests
  2. user_info = {'name': 'letian', 'password': ''}
  3. r = requests.post("http://127.0.0.1:5000/register", data=user_info)
  4. print (r.text)

先运行HelloWorld/index.py,然后运行client.py,得到如下结果:

  1. welcome

运行完client.py之后相应的在编译器终端出现如下信息:

  1. 127.0.0.1 - - [23/Mar/2018 17:44:24] "POST /register HTTP/1.1" 200 -
  2. Host: 127.0.0.1:5000
  3. User-Agent: python-requests/2.18.4
  4. Accept-Encoding: gzip, deflate
  5. Accept: */*
  6. Connection: keep-alive
  7. Content-Length: 24
  8. Content-Type: application/x-www-form-urlencoded
  9.  
  10. ImmutableMultiDict([('name', 'letian'), ('password', '')])
  11. letian
  12. letian
  13. ['letian']
  14. little apple

以上部分的前6行是client.py生成的HTTP请求头,由 print (request.headers) 输出

相对应的,print (request.form) 的输出结果是:

  1. ImmutableMultiDict([('name', 'letian'), ('name', 'letian2'), ('password', '')])

这是一个 ImmutableMultiDict 对象。

其中,request.form['name'] 和 request.form.get['name'] 都可以获得name对应的值,对 request.form.get() 通过为参数default指定值作为默认值,上述程序中:

  1. print (request.form.get('nickname', default='little apple'))

输出:little apple

若name存在多个值,则通过 request.form.getlist('name') 返回一个列表,对client.py作相应的修改:

  1. import requests
  2. user_info = {'name': ['letian', 'letian2'], 'password': ''}
  3. r = requests.post("http://127.0.0.1:5000/register", data=user_info)
  4. print (r.text)

运行client.py,print (request.form.getlist('name'))则会对应的输出:

  1. ['letian', 'letian2']

上传文件

假设上传的文件只允许'png, jpg, jpeg, git' 四种格式,使用/upload格式上传,上传的结果放在服务器端的目录下。

首先在项目HelloWorld中创建目录。

werkzeug可以用来判断文件名是否安全,修改后的HelloWorld/index.py文件如下所示:

  1. from flask import Flask, request
  2. from werkzeug.utils import secure_filename
  3. import os
  4. app = Flask(__name__)
  5. app.config['UPLOAD_FOLDER'] = 'C:/Users/1/Desktop/3/' #设置需要放置的目录
  6. app.config['ALLOWED_EXTENSIONS'] = set(['png', 'jpg', 'jpeg', 'gif'])
  7. # For a given file, return whether it's an allowed type or not
  8. def allowed_file(filename):
  9. return '.' in filename and \
  10. filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
  11. @app.route('/')
  12. def hello_world():
  13. return 'hello world'
  14. @app.route('/upload', methods=['POST'])
  15. def upload():
  16. upload_file = request.files['image01']
  17. if upload_file and allowed_file(upload_file.filename):
  18. filename = secure_filename(upload_file.filename)
  19. upload_file.save(os.path.join(app.root_path, app.config['UPLOAD_FOLDER'], filename))
  20. return 'hello, '+request.form.get('name', 'little apple')+'. success'
  21. else:
  22. return 'hello, '+request.form.get('name', 'little apple')+'. failed'
  23. if __name__ == '__main__':
  24. 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:

  1. import requests
  2. files = {'image01': open('01.jpg', 'rb')}
  3. user_info = {'name': 'letian'}
  4. r = requests.post("http://127.0.0.1:5000/upload", data=user_info, files=files)
  5. print (r.text)

将当前目录下的01.jpg上传到服务器中,运行client.py,结果如下所示:

  1. hello, letian. success

处理JSON:

处理JSON文件的时候,需要把请求头和响应头的Content-Type设置为:application/json

修改HelloWorld/index.py:

  1. from flask import Flask, request, Response
  2. import json
  3. app = Flask(__name__)
  4. @app.route('/')
  5. def hello_world():
  6. return 'hello world'
  7. @app.route('/json', methods=['POST'])
  8. def my_json():
  9. print (request.headers)
  10. print (request.json)
  11. rt = {'info':'hello '+request.json['name']}
  12. return Response(json.dumps(rt), mimetype='application/json')
  13. if __name__ == '__main__':
  14. app.run()

修改client.py,并运行:

  1. import requests, json
  2. user_info = {'name': 'letian'}
  3. headers = {'content-type': 'application/json'}
  4. r = requests.post("http://127.0.0.1:5000/json", data=json.dumps(user_info), headers=headers)
  5. print (r.headers)
  6. print (r.json())

然后得到如下显示结果:

  1. {'Content-Type': 'application/json', 'Content-Length': '', 'Server': 'Werkzeug/0.12.2 Python/3.6.3', 'Date': 'Fri, 23 Mar 2018 16:13:29 GMT'}
  2. {'info': 'hello letian'}

相应在HelloWorld/index.py出现调试信息:

  1. Host: 127.0.0.1:5000
  2. User-Agent: python-requests/2.18.4
  3. Accept-Encoding: gzip, deflate
  4. Accept: */*
  5. Connection: keep-alive
  6. Content-Type: application/json
  7. Content-Length: 18

若需要响应头具有更好的可定制性,可以如下修改my_json()格式:

  1. @app.route('/json', methods=['POST'])
  2. def my_json():
  3. print (request.headers)
  4. print (request.json)
  5. rt = {'info':'hello '+request.json['name']}
  6. response = Response(json.dumps(rt), mimetype='application/json')
  7. response.headers.add('Server', 'python flask')
  8. return response

python实现Restful服务(基于flask)(2)的更多相关文章

  1. python实现Restful服务 (基于flask)(1)

    参考:https://www.jianshu.com/p/6ac1cab17929 参考:https://www.cnblogs.com/alexyuyu/p/6243362.html 参考:http ...

  2. [转]python实现RESTful服务(基于flask)

    python实现RESTful服务(基于flask) 原文: https://www.jianshu.com/p/6ac1cab17929  前言 上一篇文章讲到如何用java实现RESTful服务, ...

  3. python实现RESTful服务(基于flask)

    https://www.jianshu.com/p/6ac1cab17929 http://www.pythondoc.com/flask/quickstart.html 在java中调用python ...

  4. python之restful api(flask)获取数据

    需要用到谷歌浏览器的扩展程序 Advanced Rest Client进行模拟请求 1.直接上代码 from flask import Flask from flask import request ...

  5. 实战SpringCloud响应式微服务系列教程(第九章)使用Spring WebFlux构建响应式RESTful服务

    本文为实战SpringCloud响应式微服务系列教程第九章,讲解使用Spring WebFlux构建响应式RESTful服务.建议没有之前基础的童鞋,先看之前的章节,章节目录放在文末. 从本节开始我们 ...

  6. Python flask 基于 Flask 提供 RESTful Web 服务

    转载自 http://python.jobbole.com/87118/ 什么是 REST REST 全称是 Representational State Transfer,翻译成中文是『表现层状态转 ...

  7. XData -–无需开发、基于配置的数据库RESTful服务,可作为移动App和ExtJS、WPF/Silverlight、Ajax等应用的服务端

    XData -–无需开发.基于配置的数据库RESTful服务,可作为移动App和ExtJS.WPF/Silverlight.Ajax等应用的服务端   源起一个App项目,Web服务器就一台,已经装了 ...

  8. 基于SpringBoot开发一个Restful服务,实现增删改查功能

    前言 在去年的时候,在各种渠道中略微的了解了SpringBoot,在开发web项目的时候是如何的方便.快捷.但是当时并没有认真的去学习下,毕竟感觉自己在Struts和SpringMVC都用得不太熟练. ...

  9. 基于TypeScript装饰器定义Express RESTful 服务

    前言 本文主要讲解如何使用TypeScript装饰器定义Express路由.文中出现的代码经过简化不能直接运行,完整代码的请戳:https://github.com/WinfredWang/expre ...

随机推荐

  1. 通用 C# DLL 注入器injector(注入dll不限)

    为了方便那些不懂或者不想用C++的同志,我把C++的dll注入器源码转换成了C#的,这是一个很简单实用的注入器,用到了CreateRemoteThread,WriteProcessMemory ,Vi ...

  2. linux基本目录

    / 根目录: dev : 存放抽象硬件 ib : 存放系统库文件 sbin : 存放特权级二进制文件 var : 存放经常变化的文件 home : 普通用户目录 etc : 存放配置文件目录 /etc ...

  3. javascript处理json字符串

    字符串转JSON格式 var obj = JSON.parse(json字符串); 判断字段值是否存在,返回true或false obj.hasOwnProperty("error" ...

  4. Delphi XE2 之 FireMonkey 入门(23) - 数据绑定: TBindingsList: TBindExpression

    准备用 TBindingsList 重做上一个例子. 可以先把 TBindingsList 理解为是一组绑定表达式(TBindExpression)的集合;官方应该是提倡在设计时完成 TBindExp ...

  5. Delphi XE2 之 FireMonkey 入门(14) - 滤镜: 概览

    相关单元: FMX.Filter FMX.FilterCatBlur FMX.FilterCatGeometry FMX.FilterCatTransition FMX_FilterCatColor ...

  6. 2019了,给自己立一个flag吧

    新年伊始,元旦已过,虽然有迟了,但是,相对于整年来说,还是比较早.年度总结,年度规划,除过上交的报告以外,还得自己给自己立个flag,一次来督促自己,而不是为了别的.做这些事,不仅仅是为了能更好的工作 ...

  7. B-/B+树 MySQL索引结构

    索引 索引的简介 简单来说,索引是一种数据结构 其目的在于提高查询效率 可以简单理解为“排好序的快速查找结构” 一般来说,索引本身也很大,不可能全部存储在内存中,因此索引往往以索引文件的形式存储在中磁 ...

  8. Sentinel分布式系统的流量防卫兵

    Sentinel 是什么?官网:https://github.com/alibaba/Sentinel/wiki/介绍 随着微服务的流行,服务和服务之间的稳定性变得越来越重要.Sentinel 以流量 ...

  9. 大牛总结的 Git 使用技巧,写得太好了!

    作者:你喜欢吃青椒么 juejin.im/post/5d157bf3f265da1bcc1954e6 前言 本文是参考廖雪峰老师的Git资料再加上我自己对Git的理解,记录我的Git学习历程,作下此文 ...

  10. 洛谷 P2672 推销员(贪心,模拟)

    传送门 解题思路 第一种: 对于选i家,很显然,a值前i-1家的一定会选,所以只需要考虑最后一家的选法.要么是选择a值第i大的(就不管s了),要么选择剩下的中s最大的. 我们把每一家的情况(s和a)存 ...