1. 程式人生 > >一個flask處理get,post請求

一個flask處理get,post請求

一個簡單的flask處理get和post請求

# -*- coding: utf-8 -*-
import os
import json
from flask import Flask,render_template
from flask import request, jsonify
app = Flask(__name__)
curdir = os.path.dirname(os.path.realpath(__file__))

@app.route('/', methods=['GET','POST'])
def return_json():
    if request.method == "GET":
        save_path = os.path.join(curdir,"back_log",'back.txt')
        len = os.path.getsize(save_path)
        if len:
            with open(save_path,"r") as f:
                    code=json.load(f)
        else:
            code = {}
        #code.close()
        return jsonify({
                "status":1,
                "message":"success",
                "payload":code
                })
    elif request.method == "POST":
        try:
            form = request.form
            data = form.to_dict()
            back_log = os.path.join(curdir,"back_log")
            back_path = os.path.join(back_log,"back.txt")
            with open(back_path,"w") as f:
                json.dump(data,f)
            return jsonify({
                "status":1,
                "message":"success",
                "payload": form
                })
        except BaseException,e:
            print e
            return jsonify({
                "status":-1,
                "message":"success"
                })
                
if __name__ == '__main__':
    app.run(host='172.31.50.39' ,port=8000,debug=True)