参考:

最简单的post例子:

from flask importFlask, request
app= Flask(__name__)
@app.route('/')defhello_world():return 'hello world'
if __name__ == '__main__':
app.run()
然后在客户端client.py运行如下内容:
importrequests
r= requests.post("http://127.0.0.1:5000")print(r.text)#返回welcome
简单的post例子:
以用户注册为例,向服务器/register传送用户名name和密码password,编写如下HelloWorld/index.py。
from flask importFlask, request
app= Flask(__name__)
@app.route('/')defhello_world():return 'hello world'@app.route('/register', methods=['POST'])defregister():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内容如下:
importrequests
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:5000User-Agent: python-requests/2.18.4Accept-Encoding: gzip, deflate
Accept:*/*Connection: keep-alive
Content-Length: 24Content-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作相应的修改:
importrequests
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 importFlask, requestfrom werkzeug.utils importsecure_filenameimportos
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
defallowed_file(filename):return '.' in filename and\
filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
@app.route('/')defhello_world():return 'hello world'@app.route('/upload', methods=['POST'])defupload():
upload_file= request.files['image01']if upload_file andallowed_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:
importrequests
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 importFlask, request, Responseimportjson
app= Flask(__name__)
@app.route('/')defhello_world():return 'hello world'@app.route('/json', methods=['POST'])defmy_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,并运行:
importrequests, 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:5000User-Agent: python-requests/2.18.4Accept-Encoding: gzip, deflate
Accept:*/*Connection: keep-alive
Content-Type: application/json
Content-Length: 18
若需要响应头具有更好的可定制性,可以如下修改my_json()格式:
@app.route('/json', methods=['POST'])defmy_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