cannot generate log when use curl send post request - python

I am trying to test register function for my flask app.
curl -X POST -H "application/json" -d "email=12345671111#qqcom&name=test123" http://192.168.50.4:5000/register
{
"message": "\u9519\u8bef\u7684 JSON \u6570\u636e\u683c\u5f0f"
}%
The return message is very strange, and the flask log show:
"POST /register HTTP/1.1" 400 -
but if I click register button in webpage, it is normal.
192.168.50.1 - - [15/Nov/2015 13:16:49] "POST /register HTTP/1.1" 400 -
192.168.50.1 - - [15/Nov/2015 13:22:03] "OPTIONS /register HTTP/1.1" 200 -
the params is {u'fullname': u'test11828732', u'email': u'hshdshhvhd#qq.com'}
no idea for this, hope someone can help me, thanks in advance!

As the error message says, you didn't pass valid JSON data. Your curl command is incorrect: you didn't set the content type header correctly and you passed form encoded data rather than JSON data.
curl -X POST -H 'Content-Type: application/json' -d '{"email": "12345671111#qq.com", "name": "test123"}'

Related

Cherrypy logingg POST body

I'am using default cherrypy logger.
I have log every access request to my server. For GET request i have full info, like
127.0.0.1 - - [06/Jul/2021:16:10:28] "GET /test/?contract_id=228322 HTTP/1.0" 200 33
But for POST request i can't log query params or body.
127.0.0.1 - - [06/Jul/2021:13:21:03] "POST /test HTTP/1.0" 201 169
So how can i log POST query's body?
You can create tool like
def response_logging():
cherrypy.log.access_log.info(
'[{time}] {ip} "{user_agent}" {request_line} "{query_params}" "{body}" "{status}" {response}'.format(
time=datetime.now().strftime("%d/%m/%Y:%H:%M:%S"),
ip=cherrypy.request.remote.ip,
user_agent=cherrypy.request.headers["User-Agent"],
request_line=cherrypy.request.request_line,
query_params=cherrypy.request.body.request_params or "",
body=cherrypy.request.json if hasattr(cherrypy.request, "json") else "",
status=cherrypy.response.status,
response=cherrypy.response.body
)
)
cherrypy.tools.response_logging = cherrypy.Tool('on_end_request', response_logging)
print(cherrypy.request.params) # Prints params on querystring
print(cherrypy.request.headers) # Prints received headers on request
print(cherrypy.request.body) # Prints Body received

Starlette/FastApi route path components with forward slash

I have defined a route in Starlette/FastApi -
#router.post("/{part}")
def post_method(part):
return "ok"
#router.post("/{part}/{another_part}")
def another_post_method(part, another_part):
return "ok"
I have some forward slash in the path components, and I want to make the following request to access post_method
curl -X POST "http://127.0.0.1:5000/api/path%2Fpath" -H "accept: application/json" -d ""
results in the 404 error in the Starlette/Fastapi logs.
INFO: 127.0.0.1:50233 - "POST /api/path/path HTTP/1.1" 404
How to get the correct path components?
You can use Starlette built-in path convertor
#app.route("/path/{param:path}", name="path-convertor")
Response from Marcelo Trylesinski (Kludex) in fastapi gitter:
It is not allowed
Temporary solution: don't use path

Why Pocket API returns 403 Forbidden always?

I'm trying to call this line:
curl https://getpocket.com/v3/oauth/authorize --insecure -X POST -H "Content-Type: application/json" -H "X-Accept: application/json" -d "{\"consumer_key\":\"61999-492f79db0bd3292f0b4...1\",\"code\":\"c9166709-0c45-2b1f-a22f-e...r\"}"
and each time I get 403 Forbidden.
I do not know and understand the reason of that.
Does anyone knows? I tried it through Python too:
import requests
auth_params = {'consumer_key': 'key_here', 'redirect_uri': 'https://www.twitter.com/'}
tkn = requests.post('https://getpocket.com/v3/oauth/request', data=auth_params)
tkn.content
Above code gives me a code:
usr_params = {'consumer_key': 'key_here', 'code': 'code_here'}
usr = requests.post('https://getpocket.com/v3/oauth/authorize', data=usr_params)
usr.content
here I'm getting 403 too.
How can I fix that?
From Pocket Authentication API Documentation, you need to register an application to get a consumer key, then request OAuth token via :
curl -X POST \
-H 'Content-Type: application/json' \
-d '{"consumer_key":"XXXXX-XXXXXXXXXXXXXXXXXXXXXX","redirect_uri":"AppTest:authorizationFinished"}' \
https://getpocket.com/v3/oauth/request
Then the step 2 is to authorize this request token (this is the step you are missing). On a browser open the following URL with the request token you got from the previous step :
https://getpocket.com/auth/authorize?request_token=XXXXXXXX-XXXX-XXXX-XXXX-XXXX&redirect_uri=AppTest:authorizationFinished
Click on "authorize" :
Once the request token is authorized, you can call your request on https://getpocket.com/v3/oauth/authorize to convert a request token into a Pocket access token:
curl -X POST \
-H 'Content-Type: application/json' \
-d '{"consumer_key":"XXXXX-XXXXXXXXXXXXXXXXXXX","code":"XXXXXXXXX-XXXX-XXXX-XXXX-XXXXX"}' \
https://getpocket.com/v3/oauth/authorize
The consumer key is the one you got when you created the app on Pocket and the request token the one generated from v3/oauth/request endpoint
Then you get as expected :
{ "access_token":"5678defg-5678-defg-5678-defg56", "username":"pocketuser" }

POST service parameter - FLASK [duplicate]

This question already has answers here:
How to get POSTed JSON in Flask?
(13 answers)
Closed 6 years ago.
This is what i get
b'{"data": "https://files.slack.com/files-pri/T03HPFD2P-F2RU2S4R0/scher7-om-14.52.47.png"}'
when i print my request data from a flask POST web service.
print(request.data)
But when i do url = request.form.get('data', None)
I get value of url variable None
Why?
Your problem is that you sent the request as follows:
req = requests.post(url, data=json.dumps(payload), headers={'Content-Type': 'application/json'})
When sending json data, you should format the request in requests with the json parameter as follows:
req = requests.post(url, json=payload)
Further, in your flask app, you can access submitted json data via request.json
Because the content type is application/json -- it will not appear in request.form -- Data will appear in request.form when a request is received with an appropriate content type such as multipart/form-data
What's the Content-Type header in your POST request?
As described in its docs: request.form is a dict contains data parsed from POST or PUT form, while request.data contains the incoming request data as string in case it came with a mimetype Flask does not handle.
For the following code:
# -*- coding: utf-8 -*-
from flask import Flask, request
app = Flask("Test")
#app.route("/ping", methods=['POST'])
def ping():
print "Data: ", request.data
print "Form: ", request.form
return "pong"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7070, debug=False)
Curl with default Content-Type, there's no data in request.data:
curl -X POST -H "Content-Type: a/b" --data 'data=https://files.slack.com/files-pri/T03HPFD2P-F2RU2S4R0/schermafbeelding-2016-01-27-om-14.52.47.png' http://localhost:7070/ping
Output:
* Running on http://0.0.0.0:7070/ (Press CTRL+C to quit)
Data:
Form: ImmutableMultiDict([('data', u'https://files.slack.com/files-pri/T03HPFD2P-F2RU2S4R0/schermafbeelding-2016-01-27-om-14.52.47.png')])
127.0.0.1 - - [20/Oct/2016 21:40:41] "POST /ping HTTP/1.1" 200 -
But curl with a unknown Content-Type header, there's no data in request.form:
curl -X POST -H "Content-Type: a/b" --data 'data=https://files.slack.com/files-pri/T03HPFD2P-F2RU2S4R0/schermafbeelding-2016-01-27-om-14.52.47.png' http://localhost:7070/ping
Output:
Data: data=https://files.slack.com/files-pri/T03HPFD2P-F2RU2S4R0/schermafbeelding-2016-01-27-om-14.52.47.png
Form: ImmutableMultiDict([])
127.0.0.1 - - [20/Oct/2016 21:43:52] "POST /ping HTTP/1.1" 200 -
So if you want your form data in request.form, make sure the Content-Type is the one of those Flask can handle.

"CSRF token missing" when using curl with a Flask app

I am trying to submit a form on a Flask app using curl. Unfortunately, I keep running into the "CSRF token missing" error.
I tried:
curl -X POST --form csrf_token=token --form data=#file.txt --form submit=submit {url} -v
I used a csrf_token from the app while I had it open in a browser. I also looked at https://flask-wtf.readthedocs.org/en/latest/csrf.html and tried to set X-CSRFToken in the header but still got the same error. Any suggestions for what is the correct way to use curl to feed the token to the flask app?
The problem is that you just sending token and flask cannot get your session which lives in browser cookie. So if you wish to access your view via curl it's not enough to pass token value within POST request, you have to attach cookie to. You can write cookie to local file with command:
curl -c /path/to/cookiefile {url}
Then modify it and send POST request to your server with attached cookie and token:
curl -b /path/to/cookiefile -X POST --form csrf_token=token --form data=#file.txt --form submit=submit {url} -v

Categories