[PYTHON] When you want to send an object with requests using flask

Overview

** Set up a server with the python ** web framework ** flask ** and point to the ** set up endpoint with some object ** (for example, a string, a list, an object of your own class) * A story when you want to send * **.

I think I often forget it every time, so I will summarize it here.

Conclusion for busy people

** Sender ** is

  1. Make what you want to send into a character string
  2. Put it in a dictionary
  3. json.dumps()

I think it's easiest (for me) to send it.

The ** receiver ** receives the data and does the work done by the sender in reverse.

  1. Receive data with `` `request.data```
  2. Use `json.loads ()` to return from the string to the dictionary.
  3. Extract the value from the dictionary.
  4. Return the value to its original type.

How to do

The flow is like this. An overview. I often use the method of finally turning the object into a string, putting that string in a dict, json.dumps, and then sending it.

Sender.py



〜〜〜〜
What you want to send= something

case1 isinstance(What you want to send,Some class object): ## もしWhat you want to sendがオブジェクトのとき
if you want to send can be binalized: ##If the object can be binary
        'pickle.dumps()Binary the object with(byte)Let's.'
        my_binary = pickle.dumps(What you want to send)
        GO_TO case2

    else: ##If the object cannot be binary
        'Make it binary in some way, or in the case of your own class object,
You need to write a serialize function. For example, a function that writes all the member variables of a class to a dictionary. For example, to_dict()Implement the function.'
        my_binary =What you want to send.to_dict()
        GO_TO case4

case2 isinstance(What you want to send, byte): ## もしWhat you want to sendがbyteのとき
    'Base64 what you want to send.b64encode()Let's make it a character string with.'
    my_str = base64.b64encode(What you want to send)
    GO_TO case3

case3 isinstance(What you want to send, str): ## もしWhat you want to sendがstr(文字列)のとき
    'Let's put it in the dictionary.'
    my_dict = {"my_object":What you want to send}
    GO_TO case4


case4 isinstance(What you want to send, dict): ## もしWhat you want to sendがすでにdictのとき
    'What you want to send json.dumps()Then you're ready to go.'
What you want to send= json.dumps(What you want to send)
    EXIT_CASE



assert type(What you want to send) =String(str), 'Please go back to the beginning.'

## print(What you want to send)
## >>> '{"my_object": my_value}'

requests.post(url="<Destination endpoint>",What you want to send,
                  headers={'Content-Type': 'application/json'})

Recipient.py



〜〜〜〜
@app.route('/receive')
def receive():
    data = request.data ##"What you want to send" sent by post is request.You can receive it with data.
    data = json.loads(data)['my_object'] ##First json.Return to the dictionary with loads,
##key is my_value of object(What was sent in the form of a string)To receive.

if data binary(byte)When you want to return to: 
        'base64 data.b64decode()Let's decode to byte with.'
        data2 = base64.b64decode(data)
        
When you want to return elif data to a class object:
if pickle.When you can return with loads:
            data3 = pickle.loads(data2)
else If pickle cannot be used with an object of your own class:
            'Deserialization function by itself, dict_to_obj()Let's implement a function like this and revert to the original class object'
            data3 = dict_to_obj(data2)


Summary

This time, I summarized how to post an object to the endpoint set up in flask.

This time around here.

end.

Recommended Posts

When you want to send an object with requests using flask
When you want to use it as it is when using it with lambda memo
Python Note: When you want to know the attributes of an object
Settings when you want to run python-mecab with travis
Personal best practice template to use when you want to make MVP with Flask
When you want to filter with Django REST framework
Solution when you want to use cv_bridge with python3 (virtualenv)
[AWS] What to do when you want to pip with Lambda
Use aggdraw when you want to draw beautifully with pillow
When you want to register Django's initial data with relationships
When you want to adjust the axis scale interval with APLpy
Send CSS compressed to Gzip with Flask
What to do if you couldn't send an email to Yahoo with Python.
Gist repository to use when you want to try a little with ansible
When you want to replace a column with a missing value (NaN) column by column
Memorandum of means when you want to make machine learning with 50 images
Send an email to Spushi's address with python
When you want to update the chrome driver.
How to deal with SessionNotCreatedException when using Selenium
I tried to detect an object with M2Det!
Send msgpack with ajax to flask (werkzeug) environment
What are you using when testing with Python?
How to build an environment when you want to use python2.7 after installing Anaconda3
I want to send Gmail with Python, but I can't because of an error
[OpenCV] When you want to check if it is read properly with imread
What to do if you get an error when installing python with pyenv
To automatically send an email with an attachment using the Gmail API in Python
What to do if you get an OpenSSL error when installing Python 2 with pyenv
I want to transition with a button in flask
Try to make RESTful API with MVC using Flask 1.0.2
[Python] You can save an object to a file by using the pickle module.
Links to do what you want with Sublime Text
When the variable you want to superscript with matplotlib is two or more characters
Things to do when you start developing with Django
When you want to plt.save in a for statement
When you get an error in python scraping (requests)
What to do if you don't want to use Japanese column names when using ortoolpy.logistics_network
I got an error when using Tensorboard with Pytorch
Useful operation when you want to solve all problems in multiple programming languages with Codewars
[Solution] When I try to connect to CloudSQL with GAE, I get an ImportError only when using dev_appserver.
If you want to use field names with hyphens when updating firestore data in python
What to do if you get an Undefined error when trying to use pip with pyenv
[Django] A memorandum when you want to communicate asynchronously [Python3]
[Python] If you suddenly want to create an inquiry form
Knowledge you need to know when programming competitive programming with Python2
How to not load images when using PhantomJS with Selenium
Until you edit an SVG file with AutoCAD to PNG.
Why you have to specify dtype when using keras pad_sequences
What to do when an error occurs with import _ssl
Things to keep in mind when using Python with AtCoder
When you want to use python2.x on modern Gentoo Linux
Things to keep in mind when using cgi with python.
When you want to hit a UNIX command on Python
When using optparse with iPython
I want to improve efficiency with Python even in an experimental system (4) Use ser.close () when an error is thrown using try syntax
Send using Python with Gmail
When you want to use multiple versions of the same Python library (virtual environment using venv)
When you want to replace multiple characters in a string without using regular expressions in python3 series
If you want to become a data scientist, start with Kaggle
Don't write Python if you want to speed it up with Python
When it is troublesome to copy what you built with vue