入门
入门网址:http://docs.jinkan.org/docs/flask/quickstart.html
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
访问 http://127.0.0.1:5000/ ,你会看见你好的问候。
- 允许外网进行访问
app.run(host='0.0.0.0')
搭建自己的api
第一版
- 功能说明
从url中解析出文字信息,并对文字信息进行加工处理,我这边是把文本进行一个实体识别和关系抽取。
# -*- coding: utf-8 -*-
# antuor:dxiaod
from flask import Flask, request
app = Flask(__name__)
@app.route('/',methods=['GET'])
def get_text_input():
text = request.args.get('inputstr')
print(text)
return text
if __name__ == "__main__":
app.run(host='0.0.0.0',debug=True)
访问http://0.0.0.0:5000/?inputstr=%E4%BD%A0%E5%A5%BD%E5%95%8A
可以见到你要的文字
第二版
- 功能说明
根据别人的文档定制化开发api
传参:一堆json样式的字符串
回参:一堆json样式的字符串 - 传参功能用bind_request_parmams
- 回参用Response
# -*- coding: utf-8 -*-
# antuor:dxiaod
from flask import Flask, request, Response
from flask_request_params import bind_request_params
import json
app = Flask(__name__)
app.before_request(bind_request_params)
@app.route('/projectname/name',methods=['GET'])
def get_text_input():
# text = request.args.get('inputstr')
text = request.params["askjson"]
action = request.params["action"]
jieguo = {"text":text}
print(text)
return Response(json.dumps(jieguo))
if __name__ == "__main__":
app.run(host='0.0.0.0',debug=True)
浏览器输入:
http://0.0.0.0:5000/projectname/name?action=query&askjson=nihaio
结果显示:
第三版
功能说明:
clent端访问server端,传这边的数据
需要用post进行传参
post传参需要用request.form获取内容
server端:
#-*- conding:utf-8 -*-
'''
验证post参数请求
'''
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.method)
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(debug=True)
client端
#-*- conding:utf-8 -*-
import requests
user_info = {'name': 'letian', 'password': '123'}
r = requests.post("http://127.0.0.1:5000/register", data=user_info)
print(r.text)
网友评论