【问题标题】:Python Flask - Add POST data to sqlite databasePython Flask - 将 POST 数据添加到 sqlite 数据库
【发布时间】:2017-03-07 07:41:26
【问题描述】:

我正在使用 POST 从 python 脚本向服务器发送数据,然后我想将该数据存储在 SQLite 数据库中。我当前的代码向客户端返回 500 内部服务器错误。

这是客户端脚本:

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)

这是服务器脚本:

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)

值得注意的是,insert_readings 函数在else 语句和其他文件中调用时有效。此外,当我尝试写入文本文件时,也会返回相同的错误。 POST 请求仅在返回 windspeed 时自行工作,所以我认为问题不在于获取数据。

提前致谢。

【问题讨论】:

    标签: python sqlite http flask server


    【解决方案1】:

    这里只有字典的风速键,只有一个值。

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

    你尝试了两个值。

    试试看:

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

    您能否发布有关该错误的更多信息?

    【讨论】:

    • 谢谢,我错过了。事实证明,主要问题是数据库文件的权限,当我使用sudo 运行脚本时,它起作用了。但服务器没有写入权限。
    【解决方案2】:

    客户端脚本没有问题,服务器脚本看起来不错。 500 内部服务器错误是一个非常广泛的错误消息,如果不测试设置中的脚本就很难判断问题。您能否提供服务器设置/配置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-25
      • 2020-10-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多