SalamalCamel SalamalCamel - 1 month ago 18
HTTP Question

Python Flask - Add POST data to sqlite database

I am sending data from a python script to the server using POST, I want to then store that data in an SQLite database. My current code returns a 500 internal server error to the client.

Here is the client script:

import requests
from random import randint

def WindSpeed():
#Creates makeshift WindSpeed data to send to server
return randint(0,20)


def Temp():
#Creates makeshift Temp data to send to server
return randint(0,20)


post_data = {'windspeed':WindSpeed(), 'temp': Temp()}
#POSTs post_data to server
r = requests.post('http://10.0.0.119', data = post_data)
print (r.text)


And here is the server script:

from flask import Flask, request, render_template, g
import json
import sqlite3 as sql


app = Flask(__name__)

def insert_readings(windspeed):
DATABASE = '/var/www/FlaskApp/FlaskApp/weather.db'
with sql.connect(DATABASE) as con:
cur = con.cursor()
cur.execute("INSERT INTO weather_readings (windspeed) VALUES (?)", (windspeed))
con.commit()

@app.route("/", methods=['GET','POST'])
def result():
if request.method == 'POST':
windspeed = request.form['windspeed']
insert_readings(windspeed)
return "Done"
else:
insert_readings(4,3) #This works
return render_template('main.html', name='GET')



if __name__ == "__main__":
app.run(debug=True)


It is worth noting that the
insert_readings
function works when called in the
else
statement and in other files. Also, the same error is returned when I tried to write to a text file.
The POST request works on its own when just returning
windspeed
so the i don't think the problem is with getting the data.

Thanks in advance.

Answer

Here you have only the windspeed key of the dict, just one value.

 if request.method == 'POST':
        windspeed = request.form['windspeed']       
        insert_readings(windspeed)
        return "Done"
else:
        insert_readings(4,3) #This works

and you tried with two values.

Try it:

if request.method == 'POST':
            value1 = request.form['windspeed']
            value2 = request.form['temp']
            insert_readings(int(value1),int(value2))
            return "Done"

Could you post more information about the error?

Comments