Python Forum
python3 + Flask + SQLite = HTTP 400
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
python3 + Flask + SQLite = HTTP 400
#1
I'm still learning python so I could be missing something obvious. I've followed a bunch of different tutorials but nothing seems to be showing me how to fix my specific issue.

I'm trying to POST data from main.py (API caller) to hello.py (API server). Expected result would be hitting 127.0.0.1:8080/message and seeing the newly added POST data. In this case the message "You did it!" would be the line displayed.

What I'm seeing from hello.py is this error: 127.0.0.1 - - [29/Jan/2018 09:29:38] "POST /message/new HTTP/1.1" 400 -

Everything can be viewed on Git.


main.py
import requests, json


desc = "You did it!"


headers = {'Content-Type': 'application/json'}
url = "http://127.0.0.1:8080/message/new"
body = {'message': desc}

r = requests.post(
    headers=headers,
    url=url,
    data=body
)
hello.py
from flask import Flask, jsonify, request, g
import sqlite3


app = Flask(__name__)


conn = sqlite3.connect('TheBats.db')
c = conn.cursor()


@app.route('/')
def hey_there():
    return 'Who are you? I\'m Batman'


@app.route('/message')
def get_message():
    conn = sqlite3.connect('TheBats.db')
    cur = conn.cursor()
    cur.execute('SELECT * FROM batquote')
    entries = cur.fetchall()
    return jsonify(entries)


@app.route('/message/new', methods=['POST'])
def post_message():
    batquote = request.json['message']
    conn = sqlite3.connect('TheBats.db')
    cur = conn.cursor()
    cur.execute('INSERT INTO batquote (message) VALUES(?)', (batquote,))
    conn.commit()
    return cur.lastrowid


#@app.route('/message/<int>')
#def get_messageID():
#    return jsonify(placeholder2)


if __name__ == '__main__':
    app.run(debug=True, port=8080)
Reply
#2
Git link used in original post is out-of-date. Updated: https://github.com/thesupertoy/SideWork
Reply
#3
Does it work without the database? Is there any other output? Or just the one line saying the request was invalid?
Reply
#4
It does not work without the database either. Same response.

This is the full output.

* Restarting with stat
* Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
127.0.0.1 - - [29/Jan/2018 13:44:06] "POST /marco HTTP/1.1" 400 -

Just tested with Postman and I'm able to update the database.

{
"message": "Batman is forever."
}

But I'm still not able to pass data from my python script. Error HTTP 400.
Reply
#5
http://flask.pocoo.org/docs/0.12/quickst...est-object Wrote:
@app.route('/login', methods=['POST', 'GET'])
def login():
    error = None
    if request.method == 'POST':
        if valid_login(request.form['username'],
                       request.form['password']):
            return log_the_user_in(request.form['username'])
        else:
            error = 'Invalid username/password'
    # the code below is executed if the request method
    # was GET or the credentials were invalid
    return render_template('login.html', error=error)
What happens if the key does not exist in the form attribute? In that case a special KeyError is raised. You can catch it like a standard KeyError but if you don’t do that, a HTTP 400 Bad Request error page is shown instead. So for many situations you don’t have to deal with that problem.

Emphasis mine. So request.json doesn't have what you think it does. Try printing it out, and seeing what's in there.

Looking at the docs for requests (http://docs.python-requests.org/en/maste...t-requests), it looks like you might not even be sending json data, which could be the root cause of the issue. If you do json=body instead of data=body, that could fix it. Or, you could continue using requests how you are, and change your flask code to use request.form instead of request.json.
Reply
#6
It's working! Thanks for your help.

I had to make 2 changes:
In main.py changed line 9 to read body = ({'message': desc}) #notice the addition parentheses.
In main.py changed line 14 to read json=body

I'm still getting errors in my debugger though. But I'm not too worried about that at the moment.

* Restarting with stat
* Debugger is active!
* Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
127.0.0.1 - - [30/Jan/2018 08:11:47] "POST /message/new HTTP/1.1" 500 -
Traceback (most recent call last):
File "C:\Users\z017641\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\z017641\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\z017641\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\z017641\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Users\z017641\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\z017641\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 1615, in full_dispatch_request
return self.finalize_request(rv)
File "C:\Users\z017641\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 1630, in finalize_request
response = self.make_response(rv)
File "C:\Users\z017641\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 1740, in make_response
rv = self.response_class.force_type(rv, request.environ)
File "C:\Users\z017641\AppData\Local\Programs\Python\Python36-32\lib\site-packages\werkzeug\wrappers.py", line 921, in force_type
response = BaseResponse(*_run_wsgi_app(response, environ))
File "C:\Users\z017641\AppData\Local\Programs\Python\Python36-32\lib\site-packages\werkzeug\wrappers.py", line 59, in _run_wsgi_app
return _run_wsgi_app(*args)
File "C:\Users\z017641\AppData\Local\Programs\Python\Python36-32\lib\site-packages\werkzeug\test.py", line 923, in run_wsgi_app
app_rv = app(environ, start_response)
TypeError: 'int' object is not callable
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  flask sqlite jinja accessing and updating database help pascale 5 4,144 Feb-11-2019, 03:49 PM
Last Post: pascale
  Flask return http status code 200 but web browser not recive supernoobs 2 10,682 Dec-29-2018, 09:27 PM
Last Post: Unisoftdev

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020