简体   繁体   中英

How to save a JSON post request with a Flask server?

I have a simple web server built with Flask. The server listens for JSON post webhooks.

  @app.route('/webhook', methods=['POST'])
def webhook():
    if request.method == 'POST':

I need a way to save the incoming JSON data. I am not sure how to go about this. The data doesn't need to be put into tables or configured in anyway.

Use Python's logging facility. An example code below, used from Logging to a file and your snippet shared above.

import logging
from flask import Flask, request

logging.basicConfig(filename='requests.log', level=logging.DEBUG, format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')

app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def webhook():
    if request.method == 'POST':
        request_data = request.get_json()
        logging.info(request_data)

if __name__ == '__main__':
    logging.info("Running application with local development server!")
    app.run()

The above code will log your requests with timestamps to a file and append to the file every time a new request is made.

from flask import request, jsonify

def webhook():
    resp=''
    if request.method == 'POST':
        my_form_field = request.form['my_form_field']
        if my_form_field:
            resp = 'Form data received'`enter code here`
            return jsonify(resp = resp) #you may collect this response with JQuery
        else:
            resp = 'Form field is empty'
            return jsonify(resp = resp)```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM