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': '123'}
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', '123')])
letian
letian
['letian']
little apple

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

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

ImmutableMultiDict([('name', 'letian'), ('name', 'letian2'), ('password', '123')])

这是一个 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': '123'}  
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': '24', '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

 

posted @ 2018-03-23 17:24  小丑_jk  阅读(498)  评论(0编辑  收藏  举报