【问题标题】:Flask with SQLite Encoding Issue带有 SQLite 编码问题的烧瓶
【发布时间】:2012-10-30 03:50:21
【问题描述】:

我有以下代码将 JSON 数据插入 SQLite 数据库:

# POST request here
if request.headers['Content-Type'] == 'application/json':
    db = get_db()
    db.execute('insert into places (lat, long, address, name) values (?, ?, ?, ?)', [request.data[0], request.data[1], request.data[2], request.data[3]])
    db.commit()

并检索该数据:

# GET request here
if request.method == 'GET':
    db = get_db()
    cur = db.execute('select * from places order by id')
    entries = [dict(id=row[0], lat=row[1], long=row[2], address=row[3], name=row[4]) for row in cur.fetchall()]
    return repr(entries)

还有我上面使用的get_db() 方法:

def get_db():
    op = _app_ctx_stack.top
    if not hasattr(top, 'sqlite_db'):
        top.sqlite_db = sqlite3.connect(app.config['DATABASE'])
    return top.sqlite_db

这是我正在执行的示例 cURL 请求:

curl -H "Content-type: application/json" -X POST http://127.0.0.1:5000/location -d '{'lat':5, 'long':10, 'address':'street', 'name':'work'}'

当尝试如下执行GET 时:curl -X GET http://127.0.0.1:5000/location,我得到:

[{'lat': u'{', 'address': u'a', 'id': 1, 'long': u'l', 'name': u't'}]

我认为这是一个编码问题。关于我应该如何存储数据以避免这种情况的任何建议?这里的问题到底是什么?

谢谢!

【问题讨论】:

    标签: python sqlite encoding flask


    【解决方案1】:

    下面的代码是您想要实现的功能的完整版本。有很多地方引起了问题。它们如下:

    卷发问题

    您使用单引号的json字符串,这是无效的json。 json 字符串必须使用双引号。正确的调用应该是:

    curl -H "Content-type: application/json" -X POST http://localhost:5000/location -d '{"lat":5, "long":10, "address":"street", "name":"work"}'
    

    当我尝试解码 json 数据时,我在代码中遇到了这个问题,因为它是无效的 json,解码最初失败。

    插入数据问题

    在您的代码中,您引用了 request.data[0],这实际上是您的 json 数据的第一个字符,恰好是 { 字符,这就是为什么您一直将其视为 lat 字段的值的原因。在下面的代码中,request.data 被引用并反序列化为 python 字典。然后我们可以通过访问每个必填字段来插入数据库行。要创建此代码中使用的数据库,您可以运行以下命令:

    echo "CREATE TABLE places (id INTEGER PRIMARY KEY, lat text, long text, address text, name  text);" | sqlite3 places.db
    

    当您访问http://127.0.0.1:5000/location 时将得到的响应是:

    [(1, u'5', u'10', u'street', u'work')]
    

    代码

    from flask import Flask, request
    import json, sqlite3
    
    app = Flask(__name__)
    @app.route('/location', methods=['GET', 'POST'])
    def hello_world():
        conn = sqlite3.connect("places.db")
        cur = conn.cursor()
        if request.method == 'GET':
            cur.execute('SELECT * FROM places ORDER BY id')
            return repr(cur.fetchall())
        else:
            d = json.loads(request.data)
            row = (d['lat'], d['long'], d['address'], d['name'])
            cur.execute("""INSERT INTO places (lat, long, address, name)
                    VALUES (?,?,?,?)""", row)
            conn.commit()
            return 'done\n'
    
    app.run(debug=True)
    

    【讨论】:

      【解决方案2】:

      你可以试试

      repr(x).decode("utf-8") where x is your value
      

      【讨论】:

      • 那行不通。存储数据以避免这种情况的最佳方法是什么?
      • 你可以在存储数据之前试试这个吗?因此,如果您想存储 x,请使用它。
      • 我在 POST 中的 get = get_db() 之前尝试过:request.data = repr(request.data).decode("utf-8"),但它仍然不起作用。这是正确的方法吗?
      • 你会推荐使用 SQLAlchemy 代替吗?
      猜你喜欢
      • 2019-01-04
      • 2021-10-17
      • 1970-01-01
      • 1970-01-01
      • 2021-09-07
      • 2012-11-18
      • 2021-10-15
      • 1970-01-01
      相关资源
      最近更新 更多