测试1 传入python dict字典
1 sever服务端
目录结构
|---- /hello.py
|----/templates/
|----|-----------/index.html
hello.py
from flask import Flask,render_template,request
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/login",methods = ['GET', 'POST'])
def login():
if request.method == "POST":
username = request.form.get('username')
password = request.form.get('password')
if username=="zhangsan" and password=="123":
return "<h1>welcome, %s !</h1>" %username
else:
return "<h1>login Failure !</h1>"
else:
return "<h1>login Failure !</h1>"
if __name__ == '__main__':
app.run(debug=True)
index.html
<form action="/login" method="post">
username: <input type="text" name="username">
password: <input type="password" name="password">
<input type="submit" id="submit">
</form>
2 client客户端调用
#coding=utf-8
import requests
s = requests
data={"username":"zhangsan","password":"123",}
r = s.post('http://127.0.0.1:5000/login', data)
print r.status_code
print r.headers['content-type']
print r.encoding
print r.text
先启用服务端程序,然后可以利用客户端程序调用以及返回结果。
测试2 传入json字符串
1 server 端
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
from flask import Flask
from flask import request
from flask import redirect
from flask import jsonify
app = Flask(__name__)
@app.route('/' , methods=['GET', 'POST'])
def index():
if request.method == 'POST':
a = request.get_data()
dict1 = json.loads(a)
return json.dumps(dict1["data"])
else:
return '<h1>只接受post请求!</h1>'
@app.route('/user/<name>')
def user(name):
return'<h1>hello, %s</h1>' % name
if __name__ =='__main__':
app.run(port='5000')
2 client端
#coding=utf-8
import requests
import json
s = requests
#data={"username":"zhangsan","password":"123",}
data={ "opr": "add", "data": { "userName": "98997", "disc": "hudihiudhu", "expDate":"2", "ip": [ "10.10.11.1", "10.10.11.2", "10.10.11.3" ] } }
data = json.dumps(data)
r = s.post('http://127.0.0.1:5000/', data)
#r = s.post('http://127.0.0.1:5000/login', data)
print r.status_code
print r.headers['content-type']
print r.encoding
print r.text
参考:
http://blog.csdn.net/qq_20711445/article/details/51658498
http://docs.jinkan.org/docs/flask/quickstart.html
http://www.runoob.com/python/python-json.html