Flask框架-常用Method JSON数据获取方式

一、Post JSON数据获取方式

提交任务:
curl -i -H "Content-Type: application/json" -X POST -d ‘{"appIds": [ {"appid": "1076877374"}, {"appid": "1108288808"} ], "language": "cn", "EmailAddress": "", "ClusterNum": 2, "WordNum": 2, "EmailMessage": true, "ShowOnWebPage": true}‘ http://182.254.247.157:5000/ana
from flask import Flask, jsonify, request, abort
import json
app = Flask(__name__)


@app.route(‘/ana‘, methods=[‘GET‘, ‘POST‘])
def call_analysis():
    print "Hello, World!"
    # if not request.json:(NO)
    #   abort(400)
    #
    # # data = request.get_json[‘appIds‘] (NO)

可用方式一:
    data = request.data   ----获取的是字符串

可用方式二:
    data = request.get_data()  ----获取的是字符串

(方式一和方式二得到的是原始提交的数据)
    j_data =  json.loads(data) -----load将字符串解析成json

    print "j_data", j_data[‘language‘] 

    return jsonify(task_j)
    # return jsonify({‘task‘: runAnalysis(data)}), 201



json模块编码: json.dumps()
json模块解码:解码python json格式,用json.loads()

二、Post 或者 Get请求参数

  • 目录结构
app
|----static(空)
|----templates(空)
|----flaskapp.py
  • flaskapp.py
# -*- coding: utf-8 -*-  
from flask import Flask  
from flask import request  
from flask import make_response,Response  
  
import json  
  
app = Flask(__name__)  
 
 
@app.route(‘/‘)  
def hello_world():  
    return ‘hello world‘  
  
def Response_headers(content):  
    resp = Response(content)  
    resp.headers[‘Access-Control-Allow-Origin‘] = ‘*‘  
    return resp  
 
@app.route(‘/test‘, methods=[‘POST‘])  
def test():  
    if request.method == ‘POST‘ and request.form.get(‘aaa‘):  
        # POST:
        # request.form获得所有post参数放在一个类似dict类中,to_dict()是字典化
        # 单个参数可以通过request.form.to_dict().get("xxx","")获得
        # ----------------------------------------------------
        # GET:
        # request.args获得所有get参数放在一个类似dict类中,to_dict()是字典化
        # 单个参数可以通过request.args.to_dict().get(‘xxx‘,"")获得
        datax = request.form.to_dict()
        content = str(datax)  
        resp = Response_headers(content)  
        return resp  
    else:  
        content = json.dumps({"error_code":"1001"})  
        resp = Response_headers(content)  
        return resp  
 
 
@app.errorhandler(403)  
def page_not_found(error):  
    content = json.dumps({"error_code": "403"})  
    resp = Response_headers(content)  
    return resp  
 
@app.errorhandler(404)  
def page_not_found(error):  
    content = json.dumps({"error_code": "404"})  
    resp = Response_headers(content)  
    return resp  
 
@app.errorhandler(400)  
def page_not_found(error):  
    content = json.dumps({"error_code": "400"})  
    # resp = Response(content)  
    # resp.headers[‘Access-Control-Allow-Origin‘] = ‘*‘  
    resp = Response_headers(content)  
    return resp  
    # return "error_code:400"  
 
@app.errorhandler(410)  
def page_not_found(error):  
    content = json.dumps({"error_code": "410"})  
    resp = Response_headers(content)  
    return resp  
 
@app.errorhandler(500)  
def page_not_found(error):  
    content = json.dumps({"error_code": "500"})  
    resp = Response_headers(content)  
    return resp  
  
if __name__ == ‘__main__‘:  
    app.run(debug=True,threaded=True) 

三、写一个server来接收数据,请求方式为post,传输方式为https

  • 相关flask接收文件代码
import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename
from werkzeug.serving import run_simple

UPLOAD_FOLDER = ‘/path/to/the/uploads‘
ALLOWED_EXTENSIONS = set([‘txt‘, ‘pdf‘, ‘png‘, ‘jpg‘, ‘jpeg‘, ‘gif‘])

app = Flask(__name__)
app.config[‘UPLOAD_FOLDER‘] = UPLOAD_FOLDER

def allowed_file(filename):
    return ‘.‘ in filename and            filename.rsplit(‘.‘, 1)[1] in ALLOWED_EXTENSIONS

@app.route(‘/‘, methods=[‘GET‘, ‘POST‘])
def upload_file():
    if request.method == ‘POST‘:
        file = request.files[‘file‘]
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config[‘UPLOAD_FOLDER‘], filename))
            return redirect(url_for(‘uploaded_file‘,
                                    filename=filename))
    return ‘‘‘
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form action="" method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>
    ‘‘‘

if __name__ == ‘__main__‘:
    run_simple(‘yourIP‘,port,app)
  • 此时传输方式为http,要将其改成https,则需要将最后一行改为
run_simple(‘yourIP‘,port,app,ssl_context(‘/way/to/.crt‘,‘/way/to/.key‘))
  • 此时就可以运行啦~~
  • 直接登录网页或者用curl命令可以进行测试

  • 关于flask写html接收文件数据的代码:
import os
from flask import Flask,request,redirect,url_for,send_from_directory
from werkzeug.serving import run_simple
from werkzeug import secure_filename
import time

UPLOAD_FOLDER = ‘/path/to/the/uploads‘

app = Flask(__name__)
app.config[‘UPLOAD_FOLDER‘] = UPLOAD_FOLDER

@app.route(‘/‘,methods=[‘GET‘,‘POST‘])
def upload_file():
        if request.method == ‘POST‘:
                content = request.data
                filename = time.time()
                with open(str(filename)+".json","w") as f:
                        f.write(content)
                        f.close()
                return "success!"
        return ‘‘‘
        <!doctype html>
        <title>Info</title>
        <h1>server is running</hi>
        ‘‘‘

if __name__ == ‘__main__‘:
        run_simple(‘yourIP‘,port,app
,ssl_context=(‘/way/to/.crt‘,‘/way/to/.key‘)
)
  • 此时登录网页可以查看服务器是否在运行,用curl测试发送数据
curl -d "@example.json" https://yourIP:port -k

Flask框架-常用Method JSON数据获取方式

上一篇:发布订阅模式(NodeJs版)


下一篇:启动Flume报地址已存在错误解决方案