[PYTHON] GET / POST communication by Flask (also about CORS support)

Overview

Since the content of POST communication in Flask was ambiguous, both GET / POST communication are summarized here. As the contents, there are "communication by form" / "communication by Json format". If you search for "Flask POST", the information will be messed up. By the way, it's Python 3.7.

GET communication

from flask import Flask, request, jsonfy
app = Flask(__name__)

@app.route("/", methods=["POST"])
def test():
    data = request.args.get('hoge', '') # ?hoge=Get the value of value
    return data #Return as is for sample

POST communication

Communication in Json format

from flask import Flask, request, jsonfy
import json
app = Flask(__name__)

@app.route("/", methods=["POST"])
def test():
    data = json.loads(request.data.decode('utf-8')) # request.utf data-Decode to 8 and make it a dictionary type in json library
    return jsonfy(data) #Return as is for sample

It seems that you can do the following, but I haven't tried it yet.

from flask import Flask, request, jsonfy
import json
app = Flask(__name__)

@app.route("/", methods=["POST"])
def test():
    data = json.loads(request.get_data())
    return jsonfy(data) #Return as is for sample

Communication by form

from flask import Flask, request, jsonfy
app = Flask(__name__)

@app.route("/", methods=["POST"])
def test():
    data = request.form["hoge"] #The "" that exists in the form"hoge"Get the value of the key
    return jsonfy(data) #Return as is for sample

About CORS (Cross-Origin Resource Sharing) support

This time's content is not particularly relevant, but next I will explain CORS support. I'm a web engineer, so I don't know the details, but in a nutshell, it seems to be a rule for using another server resource (in a little more detail, is the URL base the same? I wonder if they are the same).

For the time being, install "flask-cors" with pip.

pip install flask-cors

The rest is as follows.

from flask import Flask
from flask_cors import CORS #With this
app = Flask(__name__)
CORS(app) #this

reference

--Flask Quick Start: https://a2c.bitbucket.io/flask/quickstart.html --1 What to do if you call Flask API from Angular and get angry with No'Access-Control-Allow-Origin ...: [https://qiita.com/mitch0807/items/cd18e8fc15bb12416f3d](https: // qiita.com/mitch0807/items/cd18e8fc15bb12416f3d) --How to use JSON POST in python: https://qiita.com/naoko_s/items/04d68998cfdbe9c1b5f2

Recommended Posts

GET / POST communication by Flask (also about CORS support)
* Android * [HTTP communication_2] HTTP communication with Flask (hit WebAPI [GET, POST])
Get, post communication memo in Python
Get parameter and Post body, enable CORS in Flask (Python) and Express (Node.js)
(For myself) Flask_3 (form, POST and GET)