3
5

More than 3 years have passed since last update.

PythonでいろいろPOSTしてFlaskで受け取る

Posted at

pythonでjsonとか画像とかPOSTしたくなってきたので, 全部まとめました。全部Flaskで受け取ってます。

まずは普通にdataをPOST

post.py
import requests
import json

post_url = "http://127.0.0.1:5000/callback"

#postしたいデータ
data = "wowwowwowwow"

#POST送信
response = requests.post(
                    post_url,
                    data = data
                    )

print(response.json())

server.py
from flask import *
import os
from PIL import Image
import json

app=Flask(__name__)

@app.route("/")
def hello():
    return "hello"

@app.route("/callback",methods=["POST"]) 
def callback():
    print(request.data.decode())
    return jsonify({"kekka": "受け取ったよ!"})

if __name__=="__main__":
    port=int(os.getenv("PORT",5000))
    app.debug=True
    app.run()

JSON形式でPOST

post.py
import requests
import json

post_url = "http://127.0.0.1:5000/callback"

json = {"data": "ウオオオオお"}

#POST送信
response = requests.post(
                    post_url,
                    json = json,
                    )

print(response.json())

server.py
from flask import *
import os
from PIL import Image
import json

app=Flask(__name__)

@app.route("/")
def hello():
    return "hello"

@app.route("/callback",methods=["POST"]) 
def callback():
    data = request.data.decode('utf-8')#デコード
    data = json.loads(data)
    print(data["data"])
    return jsonify({"kekka": "受け取ったよ!"})

if __name__=="__main__":
    port=int(os.getenv("PORT",5000))
    app.debug=True
    app.run()

画像をPOST

post.py
import requests
import json

post_url = "http://127.0.0.1:5000/callback"

#POSTするファイルの読込
files = { "image_file": open('./sample.jpg', 'rb') }

#POST送信
response = requests.post(
                    post_url,
                    files = files,
                    )

print(response.json())
server.py
from flask import *
import os
from PIL import Image
import json

app=Flask(__name__)

@app.route("/")
def hello():
    return "hello"

@app.route("/callback",methods=["POST"]) 
def callback():
    #画像の読み込み
    im = Image.open(request.files["image_file"])

    #表示
    im.show()

    return jsonify({"kekka": "受け取ったよ!"})

if __name__=="__main__":
    port=int(os.getenv("PORT",5000))
    app.debug=True
    app.run()

感想

これであなたもPOSTマスター。

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5