Force Content-Type or expose request.data in Flask for known content-type
You want to look at the request.form
object when dealing with urlencoded posts with normal mimetypes. In this case you have an unusual form, but here is a way to do it:
# mkreq.pyfrom urllib import urlencodeimport urllib2from base64 import b64encodecredentials = { 'username': 'test@example.com', 'password': 'password'}data = b64encode(urlencode(credentials))request = urllib2.Request("http://localhost:5000/login")request.add_data(data)request.add_header('Content-Type', 'application/gooblygop')# 'application/x-www-form-urlencoded' seems to be a default Content-Typelogin1 = urllib2.urlopen(request).read()print(login1)request2 = urllib2.Request("http://localhost:5000/login")request2.add_data(data)login2 = urllib2.urlopen(request2).read()print(login2)
You probably want to modify the login bit to check the mimetype, here is a version with minimal changes to your current setup:
@app.route('/login', methods=['POST'])def login(): error = None if request.method == 'POST': # post data: cGFzc3dvcmQ9ZGVmYXVsdCZlbWFpbD10ZXN0JTQwZXhhbXBsZS5jb20= data = b64decode(request.data) # decoded data: password=default&email=test%40example.com if not data: data = b64decode(request.form.keys()[0]) special_mimetype = request.mimetype return(special_mimetype + '\n' + data)
This is the output of the first code sample, with two requests:
bvm$ python mkreq.pyapplication/gooblygopusername=test%40example.com&password=passwordapplication/x-www-form-urlencodedusername=test%40example.com&password=password
Have you thought about using json to pass your data in the POST? Flask has built in support for passing json data. In addition, if you set the Content-Type in the headers to application/json then flask will automatically dejson the POST data for you and put it in request.json
Here is the requesting application
import urllib2import jsonif __name__ == "__main__": headers = {'Content-Type':'application/json'} post_data = {"user":"test_user"} print "Posting request" req = urllib2.Request("http://localhost:5000/login", json.dumps(post_data), headers) resp = urllib2.urlopen(req) print "Response was %s" % resp.read()
This is the Flask view
from flask import request@app.route('/login', methods=['POST']) def login(): user = request.json['user'] return user
I suggest you test using curl as well if you are using the linux terminal. Here is an example
curl -X POST -H "Content-Type:application/json" -s -d '{"user":"This is the username"}' 'localhost:5000/login'This is the username