flask API для скручивания - PullRequest
       42

flask API для скручивания

0 голосов
/ 06 февраля 2020

Я написал flask API как:

@app.route('/train/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
    content = request.get_json(silent=True)

При использовании библиотеки python запросов для получения кода POST

import requests

req = requests.Request('POST',myip+'train/add_message/1234',json=myjson)
prepared = req.prepare()

def pretty_print_POST(req):
    """
    At this point it is completely built and ready
    to be fired; it is "prepared".

    However pay attention at the formatting used in 
    this function because it is programmed to be pretty 
    printed and may differ from the actual request.
    """
    print('{}\n{}\r\n{}\r\n\r\n{}'.format(
        '-----------START-----------',
        req.method + ' ' + req.url,
        '\r\n'.join('{}: {}'.format(k, v) for k, v in req.headers.items()),
        req.body,
    ))

pretty_print_POST(prepared)

Это вывод

----------- START -----------

POST {ip}/train/add_message/1234
Content-Length: 347
Content-Type: application/json

b'{"type": 2, "project_id": "115", "data": [{"label150": {"example1": {"key": "hi11", "key2": "$key2"}, "example2": {"key": "hi12", "key2": "$key2"}, "example3": {"key": "hi3", "key2": "$key2"}}, "label100": {"example1": {"key": "bye1", "key2": "$key2"}, "example2": {"key": "bye2", "key2": "$key2"}, "example3": {"key": "bye3", "key2": "$key2"}}}]}'
1

как я могу преобразовать это в команду curl. Я попробовал это, но получил ошибку

curl --location --request POST myip+'/train/add__message/1234' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-raw '{
    "type":1,
    "project_id":"313",
    "data":[{"label5":{
            "example1":{
                "key":"hi11",
                "key2":"$key2"
            },
            "example2":{
                "key":"hi12",
                "key2":"$key2"
            },
            "example3":{
                "key":"hi3",
                "key2":"$key2"
            }
        }
            }]
}'

This is the error I got:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>405 Method Not Allowed</title>
<h1>Method Not Allowed</h1>
<p>The method is not allowed for the requested URL.</p>

1 Ответ

0 голосов
/ 06 февраля 2020

Попробуйте также добавить заголовок Accept.

curl --location --request POST myip+'/train/add__message/1234' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Accept: application/x-www-form-urlencoded' \
--data-raw '{
    "type":1,
    "project_id":"313",
    "data":[{"label5":{
            "example1":{
                "key":"hi11",
                "key2":"$key2"
            },
            "example2":{
                "key":"hi12",
                "key2":"$key2"
            },
            "example3":{
                "key":"hi3",
                "key2":"$key2"
            }
        }
            }]
}'

...