pythonflaskflask-restful

How do I actually get the data after a request, with two Flask servers communicating with each other?


I recently started to learn how to use Flask and I was trying to send data from a server to another one.

In my PC I set up a folder with some json files and I want to send data from one folder in a specific container to another one. Here's the first server:

from flask import Flask, json, request
import os.path

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def docu_test():
    if request.method == 'POST':
        sOper = int(request.form['test'])
    if sOper == 1:
        with open('data/document.json', mode='r') as f:
            document:dict = json.load(f)
            return document
#I know that passing a dictionary is not practical, 
#but practicality is not the point of the exercise
#I'm just trying to pass the dict to understand how sending data works
        else:
            raise Exception("Error")

if __name__ == '__main__'and\
os.path.exists('data/document.json'):
    app.run(host="127.0.0.1", port=1240)

And here's the other server:

from flask import Flask, json
import requests

api = Flask(__name__)

@api.route('/', methods=['GET'])
def testing():
    response = requests.post("http://127.0.0.1:1240", data={'test':1})
    pass 

if __name__ == '__main__':
    api.run(host="127.0.0.1", port=2480)

Where I wrote "pass" is where I really don't know what should I do. I want to pass "document.json" from one server to another, but I don't know how to receive that data. What's missing?


Solution

  • JSON is, among other options, a format for data.

    In your example, you send data as a form (application/x-www-form-urlencoded) and want to receive data in JSON format. For the sake of consistency, I recommend that if you want to receive data in JSON format, you also send it in that format.

    Given your requirements, you have several options for sending data in JSON format:

    When querying, you send a request with suitable headers and the data converted to JSON. The response is then read and parsed into a dictionary. If an error occurs during the query, an exception is thrown.

    Here is an example with one server and several endpoints that covers the options described above.

    from flask import (
        Flask, 
        abort, 
        jsonify, 
        request, 
        send_from_directory
    )
    import json, os, requests
    
    app = Flask(__name__)
    
    @app.post('/')
    def index():
        op = request.json.get('test', 0)
        match int(op): 
            case 1: 
                # Send loaded dictionary in JSON format.
                with open(os.path.join(app.root_path, 'data', 'document.json')) as f:
                    data = json.load(f)
                    return jsonify(data)
            case 2: 
                # Send complete JSON file as file.
                return send_from_directory(
                    os.path.join(app.root_path, 'data'), 
                    'document.json'
                )
            case _:
                abort(422)
    
    # Get data in JSON format from another URL.
    @app.route('/retrieve')
    def retrieve():
        url = 'http://127.0.0.1:5000/'
    
        # Get data as a JSON formatted dictionary.
        # data = { 'test': 1 }
        
        # Get data as a JSON file.
        data = { 'test': 2 }
    
        headers = { 'Content-Type': 'application/json' }
        response = requests.post(url, data=json.dumps(data), headers=headers)
        response.raise_for_status()
        data = response.json()
    
        return data